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

1.347   ! brouard     1: /* $Id: imach.c,v 1.346 2022/09/16 13:52:36 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.347   ! brouard     4:   Revision 1.346  2022/09/16 13:52:36  brouard
        !             5:   * src/imach.c (Module): 0.99r41 Was an error when product of timevarying and fixed. Using FixedV[of name] now. Thank you  Feinuo
        !             6: 
1.346     brouard     7:   Revision 1.345  2022/09/16 13:40:11  brouard
                      8:   Summary: Version 0.99r41
                      9: 
                     10:   * imach.c (Module): 0.99r41 Was an error when product of timevarying and fixed. Using FixedV[of name] now. Thank you  Feinuo
                     11: 
1.345     brouard    12:   Revision 1.344  2022/09/14 19:33:30  brouard
                     13:   Summary: version 0.99r40
                     14: 
                     15:   * imach.c (Module): Fixing names of variables in T_ (thanks to Feinuo)
                     16: 
1.344     brouard    17:   Revision 1.343  2022/09/14 14:22:16  brouard
                     18:   Summary: version 0.99r39
                     19: 
                     20:   * imach.c (Module): Version 0.99r39 with colored dummy covariates
                     21:   (fixed or time varying), using new last columns of
                     22:   ILK_parameter.txt file.
                     23: 
1.343     brouard    24:   Revision 1.342  2022/09/11 19:54:09  brouard
                     25:   Summary: 0.99r38
                     26: 
                     27:   * imach.c (Module): Adding timevarying products of any kinds,
                     28:   should work before shifting cotvar from ncovcol+nqv columns in
                     29:   order to have a correspondance between the column of cotvar and
                     30:   the id of column.
                     31:   (Module): Some cleaning and adding covariates in ILK.txt
                     32: 
1.342     brouard    33:   Revision 1.341  2022/09/11 07:58:42  brouard
                     34:   Summary: Version 0.99r38
                     35: 
                     36:   After adding change in cotvar.
                     37: 
1.341     brouard    38:   Revision 1.340  2022/09/11 07:53:11  brouard
                     39:   Summary: Version imach 0.99r37
                     40: 
                     41:   * imach.c (Module): Adding timevarying products of any kinds,
                     42:   should work before shifting cotvar from ncovcol+nqv columns in
                     43:   order to have a correspondance between the column of cotvar and
                     44:   the id of column.
                     45: 
1.340     brouard    46:   Revision 1.339  2022/09/09 17:55:22  brouard
                     47:   Summary: version 0.99r37
                     48: 
                     49:   * imach.c (Module): Many improvements for fixing products of fixed
                     50:   timevarying as well as fixed * fixed, and test with quantitative
                     51:   covariate.
                     52: 
1.339     brouard    53:   Revision 1.338  2022/09/04 17:40:33  brouard
                     54:   Summary: 0.99r36
                     55: 
                     56:   * imach.c (Module): Now the easy runs i.e. without result or
                     57:   model=1+age only did not work. The defautl combination should be 1
                     58:   and not 0 because everything hasn't been tranformed yet.
                     59: 
1.338     brouard    60:   Revision 1.337  2022/09/02 14:26:02  brouard
                     61:   Summary: version 0.99r35
                     62: 
                     63:   * src/imach.c: Version 0.99r35 because it outputs same results with
                     64:   1+age+V1+V1*age for females and 1+age for females only
                     65:   (education=1 noweight)
                     66: 
1.337     brouard    67:   Revision 1.336  2022/08/31 09:52:36  brouard
                     68:   *** empty log message ***
                     69: 
1.336     brouard    70:   Revision 1.335  2022/08/31 08:23:16  brouard
                     71:   Summary: improvements...
                     72: 
1.335     brouard    73:   Revision 1.334  2022/08/25 09:08:41  brouard
                     74:   Summary: In progress for quantitative
                     75: 
1.334     brouard    76:   Revision 1.333  2022/08/21 09:10:30  brouard
                     77:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                     78:   reassigning covariates: my first idea was that people will always
                     79:   use the first covariate V1 into the model but in fact they are
                     80:   producing data with many covariates and can use an equation model
                     81:   with some of the covariate; it means that in a model V2+V3 instead
                     82:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                     83:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                     84:   the equation model is restricted to two variables only (V2, V3)
                     85:   and the combination for V2 should be codtabm(k,1) instead of
                     86:   (codtabm(k,2), and the code should be
                     87:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                     88:   made. All of these should be simplified once a day like we did in
                     89:   hpxij() for example by using precov[nres] which is computed in
                     90:   decoderesult for each nres of each resultline. Loop should be done
                     91:   on the equation model globally by distinguishing only product with
                     92:   age (which are changing with age) and no more on type of
                     93:   covariates, single dummies, single covariates.
                     94: 
1.333     brouard    95:   Revision 1.332  2022/08/21 09:06:25  brouard
                     96:   Summary: Version 0.99r33
                     97: 
                     98:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                     99:   reassigning covariates: my first idea was that people will always
                    100:   use the first covariate V1 into the model but in fact they are
                    101:   producing data with many covariates and can use an equation model
                    102:   with some of the covariate; it means that in a model V2+V3 instead
                    103:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                    104:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                    105:   the equation model is restricted to two variables only (V2, V3)
                    106:   and the combination for V2 should be codtabm(k,1) instead of
                    107:   (codtabm(k,2), and the code should be
                    108:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                    109:   made. All of these should be simplified once a day like we did in
                    110:   hpxij() for example by using precov[nres] which is computed in
                    111:   decoderesult for each nres of each resultline. Loop should be done
                    112:   on the equation model globally by distinguishing only product with
                    113:   age (which are changing with age) and no more on type of
                    114:   covariates, single dummies, single covariates.
                    115: 
1.332     brouard   116:   Revision 1.331  2022/08/07 05:40:09  brouard
                    117:   *** empty log message ***
                    118: 
1.331     brouard   119:   Revision 1.330  2022/08/06 07:18:25  brouard
                    120:   Summary: last 0.99r31
                    121: 
                    122:   *  imach.c (Module): Version of imach using partly decoderesult to rebuild xpxij function
                    123: 
1.330     brouard   124:   Revision 1.329  2022/08/03 17:29:54  brouard
                    125:   *  imach.c (Module): Many errors in graphs fixed with Vn*age covariates.
                    126: 
1.329     brouard   127:   Revision 1.328  2022/07/27 17:40:48  brouard
                    128:   Summary: valgrind bug fixed by initializing to zero DummyV as well as Tage
                    129: 
1.328     brouard   130:   Revision 1.327  2022/07/27 14:47:35  brouard
                    131:   Summary: Still a problem for one-step probabilities in case of quantitative variables
                    132: 
1.327     brouard   133:   Revision 1.326  2022/07/26 17:33:55  brouard
                    134:   Summary: some test with nres=1
                    135: 
1.326     brouard   136:   Revision 1.325  2022/07/25 14:27:23  brouard
                    137:   Summary: r30
                    138: 
                    139:   * imach.c (Module): Error cptcovn instead of nsd in bmij (was
                    140:   coredumped, revealed by Feiuno, thank you.
                    141: 
1.325     brouard   142:   Revision 1.324  2022/07/23 17:44:26  brouard
                    143:   *** empty log message ***
                    144: 
1.324     brouard   145:   Revision 1.323  2022/07/22 12:30:08  brouard
                    146:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    147: 
1.323     brouard   148:   Revision 1.322  2022/07/22 12:27:48  brouard
                    149:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    150: 
1.322     brouard   151:   Revision 1.321  2022/07/22 12:04:24  brouard
                    152:   Summary: r28
                    153: 
                    154:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    155: 
1.321     brouard   156:   Revision 1.320  2022/06/02 05:10:11  brouard
                    157:   *** empty log message ***
                    158: 
1.320     brouard   159:   Revision 1.319  2022/06/02 04:45:11  brouard
                    160:   * imach.c (Module): Adding the Wald tests from the log to the main
                    161:   htm for better display of the maximum likelihood estimators.
                    162: 
1.319     brouard   163:   Revision 1.318  2022/05/24 08:10:59  brouard
                    164:   * imach.c (Module): Some attempts to find a bug of wrong estimates
                    165:   of confidencce intervals with product in the equation modelC
                    166: 
1.318     brouard   167:   Revision 1.317  2022/05/15 15:06:23  brouard
                    168:   * imach.c (Module):  Some minor improvements
                    169: 
1.317     brouard   170:   Revision 1.316  2022/05/11 15:11:31  brouard
                    171:   Summary: r27
                    172: 
1.316     brouard   173:   Revision 1.315  2022/05/11 15:06:32  brouard
                    174:   *** empty log message ***
                    175: 
1.315     brouard   176:   Revision 1.314  2022/04/13 17:43:09  brouard
                    177:   * imach.c (Module): Adding link to text data files
                    178: 
1.314     brouard   179:   Revision 1.313  2022/04/11 15:57:42  brouard
                    180:   * imach.c (Module): Error in rewriting the 'r' file with yearsfproj or yearsbproj fixed
                    181: 
1.313     brouard   182:   Revision 1.312  2022/04/05 21:24:39  brouard
                    183:   *** empty log message ***
                    184: 
1.312     brouard   185:   Revision 1.311  2022/04/05 21:03:51  brouard
                    186:   Summary: Fixed quantitative covariates
                    187: 
                    188:          Fixed covariates (dummy or quantitative)
                    189:        with missing values have never been allowed but are ERRORS and
                    190:        program quits. Standard deviations of fixed covariates were
                    191:        wrongly computed. Mean and standard deviations of time varying
                    192:        covariates are still not computed.
                    193: 
1.311     brouard   194:   Revision 1.310  2022/03/17 08:45:53  brouard
                    195:   Summary: 99r25
                    196: 
                    197:   Improving detection of errors: result lines should be compatible with
                    198:   the model.
                    199: 
1.310     brouard   200:   Revision 1.309  2021/05/20 12:39:14  brouard
                    201:   Summary: Version 0.99r24
                    202: 
1.309     brouard   203:   Revision 1.308  2021/03/31 13:11:57  brouard
                    204:   Summary: Version 0.99r23
                    205: 
                    206: 
                    207:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
                    208: 
1.308     brouard   209:   Revision 1.307  2021/03/08 18:11:32  brouard
                    210:   Summary: 0.99r22 fixed bug on result:
                    211: 
1.307     brouard   212:   Revision 1.306  2021/02/20 15:44:02  brouard
                    213:   Summary: Version 0.99r21
                    214: 
                    215:   * imach.c (Module): Fix bug on quitting after result lines!
                    216:   (Module): Version 0.99r21
                    217: 
1.306     brouard   218:   Revision 1.305  2021/02/20 15:28:30  brouard
                    219:   * imach.c (Module): Fix bug on quitting after result lines!
                    220: 
1.305     brouard   221:   Revision 1.304  2021/02/12 11:34:20  brouard
                    222:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
                    223: 
1.304     brouard   224:   Revision 1.303  2021/02/11 19:50:15  brouard
                    225:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
                    226: 
1.303     brouard   227:   Revision 1.302  2020/02/22 21:00:05  brouard
                    228:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
                    229:   and life table from the data without any state)
                    230: 
1.302     brouard   231:   Revision 1.301  2019/06/04 13:51:20  brouard
                    232:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                    233: 
1.301     brouard   234:   Revision 1.300  2019/05/22 19:09:45  brouard
                    235:   Summary: version 0.99r19 of May 2019
                    236: 
1.300     brouard   237:   Revision 1.299  2019/05/22 18:37:08  brouard
                    238:   Summary: Cleaned 0.99r19
                    239: 
1.299     brouard   240:   Revision 1.298  2019/05/22 18:19:56  brouard
                    241:   *** empty log message ***
                    242: 
1.298     brouard   243:   Revision 1.297  2019/05/22 17:56:10  brouard
                    244:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                    245: 
1.297     brouard   246:   Revision 1.296  2019/05/20 13:03:18  brouard
                    247:   Summary: Projection syntax simplified
                    248: 
                    249: 
                    250:   We can now start projections, forward or backward, from the mean date
                    251:   of inteviews up to or down to a number of years of projection:
                    252:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                    253:   or
                    254:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                    255:   or
                    256:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                    257:   or
                    258:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                    259: 
1.296     brouard   260:   Revision 1.295  2019/05/18 09:52:50  brouard
                    261:   Summary: doxygen tex bug
                    262: 
1.295     brouard   263:   Revision 1.294  2019/05/16 14:54:33  brouard
                    264:   Summary: There was some wrong lines added
                    265: 
1.294     brouard   266:   Revision 1.293  2019/05/09 15:17:34  brouard
                    267:   *** empty log message ***
                    268: 
1.293     brouard   269:   Revision 1.292  2019/05/09 14:17:20  brouard
                    270:   Summary: Some updates
                    271: 
1.292     brouard   272:   Revision 1.291  2019/05/09 13:44:18  brouard
                    273:   Summary: Before ncovmax
                    274: 
1.291     brouard   275:   Revision 1.290  2019/05/09 13:39:37  brouard
                    276:   Summary: 0.99r18 unlimited number of individuals
                    277: 
                    278:   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.
                    279: 
1.290     brouard   280:   Revision 1.289  2018/12/13 09:16:26  brouard
                    281:   Summary: Bug for young ages (<-30) will be in r17
                    282: 
1.289     brouard   283:   Revision 1.288  2018/05/02 20:58:27  brouard
                    284:   Summary: Some bugs fixed
                    285: 
1.288     brouard   286:   Revision 1.287  2018/05/01 17:57:25  brouard
                    287:   Summary: Bug fixed by providing frequencies only for non missing covariates
                    288: 
1.287     brouard   289:   Revision 1.286  2018/04/27 14:27:04  brouard
                    290:   Summary: some minor bugs
                    291: 
1.286     brouard   292:   Revision 1.285  2018/04/21 21:02:16  brouard
                    293:   Summary: Some bugs fixed, valgrind tested
                    294: 
1.285     brouard   295:   Revision 1.284  2018/04/20 05:22:13  brouard
                    296:   Summary: Computing mean and stdeviation of fixed quantitative variables
                    297: 
1.284     brouard   298:   Revision 1.283  2018/04/19 14:49:16  brouard
                    299:   Summary: Some minor bugs fixed
                    300: 
1.283     brouard   301:   Revision 1.282  2018/02/27 22:50:02  brouard
                    302:   *** empty log message ***
                    303: 
1.282     brouard   304:   Revision 1.281  2018/02/27 19:25:23  brouard
                    305:   Summary: Adding second argument for quitting
                    306: 
1.281     brouard   307:   Revision 1.280  2018/02/21 07:58:13  brouard
                    308:   Summary: 0.99r15
                    309: 
                    310:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                    311: 
1.280     brouard   312:   Revision 1.279  2017/07/20 13:35:01  brouard
                    313:   Summary: temporary working
                    314: 
1.279     brouard   315:   Revision 1.278  2017/07/19 14:09:02  brouard
                    316:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                    317: 
1.278     brouard   318:   Revision 1.277  2017/07/17 08:53:49  brouard
                    319:   Summary: BOM files can be read now
                    320: 
1.277     brouard   321:   Revision 1.276  2017/06/30 15:48:31  brouard
                    322:   Summary: Graphs improvements
                    323: 
1.276     brouard   324:   Revision 1.275  2017/06/30 13:39:33  brouard
                    325:   Summary: Saito's color
                    326: 
1.275     brouard   327:   Revision 1.274  2017/06/29 09:47:08  brouard
                    328:   Summary: Version 0.99r14
                    329: 
1.274     brouard   330:   Revision 1.273  2017/06/27 11:06:02  brouard
                    331:   Summary: More documentation on projections
                    332: 
1.273     brouard   333:   Revision 1.272  2017/06/27 10:22:40  brouard
                    334:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    335: 
1.272     brouard   336:   Revision 1.271  2017/06/27 10:17:50  brouard
                    337:   Summary: Some bug with rint
                    338: 
1.271     brouard   339:   Revision 1.270  2017/05/24 05:45:29  brouard
                    340:   *** empty log message ***
                    341: 
1.270     brouard   342:   Revision 1.269  2017/05/23 08:39:25  brouard
                    343:   Summary: Code into subroutine, cleanings
                    344: 
1.269     brouard   345:   Revision 1.268  2017/05/18 20:09:32  brouard
                    346:   Summary: backprojection and confidence intervals of backprevalence
                    347: 
1.268     brouard   348:   Revision 1.267  2017/05/13 10:25:05  brouard
                    349:   Summary: temporary save for backprojection
                    350: 
1.267     brouard   351:   Revision 1.266  2017/05/13 07:26:12  brouard
                    352:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    353: 
1.266     brouard   354:   Revision 1.265  2017/04/26 16:22:11  brouard
                    355:   Summary: imach 0.99r13 Some bugs fixed
                    356: 
1.265     brouard   357:   Revision 1.264  2017/04/26 06:01:29  brouard
                    358:   Summary: Labels in graphs
                    359: 
1.264     brouard   360:   Revision 1.263  2017/04/24 15:23:15  brouard
                    361:   Summary: to save
                    362: 
1.263     brouard   363:   Revision 1.262  2017/04/18 16:48:12  brouard
                    364:   *** empty log message ***
                    365: 
1.262     brouard   366:   Revision 1.261  2017/04/05 10:14:09  brouard
                    367:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    368: 
1.261     brouard   369:   Revision 1.260  2017/04/04 17:46:59  brouard
                    370:   Summary: Gnuplot indexations fixed (humm)
                    371: 
1.260     brouard   372:   Revision 1.259  2017/04/04 13:01:16  brouard
                    373:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    374: 
1.259     brouard   375:   Revision 1.258  2017/04/03 10:17:47  brouard
                    376:   Summary: Version 0.99r12
                    377: 
                    378:   Some cleanings, conformed with updated documentation.
                    379: 
1.258     brouard   380:   Revision 1.257  2017/03/29 16:53:30  brouard
                    381:   Summary: Temp
                    382: 
1.257     brouard   383:   Revision 1.256  2017/03/27 05:50:23  brouard
                    384:   Summary: Temporary
                    385: 
1.256     brouard   386:   Revision 1.255  2017/03/08 16:02:28  brouard
                    387:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    388: 
1.255     brouard   389:   Revision 1.254  2017/03/08 07:13:00  brouard
                    390:   Summary: Fixing data parameter line
                    391: 
1.254     brouard   392:   Revision 1.253  2016/12/15 11:59:41  brouard
                    393:   Summary: 0.99 in progress
                    394: 
1.253     brouard   395:   Revision 1.252  2016/09/15 21:15:37  brouard
                    396:   *** empty log message ***
                    397: 
1.252     brouard   398:   Revision 1.251  2016/09/15 15:01:13  brouard
                    399:   Summary: not working
                    400: 
1.251     brouard   401:   Revision 1.250  2016/09/08 16:07:27  brouard
                    402:   Summary: continue
                    403: 
1.250     brouard   404:   Revision 1.249  2016/09/07 17:14:18  brouard
                    405:   Summary: Starting values from frequencies
                    406: 
1.249     brouard   407:   Revision 1.248  2016/09/07 14:10:18  brouard
                    408:   *** empty log message ***
                    409: 
1.248     brouard   410:   Revision 1.247  2016/09/02 11:11:21  brouard
                    411:   *** empty log message ***
                    412: 
1.247     brouard   413:   Revision 1.246  2016/09/02 08:49:22  brouard
                    414:   *** empty log message ***
                    415: 
1.246     brouard   416:   Revision 1.245  2016/09/02 07:25:01  brouard
                    417:   *** empty log message ***
                    418: 
1.245     brouard   419:   Revision 1.244  2016/09/02 07:17:34  brouard
                    420:   *** empty log message ***
                    421: 
1.244     brouard   422:   Revision 1.243  2016/09/02 06:45:35  brouard
                    423:   *** empty log message ***
                    424: 
1.243     brouard   425:   Revision 1.242  2016/08/30 15:01:20  brouard
                    426:   Summary: Fixing a lots
                    427: 
1.242     brouard   428:   Revision 1.241  2016/08/29 17:17:25  brouard
                    429:   Summary: gnuplot problem in Back projection to fix
                    430: 
1.241     brouard   431:   Revision 1.240  2016/08/29 07:53:18  brouard
                    432:   Summary: Better
                    433: 
1.240     brouard   434:   Revision 1.239  2016/08/26 15:51:03  brouard
                    435:   Summary: Improvement in Powell output in order to copy and paste
                    436: 
                    437:   Author:
                    438: 
1.239     brouard   439:   Revision 1.238  2016/08/26 14:23:35  brouard
                    440:   Summary: Starting tests of 0.99
                    441: 
1.238     brouard   442:   Revision 1.237  2016/08/26 09:20:19  brouard
                    443:   Summary: to valgrind
                    444: 
1.237     brouard   445:   Revision 1.236  2016/08/25 10:50:18  brouard
                    446:   *** empty log message ***
                    447: 
1.236     brouard   448:   Revision 1.235  2016/08/25 06:59:23  brouard
                    449:   *** empty log message ***
                    450: 
1.235     brouard   451:   Revision 1.234  2016/08/23 16:51:20  brouard
                    452:   *** empty log message ***
                    453: 
1.234     brouard   454:   Revision 1.233  2016/08/23 07:40:50  brouard
                    455:   Summary: not working
                    456: 
1.233     brouard   457:   Revision 1.232  2016/08/22 14:20:21  brouard
                    458:   Summary: not working
                    459: 
1.232     brouard   460:   Revision 1.231  2016/08/22 07:17:15  brouard
                    461:   Summary: not working
                    462: 
1.231     brouard   463:   Revision 1.230  2016/08/22 06:55:53  brouard
                    464:   Summary: Not working
                    465: 
1.230     brouard   466:   Revision 1.229  2016/07/23 09:45:53  brouard
                    467:   Summary: Completing for func too
                    468: 
1.229     brouard   469:   Revision 1.228  2016/07/22 17:45:30  brouard
                    470:   Summary: Fixing some arrays, still debugging
                    471: 
1.227     brouard   472:   Revision 1.226  2016/07/12 18:42:34  brouard
                    473:   Summary: temp
                    474: 
1.226     brouard   475:   Revision 1.225  2016/07/12 08:40:03  brouard
                    476:   Summary: saving but not running
                    477: 
1.225     brouard   478:   Revision 1.224  2016/07/01 13:16:01  brouard
                    479:   Summary: Fixes
                    480: 
1.224     brouard   481:   Revision 1.223  2016/02/19 09:23:35  brouard
                    482:   Summary: temporary
                    483: 
1.223     brouard   484:   Revision 1.222  2016/02/17 08:14:50  brouard
                    485:   Summary: Probably last 0.98 stable version 0.98r6
                    486: 
1.222     brouard   487:   Revision 1.221  2016/02/15 23:35:36  brouard
                    488:   Summary: minor bug
                    489: 
1.220     brouard   490:   Revision 1.219  2016/02/15 00:48:12  brouard
                    491:   *** empty log message ***
                    492: 
1.219     brouard   493:   Revision 1.218  2016/02/12 11:29:23  brouard
                    494:   Summary: 0.99 Back projections
                    495: 
1.218     brouard   496:   Revision 1.217  2015/12/23 17:18:31  brouard
                    497:   Summary: Experimental backcast
                    498: 
1.217     brouard   499:   Revision 1.216  2015/12/18 17:32:11  brouard
                    500:   Summary: 0.98r4 Warning and status=-2
                    501: 
                    502:   Version 0.98r4 is now:
                    503:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    504:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    505:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    506: 
1.216     brouard   507:   Revision 1.215  2015/12/16 08:52:24  brouard
                    508:   Summary: 0.98r4 working
                    509: 
1.215     brouard   510:   Revision 1.214  2015/12/16 06:57:54  brouard
                    511:   Summary: temporary not working
                    512: 
1.214     brouard   513:   Revision 1.213  2015/12/11 18:22:17  brouard
                    514:   Summary: 0.98r4
                    515: 
1.213     brouard   516:   Revision 1.212  2015/11/21 12:47:24  brouard
                    517:   Summary: minor typo
                    518: 
1.212     brouard   519:   Revision 1.211  2015/11/21 12:41:11  brouard
                    520:   Summary: 0.98r3 with some graph of projected cross-sectional
                    521: 
                    522:   Author: Nicolas Brouard
                    523: 
1.211     brouard   524:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   525:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   526:   Summary: Adding ftolpl parameter
                    527:   Author: N Brouard
                    528: 
                    529:   We had difficulties to get smoothed confidence intervals. It was due
                    530:   to the period prevalence which wasn't computed accurately. The inner
                    531:   parameter ftolpl is now an outer parameter of the .imach parameter
                    532:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    533:   computation are long.
                    534: 
1.209     brouard   535:   Revision 1.208  2015/11/17 14:31:57  brouard
                    536:   Summary: temporary
                    537: 
1.208     brouard   538:   Revision 1.207  2015/10/27 17:36:57  brouard
                    539:   *** empty log message ***
                    540: 
1.207     brouard   541:   Revision 1.206  2015/10/24 07:14:11  brouard
                    542:   *** empty log message ***
                    543: 
1.206     brouard   544:   Revision 1.205  2015/10/23 15:50:53  brouard
                    545:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    546: 
1.205     brouard   547:   Revision 1.204  2015/10/01 16:20:26  brouard
                    548:   Summary: Some new graphs of contribution to likelihood
                    549: 
1.204     brouard   550:   Revision 1.203  2015/09/30 17:45:14  brouard
                    551:   Summary: looking at better estimation of the hessian
                    552: 
                    553:   Also a better criteria for convergence to the period prevalence And
                    554:   therefore adding the number of years needed to converge. (The
                    555:   prevalence in any alive state shold sum to one
                    556: 
1.203     brouard   557:   Revision 1.202  2015/09/22 19:45:16  brouard
                    558:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    559: 
1.202     brouard   560:   Revision 1.201  2015/09/15 17:34:58  brouard
                    561:   Summary: 0.98r0
                    562: 
                    563:   - Some new graphs like suvival functions
                    564:   - Some bugs fixed like model=1+age+V2.
                    565: 
1.201     brouard   566:   Revision 1.200  2015/09/09 16:53:55  brouard
                    567:   Summary: Big bug thanks to Flavia
                    568: 
                    569:   Even model=1+age+V2. did not work anymore
                    570: 
1.200     brouard   571:   Revision 1.199  2015/09/07 14:09:23  brouard
                    572:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    573: 
1.199     brouard   574:   Revision 1.198  2015/09/03 07:14:39  brouard
                    575:   Summary: 0.98q5 Flavia
                    576: 
1.198     brouard   577:   Revision 1.197  2015/09/01 18:24:39  brouard
                    578:   *** empty log message ***
                    579: 
1.197     brouard   580:   Revision 1.196  2015/08/18 23:17:52  brouard
                    581:   Summary: 0.98q5
                    582: 
1.196     brouard   583:   Revision 1.195  2015/08/18 16:28:39  brouard
                    584:   Summary: Adding a hack for testing purpose
                    585: 
                    586:   After reading the title, ftol and model lines, if the comment line has
                    587:   a q, starting with #q, the answer at the end of the run is quit. It
                    588:   permits to run test files in batch with ctest. The former workaround was
                    589:   $ echo q | imach foo.imach
                    590: 
1.195     brouard   591:   Revision 1.194  2015/08/18 13:32:00  brouard
                    592:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    593: 
1.194     brouard   594:   Revision 1.193  2015/08/04 07:17:42  brouard
                    595:   Summary: 0.98q4
                    596: 
1.193     brouard   597:   Revision 1.192  2015/07/16 16:49:02  brouard
                    598:   Summary: Fixing some outputs
                    599: 
1.192     brouard   600:   Revision 1.191  2015/07/14 10:00:33  brouard
                    601:   Summary: Some fixes
                    602: 
1.191     brouard   603:   Revision 1.190  2015/05/05 08:51:13  brouard
                    604:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    605: 
                    606:   Fix 1+age+.
                    607: 
1.190     brouard   608:   Revision 1.189  2015/04/30 14:45:16  brouard
                    609:   Summary: 0.98q2
                    610: 
1.189     brouard   611:   Revision 1.188  2015/04/30 08:27:53  brouard
                    612:   *** empty log message ***
                    613: 
1.188     brouard   614:   Revision 1.187  2015/04/29 09:11:15  brouard
                    615:   *** empty log message ***
                    616: 
1.187     brouard   617:   Revision 1.186  2015/04/23 12:01:52  brouard
                    618:   Summary: V1*age is working now, version 0.98q1
                    619: 
                    620:   Some codes had been disabled in order to simplify and Vn*age was
                    621:   working in the optimization phase, ie, giving correct MLE parameters,
                    622:   but, as usual, outputs were not correct and program core dumped.
                    623: 
1.186     brouard   624:   Revision 1.185  2015/03/11 13:26:42  brouard
                    625:   Summary: Inclusion of compile and links command line for Intel Compiler
                    626: 
1.185     brouard   627:   Revision 1.184  2015/03/11 11:52:39  brouard
                    628:   Summary: Back from Windows 8. Intel Compiler
                    629: 
1.184     brouard   630:   Revision 1.183  2015/03/10 20:34:32  brouard
                    631:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    632: 
                    633:   We use directest instead of original Powell test; probably no
                    634:   incidence on the results, but better justifications;
                    635:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    636:   wrong results.
                    637: 
1.183     brouard   638:   Revision 1.182  2015/02/12 08:19:57  brouard
                    639:   Summary: Trying to keep directest which seems simpler and more general
                    640:   Author: Nicolas Brouard
                    641: 
1.182     brouard   642:   Revision 1.181  2015/02/11 23:22:24  brouard
                    643:   Summary: Comments on Powell added
                    644: 
                    645:   Author:
                    646: 
1.181     brouard   647:   Revision 1.180  2015/02/11 17:33:45  brouard
                    648:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    649: 
1.180     brouard   650:   Revision 1.179  2015/01/04 09:57:06  brouard
                    651:   Summary: back to OS/X
                    652: 
1.179     brouard   653:   Revision 1.178  2015/01/04 09:35:48  brouard
                    654:   *** empty log message ***
                    655: 
1.178     brouard   656:   Revision 1.177  2015/01/03 18:40:56  brouard
                    657:   Summary: Still testing ilc32 on OSX
                    658: 
1.177     brouard   659:   Revision 1.176  2015/01/03 16:45:04  brouard
                    660:   *** empty log message ***
                    661: 
1.176     brouard   662:   Revision 1.175  2015/01/03 16:33:42  brouard
                    663:   *** empty log message ***
                    664: 
1.175     brouard   665:   Revision 1.174  2015/01/03 16:15:49  brouard
                    666:   Summary: Still in cross-compilation
                    667: 
1.174     brouard   668:   Revision 1.173  2015/01/03 12:06:26  brouard
                    669:   Summary: trying to detect cross-compilation
                    670: 
1.173     brouard   671:   Revision 1.172  2014/12/27 12:07:47  brouard
                    672:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    673: 
1.172     brouard   674:   Revision 1.171  2014/12/23 13:26:59  brouard
                    675:   Summary: Back from Visual C
                    676: 
                    677:   Still problem with utsname.h on Windows
                    678: 
1.171     brouard   679:   Revision 1.170  2014/12/23 11:17:12  brouard
                    680:   Summary: Cleaning some \%% back to %%
                    681: 
                    682:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    683: 
1.170     brouard   684:   Revision 1.169  2014/12/22 23:08:31  brouard
                    685:   Summary: 0.98p
                    686: 
                    687:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    688: 
1.169     brouard   689:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   690:   Summary: update
1.169     brouard   691: 
1.168     brouard   692:   Revision 1.167  2014/12/22 13:50:56  brouard
                    693:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    694: 
                    695:   Testing on Linux 64
                    696: 
1.167     brouard   697:   Revision 1.166  2014/12/22 11:40:47  brouard
                    698:   *** empty log message ***
                    699: 
1.166     brouard   700:   Revision 1.165  2014/12/16 11:20:36  brouard
                    701:   Summary: After compiling on Visual C
                    702: 
                    703:   * imach.c (Module): Merging 1.61 to 1.162
                    704: 
1.165     brouard   705:   Revision 1.164  2014/12/16 10:52:11  brouard
                    706:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    707: 
                    708:   * imach.c (Module): Merging 1.61 to 1.162
                    709: 
1.164     brouard   710:   Revision 1.163  2014/12/16 10:30:11  brouard
                    711:   * imach.c (Module): Merging 1.61 to 1.162
                    712: 
1.163     brouard   713:   Revision 1.162  2014/09/25 11:43:39  brouard
                    714:   Summary: temporary backup 0.99!
                    715: 
1.162     brouard   716:   Revision 1.1  2014/09/16 11:06:58  brouard
                    717:   Summary: With some code (wrong) for nlopt
                    718: 
                    719:   Author:
                    720: 
                    721:   Revision 1.161  2014/09/15 20:41:41  brouard
                    722:   Summary: Problem with macro SQR on Intel compiler
                    723: 
1.161     brouard   724:   Revision 1.160  2014/09/02 09:24:05  brouard
                    725:   *** empty log message ***
                    726: 
1.160     brouard   727:   Revision 1.159  2014/09/01 10:34:10  brouard
                    728:   Summary: WIN32
                    729:   Author: Brouard
                    730: 
1.159     brouard   731:   Revision 1.158  2014/08/27 17:11:51  brouard
                    732:   *** empty log message ***
                    733: 
1.158     brouard   734:   Revision 1.157  2014/08/27 16:26:55  brouard
                    735:   Summary: Preparing windows Visual studio version
                    736:   Author: Brouard
                    737: 
                    738:   In order to compile on Visual studio, time.h is now correct and time_t
                    739:   and tm struct should be used. difftime should be used but sometimes I
                    740:   just make the differences in raw time format (time(&now).
                    741:   Trying to suppress #ifdef LINUX
                    742:   Add xdg-open for __linux in order to open default browser.
                    743: 
1.157     brouard   744:   Revision 1.156  2014/08/25 20:10:10  brouard
                    745:   *** empty log message ***
                    746: 
1.156     brouard   747:   Revision 1.155  2014/08/25 18:32:34  brouard
                    748:   Summary: New compile, minor changes
                    749:   Author: Brouard
                    750: 
1.155     brouard   751:   Revision 1.154  2014/06/20 17:32:08  brouard
                    752:   Summary: Outputs now all graphs of convergence to period prevalence
                    753: 
1.154     brouard   754:   Revision 1.153  2014/06/20 16:45:46  brouard
                    755:   Summary: If 3 live state, convergence to period prevalence on same graph
                    756:   Author: Brouard
                    757: 
1.153     brouard   758:   Revision 1.152  2014/06/18 17:54:09  brouard
                    759:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    760: 
1.152     brouard   761:   Revision 1.151  2014/06/18 16:43:30  brouard
                    762:   *** empty log message ***
                    763: 
1.151     brouard   764:   Revision 1.150  2014/06/18 16:42:35  brouard
                    765:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    766:   Author: brouard
                    767: 
1.150     brouard   768:   Revision 1.149  2014/06/18 15:51:14  brouard
                    769:   Summary: Some fixes in parameter files errors
                    770:   Author: Nicolas Brouard
                    771: 
1.149     brouard   772:   Revision 1.148  2014/06/17 17:38:48  brouard
                    773:   Summary: Nothing new
                    774:   Author: Brouard
                    775: 
                    776:   Just a new packaging for OS/X version 0.98nS
                    777: 
1.148     brouard   778:   Revision 1.147  2014/06/16 10:33:11  brouard
                    779:   *** empty log message ***
                    780: 
1.147     brouard   781:   Revision 1.146  2014/06/16 10:20:28  brouard
                    782:   Summary: Merge
                    783:   Author: Brouard
                    784: 
                    785:   Merge, before building revised version.
                    786: 
1.146     brouard   787:   Revision 1.145  2014/06/10 21:23:15  brouard
                    788:   Summary: Debugging with valgrind
                    789:   Author: Nicolas Brouard
                    790: 
                    791:   Lot of changes in order to output the results with some covariates
                    792:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    793:   improve the code.
                    794:   No more memory valgrind error but a lot has to be done in order to
                    795:   continue the work of splitting the code into subroutines.
                    796:   Also, decodemodel has been improved. Tricode is still not
                    797:   optimal. nbcode should be improved. Documentation has been added in
                    798:   the source code.
                    799: 
1.144     brouard   800:   Revision 1.143  2014/01/26 09:45:38  brouard
                    801:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    802: 
                    803:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    804:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    805: 
1.143     brouard   806:   Revision 1.142  2014/01/26 03:57:36  brouard
                    807:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    808: 
                    809:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    810: 
1.142     brouard   811:   Revision 1.141  2014/01/26 02:42:01  brouard
                    812:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    813: 
1.141     brouard   814:   Revision 1.140  2011/09/02 10:37:54  brouard
                    815:   Summary: times.h is ok with mingw32 now.
                    816: 
1.140     brouard   817:   Revision 1.139  2010/06/14 07:50:17  brouard
                    818:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    819:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    820: 
1.139     brouard   821:   Revision 1.138  2010/04/30 18:19:40  brouard
                    822:   *** empty log message ***
                    823: 
1.138     brouard   824:   Revision 1.137  2010/04/29 18:11:38  brouard
                    825:   (Module): Checking covariates for more complex models
                    826:   than V1+V2. A lot of change to be done. Unstable.
                    827: 
1.137     brouard   828:   Revision 1.136  2010/04/26 20:30:53  brouard
                    829:   (Module): merging some libgsl code. Fixing computation
                    830:   of likelione (using inter/intrapolation if mle = 0) in order to
                    831:   get same likelihood as if mle=1.
                    832:   Some cleaning of code and comments added.
                    833: 
1.136     brouard   834:   Revision 1.135  2009/10/29 15:33:14  brouard
                    835:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    836: 
1.135     brouard   837:   Revision 1.134  2009/10/29 13:18:53  brouard
                    838:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    839: 
1.134     brouard   840:   Revision 1.133  2009/07/06 10:21:25  brouard
                    841:   just nforces
                    842: 
1.133     brouard   843:   Revision 1.132  2009/07/06 08:22:05  brouard
                    844:   Many tings
                    845: 
1.132     brouard   846:   Revision 1.131  2009/06/20 16:22:47  brouard
                    847:   Some dimensions resccaled
                    848: 
1.131     brouard   849:   Revision 1.130  2009/05/26 06:44:34  brouard
                    850:   (Module): Max Covariate is now set to 20 instead of 8. A
                    851:   lot of cleaning with variables initialized to 0. Trying to make
                    852:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    853: 
1.130     brouard   854:   Revision 1.129  2007/08/31 13:49:27  lievre
                    855:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    856: 
1.129     lievre    857:   Revision 1.128  2006/06/30 13:02:05  brouard
                    858:   (Module): Clarifications on computing e.j
                    859: 
1.128     brouard   860:   Revision 1.127  2006/04/28 18:11:50  brouard
                    861:   (Module): Yes the sum of survivors was wrong since
                    862:   imach-114 because nhstepm was no more computed in the age
                    863:   loop. Now we define nhstepma in the age loop.
                    864:   (Module): In order to speed up (in case of numerous covariates) we
                    865:   compute health expectancies (without variances) in a first step
                    866:   and then all the health expectancies with variances or standard
                    867:   deviation (needs data from the Hessian matrices) which slows the
                    868:   computation.
                    869:   In the future we should be able to stop the program is only health
                    870:   expectancies and graph are needed without standard deviations.
                    871: 
1.127     brouard   872:   Revision 1.126  2006/04/28 17:23:28  brouard
                    873:   (Module): Yes the sum of survivors was wrong since
                    874:   imach-114 because nhstepm was no more computed in the age
                    875:   loop. Now we define nhstepma in the age loop.
                    876:   Version 0.98h
                    877: 
1.126     brouard   878:   Revision 1.125  2006/04/04 15:20:31  lievre
                    879:   Errors in calculation of health expectancies. Age was not initialized.
                    880:   Forecasting file added.
                    881: 
                    882:   Revision 1.124  2006/03/22 17:13:53  lievre
                    883:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    884:   The log-likelihood is printed in the log file
                    885: 
                    886:   Revision 1.123  2006/03/20 10:52:43  brouard
                    887:   * imach.c (Module): <title> changed, corresponds to .htm file
                    888:   name. <head> headers where missing.
                    889: 
                    890:   * imach.c (Module): Weights can have a decimal point as for
                    891:   English (a comma might work with a correct LC_NUMERIC environment,
                    892:   otherwise the weight is truncated).
                    893:   Modification of warning when the covariates values are not 0 or
                    894:   1.
                    895:   Version 0.98g
                    896: 
                    897:   Revision 1.122  2006/03/20 09:45:41  brouard
                    898:   (Module): Weights can have a decimal point as for
                    899:   English (a comma might work with a correct LC_NUMERIC environment,
                    900:   otherwise the weight is truncated).
                    901:   Modification of warning when the covariates values are not 0 or
                    902:   1.
                    903:   Version 0.98g
                    904: 
                    905:   Revision 1.121  2006/03/16 17:45:01  lievre
                    906:   * imach.c (Module): Comments concerning covariates added
                    907: 
                    908:   * imach.c (Module): refinements in the computation of lli if
                    909:   status=-2 in order to have more reliable computation if stepm is
                    910:   not 1 month. Version 0.98f
                    911: 
                    912:   Revision 1.120  2006/03/16 15:10:38  lievre
                    913:   (Module): refinements in the computation of lli if
                    914:   status=-2 in order to have more reliable computation if stepm is
                    915:   not 1 month. Version 0.98f
                    916: 
                    917:   Revision 1.119  2006/03/15 17:42:26  brouard
                    918:   (Module): Bug if status = -2, the loglikelihood was
                    919:   computed as likelihood omitting the logarithm. Version O.98e
                    920: 
                    921:   Revision 1.118  2006/03/14 18:20:07  brouard
                    922:   (Module): varevsij Comments added explaining the second
                    923:   table of variances if popbased=1 .
                    924:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    925:   (Module): Function pstamp added
                    926:   (Module): Version 0.98d
                    927: 
                    928:   Revision 1.117  2006/03/14 17:16:22  brouard
                    929:   (Module): varevsij Comments added explaining the second
                    930:   table of variances if popbased=1 .
                    931:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    932:   (Module): Function pstamp added
                    933:   (Module): Version 0.98d
                    934: 
                    935:   Revision 1.116  2006/03/06 10:29:27  brouard
                    936:   (Module): Variance-covariance wrong links and
                    937:   varian-covariance of ej. is needed (Saito).
                    938: 
                    939:   Revision 1.115  2006/02/27 12:17:45  brouard
                    940:   (Module): One freematrix added in mlikeli! 0.98c
                    941: 
                    942:   Revision 1.114  2006/02/26 12:57:58  brouard
                    943:   (Module): Some improvements in processing parameter
                    944:   filename with strsep.
                    945: 
                    946:   Revision 1.113  2006/02/24 14:20:24  brouard
                    947:   (Module): Memory leaks checks with valgrind and:
                    948:   datafile was not closed, some imatrix were not freed and on matrix
                    949:   allocation too.
                    950: 
                    951:   Revision 1.112  2006/01/30 09:55:26  brouard
                    952:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    953: 
                    954:   Revision 1.111  2006/01/25 20:38:18  brouard
                    955:   (Module): Lots of cleaning and bugs added (Gompertz)
                    956:   (Module): Comments can be added in data file. Missing date values
                    957:   can be a simple dot '.'.
                    958: 
                    959:   Revision 1.110  2006/01/25 00:51:50  brouard
                    960:   (Module): Lots of cleaning and bugs added (Gompertz)
                    961: 
                    962:   Revision 1.109  2006/01/24 19:37:15  brouard
                    963:   (Module): Comments (lines starting with a #) are allowed in data.
                    964: 
                    965:   Revision 1.108  2006/01/19 18:05:42  lievre
                    966:   Gnuplot problem appeared...
                    967:   To be fixed
                    968: 
                    969:   Revision 1.107  2006/01/19 16:20:37  brouard
                    970:   Test existence of gnuplot in imach path
                    971: 
                    972:   Revision 1.106  2006/01/19 13:24:36  brouard
                    973:   Some cleaning and links added in html output
                    974: 
                    975:   Revision 1.105  2006/01/05 20:23:19  lievre
                    976:   *** empty log message ***
                    977: 
                    978:   Revision 1.104  2005/09/30 16:11:43  lievre
                    979:   (Module): sump fixed, loop imx fixed, and simplifications.
                    980:   (Module): If the status is missing at the last wave but we know
                    981:   that the person is alive, then we can code his/her status as -2
                    982:   (instead of missing=-1 in earlier versions) and his/her
                    983:   contributions to the likelihood is 1 - Prob of dying from last
                    984:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    985:   the healthy state at last known wave). Version is 0.98
                    986: 
                    987:   Revision 1.103  2005/09/30 15:54:49  lievre
                    988:   (Module): sump fixed, loop imx fixed, and simplifications.
                    989: 
                    990:   Revision 1.102  2004/09/15 17:31:30  brouard
                    991:   Add the possibility to read data file including tab characters.
                    992: 
                    993:   Revision 1.101  2004/09/15 10:38:38  brouard
                    994:   Fix on curr_time
                    995: 
                    996:   Revision 1.100  2004/07/12 18:29:06  brouard
                    997:   Add version for Mac OS X. Just define UNIX in Makefile
                    998: 
                    999:   Revision 1.99  2004/06/05 08:57:40  brouard
                   1000:   *** empty log message ***
                   1001: 
                   1002:   Revision 1.98  2004/05/16 15:05:56  brouard
                   1003:   New version 0.97 . First attempt to estimate force of mortality
                   1004:   directly from the data i.e. without the need of knowing the health
                   1005:   state at each age, but using a Gompertz model: log u =a + b*age .
                   1006:   This is the basic analysis of mortality and should be done before any
                   1007:   other analysis, in order to test if the mortality estimated from the
                   1008:   cross-longitudinal survey is different from the mortality estimated
                   1009:   from other sources like vital statistic data.
                   1010: 
                   1011:   The same imach parameter file can be used but the option for mle should be -3.
                   1012: 
1.324     brouard  1013:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard  1014:   former routines in order to include the new code within the former code.
                   1015: 
                   1016:   The output is very simple: only an estimate of the intercept and of
                   1017:   the slope with 95% confident intervals.
                   1018: 
                   1019:   Current limitations:
                   1020:   A) Even if you enter covariates, i.e. with the
                   1021:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                   1022:   B) There is no computation of Life Expectancy nor Life Table.
                   1023: 
                   1024:   Revision 1.97  2004/02/20 13:25:42  lievre
                   1025:   Version 0.96d. Population forecasting command line is (temporarily)
                   1026:   suppressed.
                   1027: 
                   1028:   Revision 1.96  2003/07/15 15:38:55  brouard
                   1029:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                   1030:   rewritten within the same printf. Workaround: many printfs.
                   1031: 
                   1032:   Revision 1.95  2003/07/08 07:54:34  brouard
                   1033:   * imach.c (Repository):
                   1034:   (Repository): Using imachwizard code to output a more meaningful covariance
                   1035:   matrix (cov(a12,c31) instead of numbers.
                   1036: 
                   1037:   Revision 1.94  2003/06/27 13:00:02  brouard
                   1038:   Just cleaning
                   1039: 
                   1040:   Revision 1.93  2003/06/25 16:33:55  brouard
                   1041:   (Module): On windows (cygwin) function asctime_r doesn't
                   1042:   exist so I changed back to asctime which exists.
                   1043:   (Module): Version 0.96b
                   1044: 
                   1045:   Revision 1.92  2003/06/25 16:30:45  brouard
                   1046:   (Module): On windows (cygwin) function asctime_r doesn't
                   1047:   exist so I changed back to asctime which exists.
                   1048: 
                   1049:   Revision 1.91  2003/06/25 15:30:29  brouard
                   1050:   * imach.c (Repository): Duplicated warning errors corrected.
                   1051:   (Repository): Elapsed time after each iteration is now output. It
                   1052:   helps to forecast when convergence will be reached. Elapsed time
                   1053:   is stamped in powell.  We created a new html file for the graphs
                   1054:   concerning matrix of covariance. It has extension -cov.htm.
                   1055: 
                   1056:   Revision 1.90  2003/06/24 12:34:15  brouard
                   1057:   (Module): Some bugs corrected for windows. Also, when
                   1058:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1059:   of the covariance matrix to be input.
                   1060: 
                   1061:   Revision 1.89  2003/06/24 12:30:52  brouard
                   1062:   (Module): Some bugs corrected for windows. Also, when
                   1063:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1064:   of the covariance matrix to be input.
                   1065: 
                   1066:   Revision 1.88  2003/06/23 17:54:56  brouard
                   1067:   * 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.
                   1068: 
                   1069:   Revision 1.87  2003/06/18 12:26:01  brouard
                   1070:   Version 0.96
                   1071: 
                   1072:   Revision 1.86  2003/06/17 20:04:08  brouard
                   1073:   (Module): Change position of html and gnuplot routines and added
                   1074:   routine fileappend.
                   1075: 
                   1076:   Revision 1.85  2003/06/17 13:12:43  brouard
                   1077:   * imach.c (Repository): Check when date of death was earlier that
                   1078:   current date of interview. It may happen when the death was just
                   1079:   prior to the death. In this case, dh was negative and likelihood
                   1080:   was wrong (infinity). We still send an "Error" but patch by
                   1081:   assuming that the date of death was just one stepm after the
                   1082:   interview.
                   1083:   (Repository): Because some people have very long ID (first column)
                   1084:   we changed int to long in num[] and we added a new lvector for
                   1085:   memory allocation. But we also truncated to 8 characters (left
                   1086:   truncation)
                   1087:   (Repository): No more line truncation errors.
                   1088: 
                   1089:   Revision 1.84  2003/06/13 21:44:43  brouard
                   1090:   * imach.c (Repository): Replace "freqsummary" at a correct
                   1091:   place. It differs from routine "prevalence" which may be called
                   1092:   many times. Probs is memory consuming and must be used with
                   1093:   parcimony.
                   1094:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                   1095: 
                   1096:   Revision 1.83  2003/06/10 13:39:11  lievre
                   1097:   *** empty log message ***
                   1098: 
                   1099:   Revision 1.82  2003/06/05 15:57:20  brouard
                   1100:   Add log in  imach.c and  fullversion number is now printed.
                   1101: 
                   1102: */
                   1103: /*
                   1104:    Interpolated Markov Chain
                   1105: 
                   1106:   Short summary of the programme:
                   1107:   
1.227     brouard  1108:   This program computes Healthy Life Expectancies or State-specific
                   1109:   (if states aren't health statuses) Expectancies from
                   1110:   cross-longitudinal data. Cross-longitudinal data consist in: 
                   1111: 
                   1112:   -1- a first survey ("cross") where individuals from different ages
                   1113:   are interviewed on their health status or degree of disability (in
                   1114:   the case of a health survey which is our main interest)
                   1115: 
                   1116:   -2- at least a second wave of interviews ("longitudinal") which
                   1117:   measure each change (if any) in individual health status.  Health
                   1118:   expectancies are computed from the time spent in each health state
                   1119:   according to a model. More health states you consider, more time is
                   1120:   necessary to reach the Maximum Likelihood of the parameters involved
                   1121:   in the model.  The simplest model is the multinomial logistic model
                   1122:   where pij is the probability to be observed in state j at the second
                   1123:   wave conditional to be observed in state i at the first
                   1124:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                   1125:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                   1126:   have a more complex model than "constant and age", you should modify
                   1127:   the program where the markup *Covariates have to be included here
                   1128:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard  1129:   convergence.
                   1130: 
                   1131:   The advantage of this computer programme, compared to a simple
                   1132:   multinomial logistic model, is clear when the delay between waves is not
                   1133:   identical for each individual. Also, if a individual missed an
                   1134:   intermediate interview, the information is lost, but taken into
                   1135:   account using an interpolation or extrapolation.  
                   1136: 
                   1137:   hPijx is the probability to be observed in state i at age x+h
                   1138:   conditional to the observed state i at age x. The delay 'h' can be
                   1139:   split into an exact number (nh*stepm) of unobserved intermediate
                   1140:   states. This elementary transition (by month, quarter,
                   1141:   semester or year) is modelled as a multinomial logistic.  The hPx
                   1142:   matrix is simply the matrix product of nh*stepm elementary matrices
                   1143:   and the contribution of each individual to the likelihood is simply
                   1144:   hPijx.
                   1145: 
                   1146:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard  1147:   of the life expectancies. It also computes the period (stable) prevalence.
                   1148: 
                   1149: Back prevalence and projections:
1.227     brouard  1150: 
                   1151:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                   1152:    double agemaxpar, double ftolpl, int *ncvyearp, double
                   1153:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                   1154:    mobilavproj)
                   1155: 
                   1156:     Computes the back prevalence limit for any combination of
                   1157:     covariate values k at any age between ageminpar and agemaxpar and
                   1158:     returns it in **bprlim. In the loops,
                   1159: 
                   1160:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                   1161:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                   1162: 
                   1163:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard  1164:    Computes for any combination of covariates k and any age between bage and fage 
                   1165:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1166:                        oldm=oldms;savm=savms;
1.227     brouard  1167: 
1.267     brouard  1168:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard  1169:      Computes the transition matrix starting at age 'age' over
                   1170:      'nhstepm*hstepm*stepm' months (i.e. until
                   1171:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard  1172:      nhstepm*hstepm matrices. 
                   1173: 
                   1174:      Returns p3mat[i][j][h] after calling
                   1175:      p3mat[i][j][h]=matprod2(newm,
                   1176:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                   1177:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                   1178:      oldm);
1.226     brouard  1179: 
                   1180: Important routines
                   1181: 
                   1182: - func (or funcone), computes logit (pij) distinguishing
                   1183:   o fixed variables (single or product dummies or quantitative);
                   1184:   o varying variables by:
                   1185:    (1) wave (single, product dummies, quantitative), 
                   1186:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                   1187:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                   1188:        % varying dummy (not done) or quantitative (not done);
                   1189: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                   1190:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                   1191: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
1.325     brouard  1192:   o There are 2**cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
1.226     brouard  1193:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard  1194: 
1.226     brouard  1195: 
                   1196:   
1.324     brouard  1197:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                   1198:            Institut national d'études démographiques, Paris.
1.126     brouard  1199:   This software have been partly granted by Euro-REVES, a concerted action
                   1200:   from the European Union.
                   1201:   It is copyrighted identically to a GNU software product, ie programme and
                   1202:   software can be distributed freely for non commercial use. Latest version
                   1203:   can be accessed at http://euroreves.ined.fr/imach .
                   1204: 
                   1205:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                   1206:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                   1207:   
                   1208:   **********************************************************************/
                   1209: /*
                   1210:   main
                   1211:   read parameterfile
                   1212:   read datafile
                   1213:   concatwav
                   1214:   freqsummary
                   1215:   if (mle >= 1)
                   1216:     mlikeli
                   1217:   print results files
                   1218:   if mle==1 
                   1219:      computes hessian
                   1220:   read end of parameter file: agemin, agemax, bage, fage, estepm
                   1221:       begin-prev-date,...
                   1222:   open gnuplot file
                   1223:   open html file
1.145     brouard  1224:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1225:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1226:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1227:     freexexit2 possible for memory heap.
                   1228: 
                   1229:   h Pij x                         | pij_nom  ficrestpij
                   1230:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1231:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1232:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1233: 
                   1234:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1235:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1236:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1237:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1238:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1239: 
1.126     brouard  1240:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1241:   health expectancies
                   1242:   Variance-covariance of DFLE
                   1243:   prevalence()
                   1244:    movingaverage()
                   1245:   varevsij() 
                   1246:   if popbased==1 varevsij(,popbased)
                   1247:   total life expectancies
                   1248:   Variance of period (stable) prevalence
                   1249:  end
                   1250: */
                   1251: 
1.187     brouard  1252: /* #define DEBUG */
                   1253: /* #define DEBUGBRENT */
1.203     brouard  1254: /* #define DEBUGLINMIN */
                   1255: /* #define DEBUGHESS */
                   1256: #define DEBUGHESSIJ
1.224     brouard  1257: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1258: #define POWELL /* Instead of NLOPT */
1.224     brouard  1259: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1260: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1261: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.319     brouard  1262: /* #define FLATSUP  *//* Suppresses directions where likelihood is flat */
1.126     brouard  1263: 
                   1264: #include <math.h>
                   1265: #include <stdio.h>
                   1266: #include <stdlib.h>
                   1267: #include <string.h>
1.226     brouard  1268: #include <ctype.h>
1.159     brouard  1269: 
                   1270: #ifdef _WIN32
                   1271: #include <io.h>
1.172     brouard  1272: #include <windows.h>
                   1273: #include <tchar.h>
1.159     brouard  1274: #else
1.126     brouard  1275: #include <unistd.h>
1.159     brouard  1276: #endif
1.126     brouard  1277: 
                   1278: #include <limits.h>
                   1279: #include <sys/types.h>
1.171     brouard  1280: 
                   1281: #if defined(__GNUC__)
                   1282: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1283: #endif
                   1284: 
1.126     brouard  1285: #include <sys/stat.h>
                   1286: #include <errno.h>
1.159     brouard  1287: /* extern int errno; */
1.126     brouard  1288: 
1.157     brouard  1289: /* #ifdef LINUX */
                   1290: /* #include <time.h> */
                   1291: /* #include "timeval.h" */
                   1292: /* #else */
                   1293: /* #include <sys/time.h> */
                   1294: /* #endif */
                   1295: 
1.126     brouard  1296: #include <time.h>
                   1297: 
1.136     brouard  1298: #ifdef GSL
                   1299: #include <gsl/gsl_errno.h>
                   1300: #include <gsl/gsl_multimin.h>
                   1301: #endif
                   1302: 
1.167     brouard  1303: 
1.162     brouard  1304: #ifdef NLOPT
                   1305: #include <nlopt.h>
                   1306: typedef struct {
                   1307:   double (* function)(double [] );
                   1308: } myfunc_data ;
                   1309: #endif
                   1310: 
1.126     brouard  1311: /* #include <libintl.h> */
                   1312: /* #define _(String) gettext (String) */
                   1313: 
1.251     brouard  1314: #define MAXLINE 2048 /* Was 256 and 1024. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1315: 
                   1316: #define GNUPLOTPROGRAM "gnuplot"
1.343     brouard  1317: #define GNUPLOTVERSION 5.1
                   1318: double gnuplotversion=GNUPLOTVERSION;
1.126     brouard  1319: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
1.329     brouard  1320: #define FILENAMELENGTH 256
1.126     brouard  1321: 
                   1322: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1323: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1324: 
1.144     brouard  1325: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                   1326: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1327: 
                   1328: #define NINTERVMAX 8
1.144     brouard  1329: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1330: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.325     brouard  1331: #define NCOVMAX 30  /**< Maximum number of covariates used in the model, including generated covariates V1*V2 or V1*age */
1.197     brouard  1332: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1333: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1334: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1335: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1336: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1337: /* #define AGESUP 130 */
1.288     brouard  1338: /* #define AGESUP 150 */
                   1339: #define AGESUP 200
1.268     brouard  1340: #define AGEINF 0
1.218     brouard  1341: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1342: #define AGEBASE 40
1.194     brouard  1343: #define AGEOVERFLOW 1.e20
1.164     brouard  1344: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1345: #ifdef _WIN32
                   1346: #define DIRSEPARATOR '\\'
                   1347: #define CHARSEPARATOR "\\"
                   1348: #define ODIRSEPARATOR '/'
                   1349: #else
1.126     brouard  1350: #define DIRSEPARATOR '/'
                   1351: #define CHARSEPARATOR "/"
                   1352: #define ODIRSEPARATOR '\\'
                   1353: #endif
                   1354: 
1.347   ! brouard  1355: /* $Id: imach.c,v 1.346 2022/09/16 13:52:36 brouard Exp $ */
1.126     brouard  1356: /* $State: Exp $ */
1.196     brouard  1357: #include "version.h"
                   1358: char version[]=__IMACH_VERSION__;
1.337     brouard  1359: 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.347   ! brouard  1360: char fullversion[]="$Revision: 1.346 $ $Date: 2022/09/16 13:52:36 $"; 
1.126     brouard  1361: char strstart[80];
                   1362: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1363: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.342     brouard  1364: int debugILK=0; /* debugILK is set by a #d in a comment line */
1.187     brouard  1365: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.330     brouard  1366: /* Number of covariates model (1)=V2+V1+ V3*age+V2*V4 */
                   1367: /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
1.335     brouard  1368: 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  1369: 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  1370: int cptcovs=0; /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   1371: int cptcovsnq=0; /**< cptcovsnq number of SIMPLE covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1372: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                   1373: int cptcovprodnoage=0; /**< Number of covariate products without age */   
1.335     brouard  1374: 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  1375: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1376: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.339     brouard  1377: int ncovvt=0; /* Total number of effective (wave) varying covariates (dummy or quantitative or products [without age]) in the model */
1.232     brouard  1378: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
1.234     brouard  1379: int nsd=0; /**< Total number of single dummy variables (output) */
                   1380: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1381: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1382: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1383: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1384: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1385: int cptcov=0; /* Working variable */
1.334     brouard  1386: int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs+1 declared globally ;*/
1.290     brouard  1387: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1388: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.302     brouard  1389: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
1.126     brouard  1390: int nlstate=2; /* Number of live states */
                   1391: int ndeath=1; /* Number of dead states */
1.130     brouard  1392: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.339     brouard  1393: int nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable*/
                   1394: int ncovcolt=0; /* ncovcolt=ncovcol+nqv+ntv+nqtv; total of covariates in the data, not in the model equation*/ 
1.126     brouard  1395: int popbased=0;
                   1396: 
                   1397: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1398: int maxwav=0; /* Maxim number of waves */
                   1399: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1400: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1401: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard  1402:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1403: int mle=1, weightopt=0;
1.126     brouard  1404: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1405: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1406: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1407:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1408: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1409: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1410: 
1.130     brouard  1411: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1412: double **matprod2(); /* test */
1.126     brouard  1413: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1414: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1415: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1416: 
1.136     brouard  1417: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1418: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1419: FILE *ficlog, *ficrespow;
1.130     brouard  1420: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1421: double fretone; /* Only one call to likelihood */
1.130     brouard  1422: long ipmx=0; /* Number of contributions */
1.126     brouard  1423: double sw; /* Sum of weights */
                   1424: char filerespow[FILENAMELENGTH];
                   1425: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1426: FILE *ficresilk;
                   1427: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1428: FILE *ficresprobmorprev;
                   1429: FILE *fichtm, *fichtmcov; /* Html File */
                   1430: FILE *ficreseij;
                   1431: char filerese[FILENAMELENGTH];
                   1432: FILE *ficresstdeij;
                   1433: char fileresstde[FILENAMELENGTH];
                   1434: FILE *ficrescveij;
                   1435: char filerescve[FILENAMELENGTH];
                   1436: FILE  *ficresvij;
                   1437: char fileresv[FILENAMELENGTH];
1.269     brouard  1438: 
1.126     brouard  1439: char title[MAXLINE];
1.234     brouard  1440: char model[MAXLINE]; /**< The model line */
1.217     brouard  1441: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1442: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1443: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1444: char command[FILENAMELENGTH];
                   1445: int  outcmd=0;
                   1446: 
1.217     brouard  1447: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1448: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1449: char filelog[FILENAMELENGTH]; /* Log file */
                   1450: char filerest[FILENAMELENGTH];
                   1451: char fileregp[FILENAMELENGTH];
                   1452: char popfile[FILENAMELENGTH];
                   1453: 
                   1454: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1455: 
1.157     brouard  1456: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1457: /* struct timezone tzp; */
                   1458: /* extern int gettimeofday(); */
                   1459: struct tm tml, *gmtime(), *localtime();
                   1460: 
                   1461: extern time_t time();
                   1462: 
                   1463: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1464: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                   1465: struct tm tm;
                   1466: 
1.126     brouard  1467: char strcurr[80], strfor[80];
                   1468: 
                   1469: char *endptr;
                   1470: long lval;
                   1471: double dval;
                   1472: 
                   1473: #define NR_END 1
                   1474: #define FREE_ARG char*
                   1475: #define FTOL 1.0e-10
                   1476: 
                   1477: #define NRANSI 
1.240     brouard  1478: #define ITMAX 200
                   1479: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1480: 
                   1481: #define TOL 2.0e-4 
                   1482: 
                   1483: #define CGOLD 0.3819660 
                   1484: #define ZEPS 1.0e-10 
                   1485: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1486: 
                   1487: #define GOLD 1.618034 
                   1488: #define GLIMIT 100.0 
                   1489: #define TINY 1.0e-20 
                   1490: 
                   1491: static double maxarg1,maxarg2;
                   1492: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1493: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1494:   
                   1495: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1496: #define rint(a) floor(a+0.5)
1.166     brouard  1497: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1498: #define mytinydouble 1.0e-16
1.166     brouard  1499: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1500: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1501: /* static double dsqrarg; */
                   1502: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1503: static double sqrarg;
                   1504: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1505: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1506: int agegomp= AGEGOMP;
                   1507: 
                   1508: int imx; 
                   1509: int stepm=1;
                   1510: /* Stepm, step in month: minimum step interpolation*/
                   1511: 
                   1512: int estepm;
                   1513: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1514: 
                   1515: int m,nb;
                   1516: long *num;
1.197     brouard  1517: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1518: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1519:                   covariate for which somebody answered excluding 
                   1520:                   undefined. Usually 2: 0 and 1. */
                   1521: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1522:                             covariate for which somebody answered including 
                   1523:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1524: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1525: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1526: double ***mobaverage, ***mobaverages; /* New global variable */
1.332     brouard  1527: 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  1528: double *ageexmed,*agecens;
                   1529: double dateintmean=0;
1.296     brouard  1530:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1531:   double anprojf, mprojf, jprojf;
1.126     brouard  1532: 
1.296     brouard  1533:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1534:   double anbackf, mbackf, jbackf;
                   1535:   double jintmean,mintmean,aintmean;  
1.126     brouard  1536: double *weight;
                   1537: int **s; /* Status */
1.141     brouard  1538: double *agedc;
1.145     brouard  1539: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1540:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1541:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1542: double **coqvar; /* Fixed quantitative covariate nqv */
1.341     brouard  1543: double ***cotvar; /* Time varying covariate start at ncovcol + nqv + (1 to ntv) */
1.225     brouard  1544: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1545: double  idx; 
                   1546: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.319     brouard  1547: /* Some documentation */
                   1548:       /*   Design original data
                   1549:        *  V1   V2   V3   V4  V5  V6  V7  V8  Weight ddb ddth d1st s1 V9 V10 V11 V12 s2 V9 V10 V11 V12 
                   1550:        *  <          ncovcol=6   >   nqv=2 (V7 V8)                   dv dv  dv  qtv    dv dv  dvv qtv
                   1551:        *                                                             ntv=3     nqtv=1
1.330     brouard  1552:        *  cptcovn number of covariates (not including constant and age or age*age) = number of plus sign + 1 = 10+1=11
1.319     brouard  1553:        * For time varying covariate, quanti or dummies
                   1554:        *       cotqvar[wav][iv(1 to nqtv)][i]= [1][12][i]=(V12) quanti
1.341     brouard  1555:        *       cotvar[wav][ncovcol+nqv+ iv(1 to nqtv)][i]= [(1 to nqtv)][i]=(V12) quanti
1.319     brouard  1556:        *       cotvar[wav][iv(1 to ntv)][i]= [1][1][i]=(V9) dummies at wav 1
                   1557:        *       cotvar[wav][iv(1 to ntv)][i]= [1][2][i]=(V10) dummies at wav 1
1.332     brouard  1558:        *       covar[Vk,i], value of the Vkth fixed covariate dummy or quanti for individual i:
1.319     brouard  1559:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   1560:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 + V9 + V9*age + V10
                   1561:        *   k=  1    2      3       4     5       6      7        8   9     10       11 
                   1562:        */
                   1563: /* According to the model, more columns can be added to covar by the product of covariates */
1.318     brouard  1564: /* 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
                   1565:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1566:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1567: */
1.343     brouard  1568: /*           V5+V4+ V3+V4*V3 +V5*age+V2 +V1*V2+V1*age+V1 */
                   1569: /*    kmodel  1  2   3   4     5    6    7     8    9 */
1.319     brouard  1570: /*Typevar[k]=  0  0   0   2     1    0    2     1    0 *//*0 for simple covariate (dummy, quantitative,*/
                   1571:                                                          /* fixed or varying), 1 for age product, 2 for*/
                   1572:                                                          /* product */
                   1573: /*Dummy[k]=    1  0   0   1     3    1    1     2    0 *//*Dummy[k] 0=dummy (0 1), 1 quantitative */
                   1574:                                                          /*(single or product without age), 2 dummy*/
                   1575:                                                          /* with age product, 3 quant with age product*/
                   1576: /*Tvar[k]=     5  4   3   6     5    2    7     1    1 */
                   1577: /*    nsd         1   2                              3 */ /* Counting single dummies covar fixed or tv */
1.330     brouard  1578: /*TnsdVar[Tvar]   1   2                              3 */ 
1.337     brouard  1579: /*Tvaraff[nsd]     4   3                              1 */ /* ID of single dummy cova fixed or timevary*/
1.319     brouard  1580: /*TvarsD[nsd]     4   3                              1 */ /* ID of single dummy cova fixed or timevary*/
1.338     brouard  1581: /*TvarsDind[nsd]  2   3                              9 */ /* position K of single dummy cova */
1.319     brouard  1582: /*    nsq      1                     2                 */ /* Counting single quantit tv */
                   1583: /* TvarsQ[k]   5                     2                 */ /* Number of single quantitative cova */
                   1584: /* TvarsQind   1                     6                 */ /* position K of single quantitative cova */
                   1585: /* Tprod[i]=k             1               2            */ /* Position in model of the ith prod without age */
                   1586: /* cptcovage                    1               2      */ /* Counting cov*age in the model equation */
                   1587: /* Tage[cptcovage]=k            5               8      */ /* Position in the model of ith cov*age */
                   1588: /* Tvard[1][1]@4={4,3,1,2}    V4*V3 V1*V2              */ /* Position in model of the ith prod without age */
1.330     brouard  1589: /* 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  1590: /* 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  1591: /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.234     brouard  1592: /* Type                    */
                   1593: /* V         1  2  3  4  5 */
                   1594: /*           F  F  V  V  V */
                   1595: /*           D  Q  D  D  Q */
                   1596: /*                         */
                   1597: int *TvarsD;
1.330     brouard  1598: int *TnsdVar;
1.234     brouard  1599: int *TvarsDind;
                   1600: int *TvarsQ;
                   1601: int *TvarsQind;
                   1602: 
1.318     brouard  1603: #define MAXRESULTLINESPONE 10+1
1.235     brouard  1604: int nresult=0;
1.258     brouard  1605: int parameterline=0; /* # of the parameter (type) line */
1.334     brouard  1606: int TKresult[MAXRESULTLINESPONE]; /* TKresult[nres]=k for each resultline nres give the corresponding combination of dummies */
                   1607: int resultmodel[MAXRESULTLINESPONE][NCOVMAX];/* resultmodel[k1]=k3: k1th position in the model corresponds to the k3 position in the resultline */
                   1608: int modelresult[MAXRESULTLINESPONE][NCOVMAX];/* modelresult[k3]=k1: k1th position in the model corresponds to the k3 position in the resultline */
                   1609: int Tresult[MAXRESULTLINESPONE][NCOVMAX];/* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1610: int Tinvresult[MAXRESULTLINESPONE][NCOVMAX];/* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line  */
                   1611: double TinvDoQresult[MAXRESULTLINESPONE][NCOVMAX];/* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line */
1.334     brouard  1612: int Tvresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1613: double Tqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
1.318     brouard  1614: double Tqinvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
1.332     brouard  1615: int Tvqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline */
1.318     brouard  1616: 
                   1617: /* 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
                   1618:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1619:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1620: */
1.234     brouard  1621: /* 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  1622: 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 */
                   1623: 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 */
                   1624: 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 */
                   1625: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1626: 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 */
                   1627: 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  1628: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1629: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1630: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1631: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1632: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1633: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1634: 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 */
                   1635: 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  1636: int *TvarVV; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1637: int *TvarVVind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1638:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   1639:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   1640:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   1641:       /* TvarVV={3,1,3}, for V3 and then the product V1*V3 is decomposed into V1 and V3 */            
                   1642:       /* TvarVVind={2,5,5}, for V3 and then the product V1*V3 is decomposed into V1 and V3 */         
1.230     brouard  1643: int *Tvarsel; /**< Selected covariates for output */
                   1644: double *Tvalsel; /**< Selected modality value of covariate for output */
1.226     brouard  1645: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.227     brouard  1646: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1647: 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  1648: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1649: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1650: int *Tage;
1.227     brouard  1651: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1652: 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  1653: 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*/ 
                   1654: 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  1655: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1656: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1657: int **Tvard;
1.330     brouard  1658: int **Tvardk;
1.227     brouard  1659: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1660: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1661: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1662:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1663:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1664: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1665: double *lsurv, *lpop, *tpop;
                   1666: 
1.231     brouard  1667: #define FD 1; /* Fixed dummy covariate */
                   1668: #define FQ 2; /* Fixed quantitative covariate */
                   1669: #define FP 3; /* Fixed product covariate */
                   1670: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1671: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1672: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1673: #define VD 10; /* Varying dummy covariate */
                   1674: #define VQ 11; /* Varying quantitative covariate */
                   1675: #define VP 12; /* Varying product covariate */
                   1676: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1677: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1678: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1679: #define APFD 16; /* Age product * fixed dummy covariate */
                   1680: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1681: #define APVD 18; /* Age product * varying dummy covariate */
                   1682: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1683: 
                   1684: #define FTYPE 1; /* Fixed covariate */
                   1685: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1686: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1687: 
                   1688: struct kmodel{
                   1689:        int maintype; /* main type */
                   1690:        int subtype; /* subtype */
                   1691: };
                   1692: struct kmodel modell[NCOVMAX];
                   1693: 
1.143     brouard  1694: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1695: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1696: 
                   1697: /**************** split *************************/
                   1698: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1699: {
                   1700:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1701:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1702:   */ 
                   1703:   char *ss;                            /* pointer */
1.186     brouard  1704:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1705: 
                   1706:   l1 = strlen(path );                  /* length of path */
                   1707:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1708:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1709:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1710:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1711:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1712:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1713:     /* get current working directory */
                   1714:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1715: #ifdef WIN32
                   1716:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1717: #else
                   1718:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1719: #endif
1.126     brouard  1720:       return( GLOCK_ERROR_GETCWD );
                   1721:     }
                   1722:     /* got dirc from getcwd*/
                   1723:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1724:   } else {                             /* strip directory from path */
1.126     brouard  1725:     ss++;                              /* after this, the filename */
                   1726:     l2 = strlen( ss );                 /* length of filename */
                   1727:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1728:     strcpy( name, ss );                /* save file name */
                   1729:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1730:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1731:     printf(" DIRC2 = %s \n",dirc);
                   1732:   }
                   1733:   /* We add a separator at the end of dirc if not exists */
                   1734:   l1 = strlen( dirc );                 /* length of directory */
                   1735:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1736:     dirc[l1] =  DIRSEPARATOR;
                   1737:     dirc[l1+1] = 0; 
                   1738:     printf(" DIRC3 = %s \n",dirc);
                   1739:   }
                   1740:   ss = strrchr( name, '.' );           /* find last / */
                   1741:   if (ss >0){
                   1742:     ss++;
                   1743:     strcpy(ext,ss);                    /* save extension */
                   1744:     l1= strlen( name);
                   1745:     l2= strlen(ss)+1;
                   1746:     strncpy( finame, name, l1-l2);
                   1747:     finame[l1-l2]= 0;
                   1748:   }
                   1749: 
                   1750:   return( 0 );                         /* we're done */
                   1751: }
                   1752: 
                   1753: 
                   1754: /******************************************/
                   1755: 
                   1756: void replace_back_to_slash(char *s, char*t)
                   1757: {
                   1758:   int i;
                   1759:   int lg=0;
                   1760:   i=0;
                   1761:   lg=strlen(t);
                   1762:   for(i=0; i<= lg; i++) {
                   1763:     (s[i] = t[i]);
                   1764:     if (t[i]== '\\') s[i]='/';
                   1765:   }
                   1766: }
                   1767: 
1.132     brouard  1768: char *trimbb(char *out, char *in)
1.137     brouard  1769: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1770:   char *s;
                   1771:   s=out;
                   1772:   while (*in != '\0'){
1.137     brouard  1773:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1774:       in++;
                   1775:     }
                   1776:     *out++ = *in++;
                   1777:   }
                   1778:   *out='\0';
                   1779:   return s;
                   1780: }
                   1781: 
1.187     brouard  1782: /* char *substrchaine(char *out, char *in, char *chain) */
                   1783: /* { */
                   1784: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1785: /*   char *s, *t; */
                   1786: /*   t=in;s=out; */
                   1787: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1788: /*     *out++ = *in++; */
                   1789: /*   } */
                   1790: 
                   1791: /*   /\* *in matches *chain *\/ */
                   1792: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1793: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1794: /*   } */
                   1795: /*   in--; chain--; */
                   1796: /*   while ( (*in != '\0')){ */
                   1797: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1798: /*     *out++ = *in++; */
                   1799: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1800: /*   } */
                   1801: /*   *out='\0'; */
                   1802: /*   out=s; */
                   1803: /*   return out; */
                   1804: /* } */
                   1805: char *substrchaine(char *out, char *in, char *chain)
                   1806: {
                   1807:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1808:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1809: 
                   1810:   char *strloc;
                   1811: 
                   1812:   strcpy (out, in); 
                   1813:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1814:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1815:   if(strloc != NULL){ 
                   1816:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1817:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1818:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1819:   }
                   1820:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1821:   return out;
                   1822: }
                   1823: 
                   1824: 
1.145     brouard  1825: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1826: {
1.187     brouard  1827:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1828:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.310     brouard  1829:      gives alocc="abcdef" and blocc="ghi2j".
1.145     brouard  1830:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1831:   */
1.160     brouard  1832:   char *s, *t;
1.145     brouard  1833:   t=in;s=in;
                   1834:   while ((*in != occ) && (*in != '\0')){
                   1835:     *alocc++ = *in++;
                   1836:   }
                   1837:   if( *in == occ){
                   1838:     *(alocc)='\0';
                   1839:     s=++in;
                   1840:   }
                   1841:  
                   1842:   if (s == t) {/* occ not found */
                   1843:     *(alocc-(in-s))='\0';
                   1844:     in=s;
                   1845:   }
                   1846:   while ( *in != '\0'){
                   1847:     *blocc++ = *in++;
                   1848:   }
                   1849: 
                   1850:   *blocc='\0';
                   1851:   return t;
                   1852: }
1.137     brouard  1853: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1854: {
1.187     brouard  1855:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1856:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1857:      gives blocc="abcdef2ghi" and alocc="j".
                   1858:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1859:   */
                   1860:   char *s, *t;
                   1861:   t=in;s=in;
                   1862:   while (*in != '\0'){
                   1863:     while( *in == occ){
                   1864:       *blocc++ = *in++;
                   1865:       s=in;
                   1866:     }
                   1867:     *blocc++ = *in++;
                   1868:   }
                   1869:   if (s == t) /* occ not found */
                   1870:     *(blocc-(in-s))='\0';
                   1871:   else
                   1872:     *(blocc-(in-s)-1)='\0';
                   1873:   in=s;
                   1874:   while ( *in != '\0'){
                   1875:     *alocc++ = *in++;
                   1876:   }
                   1877: 
                   1878:   *alocc='\0';
                   1879:   return s;
                   1880: }
                   1881: 
1.126     brouard  1882: int nbocc(char *s, char occ)
                   1883: {
                   1884:   int i,j=0;
                   1885:   int lg=20;
                   1886:   i=0;
                   1887:   lg=strlen(s);
                   1888:   for(i=0; i<= lg; i++) {
1.234     brouard  1889:     if  (s[i] == occ ) j++;
1.126     brouard  1890:   }
                   1891:   return j;
                   1892: }
                   1893: 
1.137     brouard  1894: /* void cutv(char *u,char *v, char*t, char occ) */
                   1895: /* { */
                   1896: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1897: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1898: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1899: /*   int i,lg,j,p=0; */
                   1900: /*   i=0; */
                   1901: /*   lg=strlen(t); */
                   1902: /*   for(j=0; j<=lg-1; j++) { */
                   1903: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1904: /*   } */
1.126     brouard  1905: 
1.137     brouard  1906: /*   for(j=0; j<p; j++) { */
                   1907: /*     (u[j] = t[j]); */
                   1908: /*   } */
                   1909: /*      u[p]='\0'; */
1.126     brouard  1910: 
1.137     brouard  1911: /*    for(j=0; j<= lg; j++) { */
                   1912: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1913: /*   } */
                   1914: /* } */
1.126     brouard  1915: 
1.160     brouard  1916: #ifdef _WIN32
                   1917: char * strsep(char **pp, const char *delim)
                   1918: {
                   1919:   char *p, *q;
                   1920:          
                   1921:   if ((p = *pp) == NULL)
                   1922:     return 0;
                   1923:   if ((q = strpbrk (p, delim)) != NULL)
                   1924:   {
                   1925:     *pp = q + 1;
                   1926:     *q = '\0';
                   1927:   }
                   1928:   else
                   1929:     *pp = 0;
                   1930:   return p;
                   1931: }
                   1932: #endif
                   1933: 
1.126     brouard  1934: /********************** nrerror ********************/
                   1935: 
                   1936: void nrerror(char error_text[])
                   1937: {
                   1938:   fprintf(stderr,"ERREUR ...\n");
                   1939:   fprintf(stderr,"%s\n",error_text);
                   1940:   exit(EXIT_FAILURE);
                   1941: }
                   1942: /*********************** vector *******************/
                   1943: double *vector(int nl, int nh)
                   1944: {
                   1945:   double *v;
                   1946:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1947:   if (!v) nrerror("allocation failure in vector");
                   1948:   return v-nl+NR_END;
                   1949: }
                   1950: 
                   1951: /************************ free vector ******************/
                   1952: void free_vector(double*v, int nl, int nh)
                   1953: {
                   1954:   free((FREE_ARG)(v+nl-NR_END));
                   1955: }
                   1956: 
                   1957: /************************ivector *******************************/
                   1958: int *ivector(long nl,long nh)
                   1959: {
                   1960:   int *v;
                   1961:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1962:   if (!v) nrerror("allocation failure in ivector");
                   1963:   return v-nl+NR_END;
                   1964: }
                   1965: 
                   1966: /******************free ivector **************************/
                   1967: void free_ivector(int *v, long nl, long nh)
                   1968: {
                   1969:   free((FREE_ARG)(v+nl-NR_END));
                   1970: }
                   1971: 
                   1972: /************************lvector *******************************/
                   1973: long *lvector(long nl,long nh)
                   1974: {
                   1975:   long *v;
                   1976:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1977:   if (!v) nrerror("allocation failure in ivector");
                   1978:   return v-nl+NR_END;
                   1979: }
                   1980: 
                   1981: /******************free lvector **************************/
                   1982: void free_lvector(long *v, long nl, long nh)
                   1983: {
                   1984:   free((FREE_ARG)(v+nl-NR_END));
                   1985: }
                   1986: 
                   1987: /******************* imatrix *******************************/
                   1988: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1989:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1990: { 
                   1991:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1992:   int **m; 
                   1993:   
                   1994:   /* allocate pointers to rows */ 
                   1995:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1996:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1997:   m += NR_END; 
                   1998:   m -= nrl; 
                   1999:   
                   2000:   
                   2001:   /* allocate rows and set pointers to them */ 
                   2002:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   2003:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   2004:   m[nrl] += NR_END; 
                   2005:   m[nrl] -= ncl; 
                   2006:   
                   2007:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   2008:   
                   2009:   /* return pointer to array of pointers to rows */ 
                   2010:   return m; 
                   2011: } 
                   2012: 
                   2013: /****************** free_imatrix *************************/
                   2014: void free_imatrix(m,nrl,nrh,ncl,nch)
                   2015:       int **m;
                   2016:       long nch,ncl,nrh,nrl; 
                   2017:      /* free an int matrix allocated by imatrix() */ 
                   2018: { 
                   2019:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   2020:   free((FREE_ARG) (m+nrl-NR_END)); 
                   2021: } 
                   2022: 
                   2023: /******************* matrix *******************************/
                   2024: double **matrix(long nrl, long nrh, long ncl, long nch)
                   2025: {
                   2026:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   2027:   double **m;
                   2028: 
                   2029:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2030:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2031:   m += NR_END;
                   2032:   m -= nrl;
                   2033: 
                   2034:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2035:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2036:   m[nrl] += NR_END;
                   2037:   m[nrl] -= ncl;
                   2038: 
                   2039:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2040:   return m;
1.145     brouard  2041:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   2042: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   2043: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  2044:    */
                   2045: }
                   2046: 
                   2047: /*************************free matrix ************************/
                   2048: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   2049: {
                   2050:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2051:   free((FREE_ARG)(m+nrl-NR_END));
                   2052: }
                   2053: 
                   2054: /******************* ma3x *******************************/
                   2055: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   2056: {
                   2057:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   2058:   double ***m;
                   2059: 
                   2060:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2061:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2062:   m += NR_END;
                   2063:   m -= nrl;
                   2064: 
                   2065:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2066:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2067:   m[nrl] += NR_END;
                   2068:   m[nrl] -= ncl;
                   2069: 
                   2070:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2071: 
                   2072:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   2073:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   2074:   m[nrl][ncl] += NR_END;
                   2075:   m[nrl][ncl] -= nll;
                   2076:   for (j=ncl+1; j<=nch; j++) 
                   2077:     m[nrl][j]=m[nrl][j-1]+nlay;
                   2078:   
                   2079:   for (i=nrl+1; i<=nrh; i++) {
                   2080:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   2081:     for (j=ncl+1; j<=nch; j++) 
                   2082:       m[i][j]=m[i][j-1]+nlay;
                   2083:   }
                   2084:   return m; 
                   2085:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   2086:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   2087:   */
                   2088: }
                   2089: 
                   2090: /*************************free ma3x ************************/
                   2091: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   2092: {
                   2093:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   2094:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2095:   free((FREE_ARG)(m+nrl-NR_END));
                   2096: }
                   2097: 
                   2098: /*************** function subdirf ***********/
                   2099: char *subdirf(char fileres[])
                   2100: {
                   2101:   /* Caution optionfilefiname is hidden */
                   2102:   strcpy(tmpout,optionfilefiname);
                   2103:   strcat(tmpout,"/"); /* Add to the right */
                   2104:   strcat(tmpout,fileres);
                   2105:   return tmpout;
                   2106: }
                   2107: 
                   2108: /*************** function subdirf2 ***********/
                   2109: char *subdirf2(char fileres[], char *preop)
                   2110: {
1.314     brouard  2111:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
                   2112:  Errors in subdirf, 2, 3 while printing tmpout is
1.315     brouard  2113:  rewritten within the same printf. Workaround: many printfs */
1.126     brouard  2114:   /* Caution optionfilefiname is hidden */
                   2115:   strcpy(tmpout,optionfilefiname);
                   2116:   strcat(tmpout,"/");
                   2117:   strcat(tmpout,preop);
                   2118:   strcat(tmpout,fileres);
                   2119:   return tmpout;
                   2120: }
                   2121: 
                   2122: /*************** function subdirf3 ***********/
                   2123: char *subdirf3(char fileres[], char *preop, char *preop2)
                   2124: {
                   2125:   
                   2126:   /* Caution optionfilefiname is hidden */
                   2127:   strcpy(tmpout,optionfilefiname);
                   2128:   strcat(tmpout,"/");
                   2129:   strcat(tmpout,preop);
                   2130:   strcat(tmpout,preop2);
                   2131:   strcat(tmpout,fileres);
                   2132:   return tmpout;
                   2133: }
1.213     brouard  2134:  
                   2135: /*************** function subdirfext ***********/
                   2136: char *subdirfext(char fileres[], char *preop, char *postop)
                   2137: {
                   2138:   
                   2139:   strcpy(tmpout,preop);
                   2140:   strcat(tmpout,fileres);
                   2141:   strcat(tmpout,postop);
                   2142:   return tmpout;
                   2143: }
1.126     brouard  2144: 
1.213     brouard  2145: /*************** function subdirfext3 ***********/
                   2146: char *subdirfext3(char fileres[], char *preop, char *postop)
                   2147: {
                   2148:   
                   2149:   /* Caution optionfilefiname is hidden */
                   2150:   strcpy(tmpout,optionfilefiname);
                   2151:   strcat(tmpout,"/");
                   2152:   strcat(tmpout,preop);
                   2153:   strcat(tmpout,fileres);
                   2154:   strcat(tmpout,postop);
                   2155:   return tmpout;
                   2156: }
                   2157:  
1.162     brouard  2158: char *asc_diff_time(long time_sec, char ascdiff[])
                   2159: {
                   2160:   long sec_left, days, hours, minutes;
                   2161:   days = (time_sec) / (60*60*24);
                   2162:   sec_left = (time_sec) % (60*60*24);
                   2163:   hours = (sec_left) / (60*60) ;
                   2164:   sec_left = (sec_left) %(60*60);
                   2165:   minutes = (sec_left) /60;
                   2166:   sec_left = (sec_left) % (60);
                   2167:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   2168:   return ascdiff;
                   2169: }
                   2170: 
1.126     brouard  2171: /***************** f1dim *************************/
                   2172: extern int ncom; 
                   2173: extern double *pcom,*xicom;
                   2174: extern double (*nrfunc)(double []); 
                   2175:  
                   2176: double f1dim(double x) 
                   2177: { 
                   2178:   int j; 
                   2179:   double f;
                   2180:   double *xt; 
                   2181:  
                   2182:   xt=vector(1,ncom); 
                   2183:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   2184:   f=(*nrfunc)(xt); 
                   2185:   free_vector(xt,1,ncom); 
                   2186:   return f; 
                   2187: } 
                   2188: 
                   2189: /*****************brent *************************/
                   2190: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  2191: {
                   2192:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   2193:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   2194:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   2195:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   2196:    * returned function value. 
                   2197:   */
1.126     brouard  2198:   int iter; 
                   2199:   double a,b,d,etemp;
1.159     brouard  2200:   double fu=0,fv,fw,fx;
1.164     brouard  2201:   double ftemp=0.;
1.126     brouard  2202:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   2203:   double e=0.0; 
                   2204:  
                   2205:   a=(ax < cx ? ax : cx); 
                   2206:   b=(ax > cx ? ax : cx); 
                   2207:   x=w=v=bx; 
                   2208:   fw=fv=fx=(*f)(x); 
                   2209:   for (iter=1;iter<=ITMAX;iter++) { 
                   2210:     xm=0.5*(a+b); 
                   2211:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   2212:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   2213:     printf(".");fflush(stdout);
                   2214:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  2215: #ifdef DEBUGBRENT
1.126     brouard  2216:     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);
                   2217:     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);
                   2218:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   2219: #endif
                   2220:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   2221:       *xmin=x; 
                   2222:       return fx; 
                   2223:     } 
                   2224:     ftemp=fu;
                   2225:     if (fabs(e) > tol1) { 
                   2226:       r=(x-w)*(fx-fv); 
                   2227:       q=(x-v)*(fx-fw); 
                   2228:       p=(x-v)*q-(x-w)*r; 
                   2229:       q=2.0*(q-r); 
                   2230:       if (q > 0.0) p = -p; 
                   2231:       q=fabs(q); 
                   2232:       etemp=e; 
                   2233:       e=d; 
                   2234:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  2235:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  2236:       else { 
1.224     brouard  2237:                                d=p/q; 
                   2238:                                u=x+d; 
                   2239:                                if (u-a < tol2 || b-u < tol2) 
                   2240:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  2241:       } 
                   2242:     } else { 
                   2243:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2244:     } 
                   2245:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   2246:     fu=(*f)(u); 
                   2247:     if (fu <= fx) { 
                   2248:       if (u >= x) a=x; else b=x; 
                   2249:       SHFT(v,w,x,u) 
1.183     brouard  2250:       SHFT(fv,fw,fx,fu) 
                   2251:     } else { 
                   2252:       if (u < x) a=u; else b=u; 
                   2253:       if (fu <= fw || w == x) { 
1.224     brouard  2254:                                v=w; 
                   2255:                                w=u; 
                   2256:                                fv=fw; 
                   2257:                                fw=fu; 
1.183     brouard  2258:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  2259:                                v=u; 
                   2260:                                fv=fu; 
1.183     brouard  2261:       } 
                   2262:     } 
1.126     brouard  2263:   } 
                   2264:   nrerror("Too many iterations in brent"); 
                   2265:   *xmin=x; 
                   2266:   return fx; 
                   2267: } 
                   2268: 
                   2269: /****************** mnbrak ***********************/
                   2270: 
                   2271: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2272:            double (*func)(double)) 
1.183     brouard  2273: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2274: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2275: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2276: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2277:    */
1.126     brouard  2278:   double ulim,u,r,q, dum;
                   2279:   double fu; 
1.187     brouard  2280: 
                   2281:   double scale=10.;
                   2282:   int iterscale=0;
                   2283: 
                   2284:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2285:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2286: 
                   2287: 
                   2288:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2289:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2290:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2291:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2292:   /* } */
                   2293: 
1.126     brouard  2294:   if (*fb > *fa) { 
                   2295:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2296:     SHFT(dum,*fb,*fa,dum) 
                   2297:   } 
1.126     brouard  2298:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2299:   *fc=(*func)(*cx); 
1.183     brouard  2300: #ifdef DEBUG
1.224     brouard  2301:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2302:   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  2303: #endif
1.224     brouard  2304:   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  2305:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2306:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2307:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2308:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2309:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2310:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2311:       fu=(*func)(u); 
1.163     brouard  2312: #ifdef DEBUG
                   2313:       /* f(x)=A(x-u)**2+f(u) */
                   2314:       double A, fparabu; 
                   2315:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2316:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2317:       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);
                   2318:       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  2319:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2320:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2321:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2322:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2323: #endif 
1.184     brouard  2324: #ifdef MNBRAKORIGINAL
1.183     brouard  2325: #else
1.191     brouard  2326: /*       if (fu > *fc) { */
                   2327: /* #ifdef DEBUG */
                   2328: /*       printf("mnbrak4  fu > fc \n"); */
                   2329: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2330: /* #endif */
                   2331: /*     /\* 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 *\\/  *\/ */
                   2332: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2333: /*     dum=u; /\* Shifting c and u *\/ */
                   2334: /*     u = *cx; */
                   2335: /*     *cx = dum; */
                   2336: /*     dum = fu; */
                   2337: /*     fu = *fc; */
                   2338: /*     *fc =dum; */
                   2339: /*       } else { /\* end *\/ */
                   2340: /* #ifdef DEBUG */
                   2341: /*       printf("mnbrak3  fu < fc \n"); */
                   2342: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2343: /* #endif */
                   2344: /*     dum=u; /\* Shifting c and u *\/ */
                   2345: /*     u = *cx; */
                   2346: /*     *cx = dum; */
                   2347: /*     dum = fu; */
                   2348: /*     fu = *fc; */
                   2349: /*     *fc =dum; */
                   2350: /*       } */
1.224     brouard  2351: #ifdef DEBUGMNBRAK
                   2352:                 double A, fparabu; 
                   2353:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2354:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2355:      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);
                   2356:      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  2357: #endif
1.191     brouard  2358:       dum=u; /* Shifting c and u */
                   2359:       u = *cx;
                   2360:       *cx = dum;
                   2361:       dum = fu;
                   2362:       fu = *fc;
                   2363:       *fc =dum;
1.183     brouard  2364: #endif
1.162     brouard  2365:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2366: #ifdef DEBUG
1.224     brouard  2367:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2368:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2369: #endif
1.126     brouard  2370:       fu=(*func)(u); 
                   2371:       if (fu < *fc) { 
1.183     brouard  2372: #ifdef DEBUG
1.224     brouard  2373:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2374:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2375: #endif
                   2376:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2377:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2378: #ifdef DEBUG
                   2379:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2380: #endif
                   2381:       } 
1.162     brouard  2382:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2383: #ifdef DEBUG
1.224     brouard  2384:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2385:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2386: #endif
1.126     brouard  2387:       u=ulim; 
                   2388:       fu=(*func)(u); 
1.183     brouard  2389:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2390: #ifdef DEBUG
1.224     brouard  2391:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2392:       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  2393: #endif
1.126     brouard  2394:       u=(*cx)+GOLD*(*cx-*bx); 
                   2395:       fu=(*func)(u); 
1.224     brouard  2396: #ifdef DEBUG
                   2397:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2398:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2399: #endif
1.183     brouard  2400:     } /* end tests */
1.126     brouard  2401:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2402:     SHFT(*fa,*fb,*fc,fu) 
                   2403: #ifdef DEBUG
1.224     brouard  2404:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2405:       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  2406: #endif
                   2407:   } /* 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  2408: } 
                   2409: 
                   2410: /*************** linmin ************************/
1.162     brouard  2411: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2412: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2413: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2414: the value of func at the returned location p . This is actually all accomplished by calling the
                   2415: routines mnbrak and brent .*/
1.126     brouard  2416: int ncom; 
                   2417: double *pcom,*xicom;
                   2418: double (*nrfunc)(double []); 
                   2419:  
1.224     brouard  2420: #ifdef LINMINORIGINAL
1.126     brouard  2421: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2422: #else
                   2423: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2424: #endif
1.126     brouard  2425: { 
                   2426:   double brent(double ax, double bx, double cx, 
                   2427:               double (*f)(double), double tol, double *xmin); 
                   2428:   double f1dim(double x); 
                   2429:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2430:              double *fc, double (*func)(double)); 
                   2431:   int j; 
                   2432:   double xx,xmin,bx,ax; 
                   2433:   double fx,fb,fa;
1.187     brouard  2434: 
1.203     brouard  2435: #ifdef LINMINORIGINAL
                   2436: #else
                   2437:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2438: #endif
                   2439:   
1.126     brouard  2440:   ncom=n; 
                   2441:   pcom=vector(1,n); 
                   2442:   xicom=vector(1,n); 
                   2443:   nrfunc=func; 
                   2444:   for (j=1;j<=n;j++) { 
                   2445:     pcom[j]=p[j]; 
1.202     brouard  2446:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2447:   } 
1.187     brouard  2448: 
1.203     brouard  2449: #ifdef LINMINORIGINAL
                   2450:   xx=1.;
                   2451: #else
                   2452:   axs=0.0;
                   2453:   xxs=1.;
                   2454:   do{
                   2455:     xx= xxs;
                   2456: #endif
1.187     brouard  2457:     ax=0.;
                   2458:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2459:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2460:     /* 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))   */
                   2461:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2462:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2463:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2464:     /* 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  2465: #ifdef LINMINORIGINAL
                   2466: #else
                   2467:     if (fx != fx){
1.224     brouard  2468:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2469:                        printf("|");
                   2470:                        fprintf(ficlog,"|");
1.203     brouard  2471: #ifdef DEBUGLINMIN
1.224     brouard  2472:                        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  2473: #endif
                   2474:     }
1.224     brouard  2475:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2476: #endif
                   2477:   
1.191     brouard  2478: #ifdef DEBUGLINMIN
                   2479:   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  2480:   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  2481: #endif
1.224     brouard  2482: #ifdef LINMINORIGINAL
                   2483: #else
1.317     brouard  2484:   if(fb == fx){ /* Flat function in the direction */
                   2485:     xmin=xx;
1.224     brouard  2486:     *flat=1;
1.317     brouard  2487:   }else{
1.224     brouard  2488:     *flat=0;
                   2489: #endif
                   2490:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2491:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2492:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2493:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2494:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2495:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2496: #ifdef DEBUG
1.224     brouard  2497:   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);
                   2498:   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);
                   2499: #endif
                   2500: #ifdef LINMINORIGINAL
                   2501: #else
                   2502:                        }
1.126     brouard  2503: #endif
1.191     brouard  2504: #ifdef DEBUGLINMIN
                   2505:   printf("linmin end ");
1.202     brouard  2506:   fprintf(ficlog,"linmin end ");
1.191     brouard  2507: #endif
1.126     brouard  2508:   for (j=1;j<=n;j++) { 
1.203     brouard  2509: #ifdef LINMINORIGINAL
                   2510:     xi[j] *= xmin; 
                   2511: #else
                   2512: #ifdef DEBUGLINMIN
                   2513:     if(xxs <1.0)
                   2514:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2515: #endif
                   2516:     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) */
                   2517: #ifdef DEBUGLINMIN
                   2518:     if(xxs <1.0)
                   2519:       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 );
                   2520: #endif
                   2521: #endif
1.187     brouard  2522:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2523:   } 
1.191     brouard  2524: #ifdef DEBUGLINMIN
1.203     brouard  2525:   printf("\n");
1.191     brouard  2526:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2527:   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  2528:   for (j=1;j<=n;j++) { 
1.202     brouard  2529:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2530:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2531:     if(j % ncovmodel == 0){
1.191     brouard  2532:       printf("\n");
1.202     brouard  2533:       fprintf(ficlog,"\n");
                   2534:     }
1.191     brouard  2535:   }
1.203     brouard  2536: #else
1.191     brouard  2537: #endif
1.126     brouard  2538:   free_vector(xicom,1,n); 
                   2539:   free_vector(pcom,1,n); 
                   2540: } 
                   2541: 
                   2542: 
                   2543: /*************** powell ************************/
1.162     brouard  2544: /*
1.317     brouard  2545: Minimization of a function func of n variables. Input consists in an initial starting point
                   2546: p[1..n] ; an initial matrix xi[1..n][1..n]  whose columns contain the initial set of di-
                   2547: rections (usually the n unit vectors); and ftol, the fractional tolerance in the function value
                   2548: such that failure to decrease by more than this amount in one iteration signals doneness. On
1.162     brouard  2549: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2550: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2551:  */
1.224     brouard  2552: #ifdef LINMINORIGINAL
                   2553: #else
                   2554:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2555:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2556: #endif
1.126     brouard  2557: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2558:            double (*func)(double [])) 
                   2559: { 
1.224     brouard  2560: #ifdef LINMINORIGINAL
                   2561:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2562:              double (*func)(double [])); 
1.224     brouard  2563: #else 
1.241     brouard  2564:  void linmin(double p[], double xi[], int n, double *fret,
                   2565:             double (*func)(double []),int *flat); 
1.224     brouard  2566: #endif
1.239     brouard  2567:  int i,ibig,j,jk,k; 
1.126     brouard  2568:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2569:   double directest;
1.126     brouard  2570:   double fp,fptt;
                   2571:   double *xits;
                   2572:   int niterf, itmp;
                   2573: 
                   2574:   pt=vector(1,n); 
                   2575:   ptt=vector(1,n); 
                   2576:   xit=vector(1,n); 
                   2577:   xits=vector(1,n); 
                   2578:   *fret=(*func)(p); 
                   2579:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.338     brouard  2580:   rcurr_time = time(NULL);
                   2581:   fp=(*fret); /* Initialisation */
1.126     brouard  2582:   for (*iter=1;;++(*iter)) { 
                   2583:     ibig=0; 
                   2584:     del=0.0; 
1.157     brouard  2585:     rlast_time=rcurr_time;
                   2586:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2587:     rcurr_time = time(NULL);  
                   2588:     curr_time = *localtime(&rcurr_time);
1.337     brouard  2589:     /* 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); */
                   2590:     /* 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); */
                   2591:     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);
                   2592:     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  2593: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.324     brouard  2594:     fp=(*fret); /* From former iteration or initial value */
1.192     brouard  2595:     for (i=1;i<=n;i++) {
1.126     brouard  2596:       fprintf(ficrespow," %.12lf", p[i]);
                   2597:     }
1.239     brouard  2598:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2599:     printf("\n#model=  1      +     age ");
                   2600:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2601:     if(nagesqr==1){
1.241     brouard  2602:        printf("  + age*age  ");
                   2603:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2604:     }
                   2605:     for(j=1;j <=ncovmodel-2;j++){
                   2606:       if(Typevar[j]==0) {
                   2607:        printf("  +      V%d  ",Tvar[j]);
                   2608:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2609:       }else if(Typevar[j]==1) {
                   2610:        printf("  +    V%d*age ",Tvar[j]);
                   2611:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2612:       }else if(Typevar[j]==2) {
                   2613:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2614:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2615:       }
                   2616:     }
1.126     brouard  2617:     printf("\n");
1.239     brouard  2618: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2619: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2620:     fprintf(ficlog,"\n");
1.239     brouard  2621:     for(i=1,jk=1; i <=nlstate; i++){
                   2622:       for(k=1; k <=(nlstate+ndeath); k++){
                   2623:        if (k != i) {
                   2624:          printf("%d%d ",i,k);
                   2625:          fprintf(ficlog,"%d%d ",i,k);
                   2626:          for(j=1; j <=ncovmodel; j++){
                   2627:            printf("%12.7f ",p[jk]);
                   2628:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2629:            jk++; 
                   2630:          }
                   2631:          printf("\n");
                   2632:          fprintf(ficlog,"\n");
                   2633:        }
                   2634:       }
                   2635:     }
1.241     brouard  2636:     if(*iter <=3 && *iter >1){
1.157     brouard  2637:       tml = *localtime(&rcurr_time);
                   2638:       strcpy(strcurr,asctime(&tml));
                   2639:       rforecast_time=rcurr_time; 
1.126     brouard  2640:       itmp = strlen(strcurr);
                   2641:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2642:        strcurr[itmp-1]='\0';
1.162     brouard  2643:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2644:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  2645:       for(niterf=10;niterf<=30;niterf+=10){
1.241     brouard  2646:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2647:        forecast_time = *localtime(&rforecast_time);
                   2648:        strcpy(strfor,asctime(&forecast_time));
                   2649:        itmp = strlen(strfor);
                   2650:        if(strfor[itmp-1]=='\n')
                   2651:          strfor[itmp-1]='\0';
                   2652:        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);
                   2653:        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  2654:       }
                   2655:     }
1.187     brouard  2656:     for (i=1;i<=n;i++) { /* For each direction i */
                   2657:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2658:       fptt=(*fret); 
                   2659: #ifdef DEBUG
1.203     brouard  2660:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2661:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2662: #endif
1.203     brouard  2663:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2664:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2665: #ifdef LINMINORIGINAL
1.188     brouard  2666:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2667: #else
                   2668:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2669:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2670: #endif
                   2671:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2672:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2673:                                /* because that direction will be replaced unless the gain del is small */
                   2674:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2675:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2676:                                /* with the new direction. */
                   2677:                                del=fabs(fptt-(*fret)); 
                   2678:                                ibig=i; 
1.126     brouard  2679:       } 
                   2680: #ifdef DEBUG
                   2681:       printf("%d %.12e",i,(*fret));
                   2682:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2683:       for (j=1;j<=n;j++) {
1.224     brouard  2684:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2685:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2686:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2687:       }
                   2688:       for(j=1;j<=n;j++) {
1.225     brouard  2689:                                printf(" p(%d)=%.12e",j,p[j]);
                   2690:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2691:       }
                   2692:       printf("\n");
                   2693:       fprintf(ficlog,"\n");
                   2694: #endif
1.187     brouard  2695:     } /* end loop on each direction i */
                   2696:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2697:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2698:     /* New value of last point Pn is not computed, P(n-1) */
1.319     brouard  2699:     for(j=1;j<=n;j++) {
                   2700:       if(flatdir[j] >0){
                   2701:         printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2702:         fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
1.302     brouard  2703:       }
1.319     brouard  2704:       /* printf("\n"); */
                   2705:       /* fprintf(ficlog,"\n"); */
                   2706:     }
1.243     brouard  2707:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2708:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2709:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2710:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2711:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2712:       /* decreased of more than 3.84  */
                   2713:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2714:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2715:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2716:                        
1.188     brouard  2717:       /* Starting the program with initial values given by a former maximization will simply change */
                   2718:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2719:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2720:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2721: #ifdef DEBUG
                   2722:       int k[2],l;
                   2723:       k[0]=1;
                   2724:       k[1]=-1;
                   2725:       printf("Max: %.12e",(*func)(p));
                   2726:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2727:       for (j=1;j<=n;j++) {
                   2728:        printf(" %.12e",p[j]);
                   2729:        fprintf(ficlog," %.12e",p[j]);
                   2730:       }
                   2731:       printf("\n");
                   2732:       fprintf(ficlog,"\n");
                   2733:       for(l=0;l<=1;l++) {
                   2734:        for (j=1;j<=n;j++) {
                   2735:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2736:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2737:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2738:        }
                   2739:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2740:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2741:       }
                   2742: #endif
                   2743: 
                   2744:       free_vector(xit,1,n); 
                   2745:       free_vector(xits,1,n); 
                   2746:       free_vector(ptt,1,n); 
                   2747:       free_vector(pt,1,n); 
                   2748:       return; 
1.192     brouard  2749:     } /* enough precision */ 
1.240     brouard  2750:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2751:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2752:       ptt[j]=2.0*p[j]-pt[j]; 
                   2753:       xit[j]=p[j]-pt[j]; 
                   2754:       pt[j]=p[j]; 
                   2755:     } 
1.181     brouard  2756:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2757: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2758:                if (*iter <=4) {
1.225     brouard  2759: #else
                   2760: #endif
1.224     brouard  2761: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2762: #else
1.161     brouard  2763:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2764: #endif
1.162     brouard  2765:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2766:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2767:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2768:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2769:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2770:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2771:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2772:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2773:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2774:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2775:       /* mu² and del² are equal when f3=f1 */
                   2776:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2777:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2778:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2779:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2780: #ifdef NRCORIGINAL
                   2781:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2782: #else
                   2783:       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  2784:       t= t- del*SQR(fp-fptt);
1.183     brouard  2785: #endif
1.202     brouard  2786:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2787: #ifdef DEBUG
1.181     brouard  2788:       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);
                   2789:       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  2790:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2791:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2792:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2793:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2794:       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);
                   2795:       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);
                   2796: #endif
1.183     brouard  2797: #ifdef POWELLORIGINAL
                   2798:       if (t < 0.0) { /* Then we use it for new direction */
                   2799: #else
1.182     brouard  2800:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2801:                                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  2802:         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  2803:         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  2804:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2805:       } 
1.181     brouard  2806:       if (directest < 0.0) { /* Then we use it for new direction */
                   2807: #endif
1.191     brouard  2808: #ifdef DEBUGLINMIN
1.234     brouard  2809:        printf("Before linmin in direction P%d-P0\n",n);
                   2810:        for (j=1;j<=n;j++) {
                   2811:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2812:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2813:          if(j % ncovmodel == 0){
                   2814:            printf("\n");
                   2815:            fprintf(ficlog,"\n");
                   2816:          }
                   2817:        }
1.224     brouard  2818: #endif
                   2819: #ifdef LINMINORIGINAL
1.234     brouard  2820:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2821: #else
1.234     brouard  2822:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2823:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2824: #endif
1.234     brouard  2825:        
1.191     brouard  2826: #ifdef DEBUGLINMIN
1.234     brouard  2827:        for (j=1;j<=n;j++) { 
                   2828:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2829:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2830:          if(j % ncovmodel == 0){
                   2831:            printf("\n");
                   2832:            fprintf(ficlog,"\n");
                   2833:          }
                   2834:        }
1.224     brouard  2835: #endif
1.234     brouard  2836:        for (j=1;j<=n;j++) { 
                   2837:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2838:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2839:        }
1.224     brouard  2840: #ifdef LINMINORIGINAL
                   2841: #else
1.234     brouard  2842:        for (j=1, flatd=0;j<=n;j++) {
                   2843:          if(flatdir[j]>0)
                   2844:            flatd++;
                   2845:        }
                   2846:        if(flatd >0){
1.255     brouard  2847:          printf("%d flat directions: ",flatd);
                   2848:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  2849:          for (j=1;j<=n;j++) { 
                   2850:            if(flatdir[j]>0){
                   2851:              printf("%d ",j);
                   2852:              fprintf(ficlog,"%d ",j);
                   2853:            }
                   2854:          }
                   2855:          printf("\n");
                   2856:          fprintf(ficlog,"\n");
1.319     brouard  2857: #ifdef FLATSUP
                   2858:           free_vector(xit,1,n); 
                   2859:           free_vector(xits,1,n); 
                   2860:           free_vector(ptt,1,n); 
                   2861:           free_vector(pt,1,n); 
                   2862:           return;
                   2863: #endif
1.234     brouard  2864:        }
1.191     brouard  2865: #endif
1.234     brouard  2866:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2867:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2868:        
1.126     brouard  2869: #ifdef DEBUG
1.234     brouard  2870:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2871:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2872:        for(j=1;j<=n;j++){
                   2873:          printf(" %lf",xit[j]);
                   2874:          fprintf(ficlog," %lf",xit[j]);
                   2875:        }
                   2876:        printf("\n");
                   2877:        fprintf(ficlog,"\n");
1.126     brouard  2878: #endif
1.192     brouard  2879:       } /* end of t or directest negative */
1.224     brouard  2880: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2881: #else
1.234     brouard  2882:       } /* end if (fptt < fp)  */
1.192     brouard  2883: #endif
1.225     brouard  2884: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2885:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2886: #else
1.224     brouard  2887: #endif
1.234     brouard  2888:                } /* loop iteration */ 
1.126     brouard  2889: } 
1.234     brouard  2890:   
1.126     brouard  2891: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2892:   
1.235     brouard  2893:   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  2894:   {
1.338     brouard  2895:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij . Nicely done
1.279     brouard  2896:      *   (and selected quantitative values in nres)
                   2897:      *  by left multiplying the unit
                   2898:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   2899:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   2900:      * Wx is row vector: population in state 1, population in state 2, population dead
                   2901:      * or prevalence in state 1, prevalence in state 2, 0
                   2902:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   2903:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   2904:      * Output is prlim.
                   2905:      * Initial matrix pimij 
                   2906:      */
1.206     brouard  2907:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2908:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2909:   /*  0,                   0                  , 1} */
                   2910:   /*
                   2911:    * and after some iteration: */
                   2912:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2913:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2914:   /*  0,                   0                  , 1} */
                   2915:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2916:   /* {0.51571254859325999, 0.4842874514067399, */
                   2917:   /*  0.51326036147820708, 0.48673963852179264} */
                   2918:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2919:     
1.332     brouard  2920:     int i, ii,j,k, k1;
1.209     brouard  2921:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2922:   /* double **matprod2(); */ /* test */
1.218     brouard  2923:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2924:   double **newm;
1.209     brouard  2925:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2926:   int ncvloop=0;
1.288     brouard  2927:   int first=0;
1.169     brouard  2928:   
1.209     brouard  2929:   min=vector(1,nlstate);
                   2930:   max=vector(1,nlstate);
                   2931:   meandiff=vector(1,nlstate);
                   2932: 
1.218     brouard  2933:        /* Starting with matrix unity */
1.126     brouard  2934:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2935:     for (j=1;j<=nlstate+ndeath;j++){
                   2936:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2937:     }
1.169     brouard  2938:   
                   2939:   cov[1]=1.;
                   2940:   
                   2941:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2942:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2943:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2944:     ncvloop++;
1.126     brouard  2945:     newm=savm;
                   2946:     /* Covariates have to be included here again */
1.138     brouard  2947:     cov[2]=agefin;
1.319     brouard  2948:      if(nagesqr==1){
                   2949:       cov[3]= agefin*agefin;
                   2950:      }
1.332     brouard  2951:      /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   2952:      /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   2953:      for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   2954:        if(Typevar[k1]==1){ /* A product with age */
                   2955:         cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   2956:        }else{
                   2957:         cov[2+nagesqr+k1]=precov[nres][k1];
                   2958:        }
                   2959:      }/* End of loop on model equation */
                   2960:      
                   2961: /* Start of old code (replaced by a loop on position in the model equation */
                   2962:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only of the model *\/ */
                   2963:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   2964:     /*   /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; *\/ */
                   2965:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TnsdVar[TvarsD[k]])]; */
                   2966:     /*   /\* model = 1 +age + V1*V3 + age*V1 + V2 + V1 + age*V2 + V3 + V3*age + V1*V2  */
                   2967:     /*    * k                  1        2      3    4      5      6     7        8 */
                   2968:     /*    *cov[]   1    2      3        4      5    6      7      8     9       10 */
                   2969:     /*    *TypeVar[k]          2        1      0    0      1      0     1        2 */
                   2970:     /*    *Dummy[k]            0        2      0    0      2      0     2        0 */
                   2971:     /*    *Tvar[k]             4        1      2    1      2      3     3        5 */
                   2972:     /*    *nsd=3                              (1)  (2)           (3) */
                   2973:     /*    *TvarsD[nsd]                      [1]=2    1             3 */
                   2974:     /*    *TnsdVar                          [2]=2 [1]=1         [3]=3 */
                   2975:     /*    *TvarsDind[nsd](=k)               [1]=3 [2]=4         [3]=6 */
                   2976:     /*    *Tage[]                  [1]=1                  [2]=2      [3]=3 */
                   2977:     /*    *Tvard[]       [1][1]=1                                           [2][1]=1 */
                   2978:     /*    *                   [1][2]=3                                           [2][2]=2 */
                   2979:     /*    *Tprod[](=k)     [1]=1                                              [2]=8 */
                   2980:     /*    *TvarsDp(=Tvar)   [1]=1            [2]=2             [3]=3          [4]=5 */
                   2981:     /*    *TvarD (=k)       [1]=1            [2]=3 [3]=4       [3]=6          [4]=6 */
                   2982:     /*    *TvarsDpType */
                   2983:     /*    *si model= 1 + age + V3 + V2*age + V2 + V3*age */
                   2984:     /*    * nsd=1              (1)           (2) */
                   2985:     /*    *TvarsD[nsd]          3             2 */
                   2986:     /*    *TnsdVar           (3)=1          (2)=2 */
                   2987:     /*    *TvarsDind[nsd](=k)  [1]=1        [2]=3 */
                   2988:     /*    *Tage[]                  [1]=2           [2]= 3    */
                   2989:     /*    *\/ */
                   2990:     /*   /\* cov[++k1]=nbcode[TvarsD[k]][codtabm(ij,k)]; *\/ */
                   2991:     /*   /\* 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)); *\/ */
                   2992:     /* } */
                   2993:     /* for (k=1; k<=nsq;k++) { /\* For single quantitative varying covariates only of the model *\/ */
                   2994:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   2995:     /*   /\* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 *\/ */
                   2996:     /*   /\* cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   2997:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][resultmodel[nres][k1]] */
                   2998:     /*   /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   2999:     /*   /\* 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]); *\/ */
                   3000:     /* } */
                   3001:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   3002:     /*   if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   3003:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3004:     /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   3005:     /*   } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   3006:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   3007:     /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   3008:     /*   } */
                   3009:     /*   /\* 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]); *\/ */
                   3010:     /* } */
                   3011:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   3012:     /*   /\* 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]); *\/ */
                   3013:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3014:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3015:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3016:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3017:     /*         }else{ */
                   3018:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3019:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   3020:     /*         } */
                   3021:     /*   }else{ */
                   3022:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3023:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3024:     /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   3025:     /*         }else{ */
                   3026:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3027:     /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   3028:     /*         } */
                   3029:     /*   } */
                   3030:     /* } /\* End product without age *\/ */
                   3031: /* ENd of old code */
1.138     brouard  3032:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3033:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3034:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  3035:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3036:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.319     brouard  3037:     /* age and covariate values of ij are in 'cov' */
1.142     brouard  3038:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  3039:     
1.126     brouard  3040:     savm=oldm;
                   3041:     oldm=newm;
1.209     brouard  3042: 
                   3043:     for(j=1; j<=nlstate; j++){
                   3044:       max[j]=0.;
                   3045:       min[j]=1.;
                   3046:     }
                   3047:     for(i=1;i<=nlstate;i++){
                   3048:       sumnew=0;
                   3049:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   3050:       for(j=1; j<=nlstate; j++){ 
                   3051:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   3052:        max[j]=FMAX(max[j],prlim[i][j]);
                   3053:        min[j]=FMIN(min[j],prlim[i][j]);
                   3054:       }
                   3055:     }
                   3056: 
1.126     brouard  3057:     maxmax=0.;
1.209     brouard  3058:     for(j=1; j<=nlstate; j++){
                   3059:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   3060:       maxmax=FMAX(maxmax,meandiff[j]);
                   3061:       /* 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  3062:     } /* j loop */
1.203     brouard  3063:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  3064:     /* 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  3065:     if(maxmax < ftolpl){
1.209     brouard  3066:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   3067:       free_vector(min,1,nlstate);
                   3068:       free_vector(max,1,nlstate);
                   3069:       free_vector(meandiff,1,nlstate);
1.126     brouard  3070:       return prlim;
                   3071:     }
1.288     brouard  3072:   } /* agefin loop */
1.208     brouard  3073:     /* After some age loop it doesn't converge */
1.288     brouard  3074:   if(!first){
                   3075:     first=1;
                   3076:     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  3077:     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);
                   3078:   }else if (first >=1 && first <10){
                   3079:     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);
                   3080:     first++;
                   3081:   }else if (first ==10){
                   3082:     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);
                   3083:     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");
                   3084:     fprintf(ficlog,"Warning: the stable prevalence no convergence; too many cases, giving up noticing, even in log file\n");
                   3085:     first++;
1.288     brouard  3086:   }
                   3087: 
1.209     brouard  3088:   /* 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); */
                   3089:   free_vector(min,1,nlstate);
                   3090:   free_vector(max,1,nlstate);
                   3091:   free_vector(meandiff,1,nlstate);
1.208     brouard  3092:   
1.169     brouard  3093:   return prlim; /* should not reach here */
1.126     brouard  3094: }
                   3095: 
1.217     brouard  3096: 
                   3097:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   3098: 
1.218     brouard  3099:  /* 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) */
                   3100:  /* 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  3101:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  3102: {
1.264     brouard  3103:   /* 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  3104:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   3105:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   3106:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   3107:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   3108:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   3109:   /* Initial matrix pimij */
                   3110:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   3111:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   3112:   /*  0,                   0                  , 1} */
                   3113:   /*
                   3114:    * and after some iteration: */
                   3115:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   3116:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   3117:   /*  0,                   0                  , 1} */
                   3118:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   3119:   /* {0.51571254859325999, 0.4842874514067399, */
                   3120:   /*  0.51326036147820708, 0.48673963852179264} */
                   3121:   /* If we start from prlim again, prlim tends to a constant matrix */
                   3122: 
1.332     brouard  3123:   int i, ii,j,k, k1;
1.247     brouard  3124:   int first=0;
1.217     brouard  3125:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   3126:   /* double **matprod2(); */ /* test */
                   3127:   double **out, cov[NCOVMAX+1], **bmij();
                   3128:   double **newm;
1.218     brouard  3129:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   3130:   double        **oldm, **savm;  /* for use */
                   3131: 
1.217     brouard  3132:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   3133:   int ncvloop=0;
                   3134:   
                   3135:   min=vector(1,nlstate);
                   3136:   max=vector(1,nlstate);
                   3137:   meandiff=vector(1,nlstate);
                   3138: 
1.266     brouard  3139:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   3140:   oldm=oldms; savm=savms;
                   3141:   
                   3142:   /* Starting with matrix unity */
                   3143:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   3144:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  3145:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3146:     }
                   3147:   
                   3148:   cov[1]=1.;
                   3149:   
                   3150:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3151:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  3152:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  3153:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   3154:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  3155:     ncvloop++;
1.218     brouard  3156:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   3157:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  3158:     /* Covariates have to be included here again */
                   3159:     cov[2]=agefin;
1.319     brouard  3160:     if(nagesqr==1){
1.217     brouard  3161:       cov[3]= agefin*agefin;;
1.319     brouard  3162:     }
1.332     brouard  3163:     for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   3164:       if(Typevar[k1]==1){ /* A product with age */
                   3165:        cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.242     brouard  3166:       }else{
1.332     brouard  3167:        cov[2+nagesqr+k1]=precov[nres][k1];
1.242     brouard  3168:       }
1.332     brouard  3169:     }/* End of loop on model equation */
                   3170: 
                   3171: /* Old code */ 
                   3172: 
                   3173:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   3174:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   3175:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; */
                   3176:     /*   /\* 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)); *\/ */
                   3177:     /* } */
                   3178:     /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   3179:     /* /\*   /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3180:     /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3181:     /* /\*   /\\* 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])]); *\\/ *\/ */
                   3182:     /* /\* } *\/ */
                   3183:     /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3184:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3185:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3186:     /*   /\* 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]); *\/ */
                   3187:     /* } */
                   3188:     /* /\* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; *\/ */
                   3189:     /* /\* for (k=1; k<=cptcovprod;k++) /\\* Useless *\\/ *\/ */
                   3190:     /* /\*   /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\\/ *\/ */
                   3191:     /* /\*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3192:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   3193:     /*   /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age *\\/ ERROR ???*\/ */
                   3194:     /*   if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3195:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3196:     /*   } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3197:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   3198:     /*   } */
                   3199:     /*   /\* 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]); *\/ */
                   3200:     /* } */
                   3201:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   3202:     /*   /\* 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]); *\/ */
                   3203:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3204:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3205:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3206:     /*         }else{ */
                   3207:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3208:     /*         } */
                   3209:     /*   }else{ */
                   3210:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3211:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3212:     /*         }else{ */
                   3213:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3214:     /*         } */
                   3215:     /*   } */
                   3216:     /* } */
1.217     brouard  3217:     
                   3218:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3219:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3220:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   3221:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3222:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  3223:                /* ij should be linked to the correct index of cov */
                   3224:                /* age and covariate values ij are in 'cov', but we need to pass
                   3225:                 * ij for the observed prevalence at age and status and covariate
                   3226:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   3227:                 */
                   3228:     /* 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 *\/ */
                   3229:     /* 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 *\/ */
                   3230:     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  3231:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  3232:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   3233:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   3234:     /*         printf("%d newm= ",i); */
                   3235:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3236:     /*           printf("%f ",newm[i][j]); */
                   3237:     /*         } */
                   3238:     /*         printf("oldm * "); */
                   3239:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3240:     /*           printf("%f ",oldm[i][j]); */
                   3241:     /*         } */
1.268     brouard  3242:     /*         printf(" bmmij "); */
1.266     brouard  3243:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3244:     /*           printf("%f ",pmmij[i][j]); */
                   3245:     /*         } */
                   3246:     /*         printf("\n"); */
                   3247:     /*   } */
                   3248:     /* } */
1.217     brouard  3249:     savm=oldm;
                   3250:     oldm=newm;
1.266     brouard  3251: 
1.217     brouard  3252:     for(j=1; j<=nlstate; j++){
                   3253:       max[j]=0.;
                   3254:       min[j]=1.;
                   3255:     }
                   3256:     for(j=1; j<=nlstate; j++){ 
                   3257:       for(i=1;i<=nlstate;i++){
1.234     brouard  3258:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   3259:        bprlim[i][j]= newm[i][j];
                   3260:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   3261:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  3262:       }
                   3263:     }
1.218     brouard  3264:                
1.217     brouard  3265:     maxmax=0.;
                   3266:     for(i=1; i<=nlstate; i++){
1.318     brouard  3267:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column, could be nan! */
1.217     brouard  3268:       maxmax=FMAX(maxmax,meandiff[i]);
                   3269:       /* 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  3270:     } /* i loop */
1.217     brouard  3271:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  3272:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3273:     if(maxmax < ftolpl){
1.220     brouard  3274:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3275:       free_vector(min,1,nlstate);
                   3276:       free_vector(max,1,nlstate);
                   3277:       free_vector(meandiff,1,nlstate);
                   3278:       return bprlim;
                   3279:     }
1.288     brouard  3280:   } /* agefin loop */
1.217     brouard  3281:     /* After some age loop it doesn't converge */
1.288     brouard  3282:   if(!first){
1.247     brouard  3283:     first=1;
                   3284:     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\
                   3285: 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);
                   3286:   }
                   3287:   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  3288: 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);
                   3289:   /* 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); */
                   3290:   free_vector(min,1,nlstate);
                   3291:   free_vector(max,1,nlstate);
                   3292:   free_vector(meandiff,1,nlstate);
                   3293:   
                   3294:   return bprlim; /* should not reach here */
                   3295: }
                   3296: 
1.126     brouard  3297: /*************** transition probabilities ***************/ 
                   3298: 
                   3299: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   3300: {
1.138     brouard  3301:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  3302:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  3303:      model to the ncovmodel covariates (including constant and age).
                   3304:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3305:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3306:      ncth covariate in the global vector x is given by the formula:
                   3307:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3308:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3309:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3310:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  3311:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  3312:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  3313:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  3314:   */
                   3315:   double s1, lnpijopii;
1.126     brouard  3316:   /*double t34;*/
1.164     brouard  3317:   int i,j, nc, ii, jj;
1.126     brouard  3318: 
1.223     brouard  3319:   for(i=1; i<= nlstate; i++){
                   3320:     for(j=1; j<i;j++){
                   3321:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3322:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3323:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3324:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3325:       }
                   3326:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3327:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3328:     }
                   3329:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3330:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3331:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3332:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3333:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3334:       }
                   3335:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3336:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3337:     }
                   3338:   }
1.218     brouard  3339:   
1.223     brouard  3340:   for(i=1; i<= nlstate; i++){
                   3341:     s1=0;
                   3342:     for(j=1; j<i; j++){
1.339     brouard  3343:       /* printf("debug1 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  3344:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3345:     }
                   3346:     for(j=i+1; j<=nlstate+ndeath; j++){
1.339     brouard  3347:       /* printf("debug2 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  3348:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3349:     }
                   3350:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3351:     ps[i][i]=1./(s1+1.);
                   3352:     /* Computing other pijs */
                   3353:     for(j=1; j<i; j++)
1.325     brouard  3354:       ps[i][j]= exp(ps[i][j])*ps[i][i];/* Bug valgrind */
1.223     brouard  3355:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3356:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3357:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3358:   } /* end i */
1.218     brouard  3359:   
1.223     brouard  3360:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3361:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3362:       ps[ii][jj]=0;
                   3363:       ps[ii][ii]=1;
                   3364:     }
                   3365:   }
1.294     brouard  3366: 
                   3367: 
1.223     brouard  3368:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3369:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3370:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3371:   /*   } */
                   3372:   /*   printf("\n "); */
                   3373:   /* } */
                   3374:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3375:   /*
                   3376:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  3377:                goto end;*/
1.266     brouard  3378:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  3379: }
                   3380: 
1.218     brouard  3381: /*************** backward transition probabilities ***************/ 
                   3382: 
                   3383:  /* 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 ) */
                   3384: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   3385:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   3386: {
1.302     brouard  3387:   /* 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  3388:    * 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  3389:    */
1.218     brouard  3390:   int i, ii, j,k;
1.222     brouard  3391:   
                   3392:   double **out, **pmij();
                   3393:   double sumnew=0.;
1.218     brouard  3394:   double agefin;
1.292     brouard  3395:   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  3396:   double **dnewm, **dsavm, **doldm;
                   3397:   double **bbmij;
                   3398:   
1.218     brouard  3399:   doldm=ddoldms; /* global pointers */
1.222     brouard  3400:   dnewm=ddnewms;
                   3401:   dsavm=ddsavms;
1.318     brouard  3402: 
                   3403:   /* Debug */
                   3404:   /* printf("Bmij ij=%d, cov[2}=%f\n", ij, cov[2]); */
1.222     brouard  3405:   agefin=cov[2];
1.268     brouard  3406:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  3407:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  3408:      the observed prevalence (with this covariate ij) at beginning of transition */
                   3409:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  3410: 
                   3411:   /* P_x */
1.325     brouard  3412:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm *//* Bug valgrind */
1.268     brouard  3413:   /* outputs pmmij which is a stochastic matrix in row */
                   3414: 
                   3415:   /* Diag(w_x) */
1.292     brouard  3416:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  3417:   sumnew=0.;
1.269     brouard  3418:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  3419:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  3420:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  3421:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   3422:   }
                   3423:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   3424:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3425:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  3426:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  3427:     }
                   3428:   }else{
                   3429:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3430:       for (j=1;j<=nlstate+ndeath;j++)
                   3431:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   3432:     }
                   3433:     /* if(sumnew <0.9){ */
                   3434:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   3435:     /* } */
                   3436:   }
                   3437:   k3=0.0;  /* We put the last diagonal to 0 */
                   3438:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   3439:       doldm[ii][ii]= k3;
                   3440:   }
                   3441:   /* End doldm, At the end doldm is diag[(w_i)] */
                   3442:   
1.292     brouard  3443:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   3444:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  3445: 
1.292     brouard  3446:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  3447:   /* 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  3448:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  3449:     sumnew=0.;
1.222     brouard  3450:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  3451:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  3452:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  3453:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  3454:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  3455:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  3456:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3457:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  3458:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3459:        /* }else */
1.268     brouard  3460:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   3461:     } /*End ii */
                   3462:   } /* 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 */
                   3463: 
1.292     brouard  3464:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  3465:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  3466:   /* end bmij */
1.266     brouard  3467:   return ps; /*pointer is unchanged */
1.218     brouard  3468: }
1.217     brouard  3469: /*************** transition probabilities ***************/ 
                   3470: 
1.218     brouard  3471: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  3472: {
                   3473:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3474:      computes the probability to be observed in state j being in state i by appying the
                   3475:      model to the ncovmodel covariates (including constant and age).
                   3476:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3477:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3478:      ncth covariate in the global vector x is given by the formula:
                   3479:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3480:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3481:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3482:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3483:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   3484:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3485:   */
                   3486:   double s1, lnpijopii;
                   3487:   /*double t34;*/
                   3488:   int i,j, nc, ii, jj;
                   3489: 
1.234     brouard  3490:   for(i=1; i<= nlstate; i++){
                   3491:     for(j=1; j<i;j++){
                   3492:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3493:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3494:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3495:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3496:       }
                   3497:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3498:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3499:     }
                   3500:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3501:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3502:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3503:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3504:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3505:       }
                   3506:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3507:     }
                   3508:   }
                   3509:   
                   3510:   for(i=1; i<= nlstate; i++){
                   3511:     s1=0;
                   3512:     for(j=1; j<i; j++){
                   3513:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3514:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3515:     }
                   3516:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3517:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3518:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3519:     }
                   3520:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3521:     ps[i][i]=1./(s1+1.);
                   3522:     /* Computing other pijs */
                   3523:     for(j=1; j<i; j++)
                   3524:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3525:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3526:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3527:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3528:   } /* end i */
                   3529:   
                   3530:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3531:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3532:       ps[ii][jj]=0;
                   3533:       ps[ii][ii]=1;
                   3534:     }
                   3535:   }
1.296     brouard  3536:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  3537:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3538:     s1=0.;
                   3539:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   3540:       s1+=ps[ii][jj];
                   3541:     }
                   3542:     for(ii=1; ii<= nlstate; ii++){
                   3543:       ps[ii][jj]=ps[ii][jj]/s1;
                   3544:     }
                   3545:   }
                   3546:   /* Transposition */
                   3547:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3548:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   3549:       s1=ps[ii][jj];
                   3550:       ps[ii][jj]=ps[jj][ii];
                   3551:       ps[jj][ii]=s1;
                   3552:     }
                   3553:   }
                   3554:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3555:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3556:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3557:   /*   } */
                   3558:   /*   printf("\n "); */
                   3559:   /* } */
                   3560:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3561:   /*
                   3562:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3563:     goto end;*/
                   3564:   return ps;
1.217     brouard  3565: }
                   3566: 
                   3567: 
1.126     brouard  3568: /**************** Product of 2 matrices ******************/
                   3569: 
1.145     brouard  3570: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  3571: {
                   3572:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3573:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3574:   /* in, b, out are matrice of pointers which should have been initialized 
                   3575:      before: only the contents of out is modified. The function returns
                   3576:      a pointer to pointers identical to out */
1.145     brouard  3577:   int i, j, k;
1.126     brouard  3578:   for(i=nrl; i<= nrh; i++)
1.145     brouard  3579:     for(k=ncolol; k<=ncoloh; k++){
                   3580:       out[i][k]=0.;
                   3581:       for(j=ncl; j<=nch; j++)
                   3582:        out[i][k] +=in[i][j]*b[j][k];
                   3583:     }
1.126     brouard  3584:   return out;
                   3585: }
                   3586: 
                   3587: 
                   3588: /************* Higher Matrix Product ***************/
                   3589: 
1.235     brouard  3590: 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  3591: {
1.336     brouard  3592:   /* Already optimized with precov.
                   3593:      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  3594:      'nhstepm*hstepm*stepm' months (i.e. until
                   3595:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3596:      nhstepm*hstepm matrices. 
                   3597:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3598:      (typically every 2 years instead of every month which is too big 
                   3599:      for the memory).
                   3600:      Model is determined by parameters x and covariates have to be 
                   3601:      included manually here. 
                   3602: 
                   3603:      */
                   3604: 
1.330     brouard  3605:   int i, j, d, h, k, k1;
1.131     brouard  3606:   double **out, cov[NCOVMAX+1];
1.126     brouard  3607:   double **newm;
1.187     brouard  3608:   double agexact;
1.214     brouard  3609:   double agebegin, ageend;
1.126     brouard  3610: 
                   3611:   /* Hstepm could be zero and should return the unit matrix */
                   3612:   for (i=1;i<=nlstate+ndeath;i++)
                   3613:     for (j=1;j<=nlstate+ndeath;j++){
                   3614:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3615:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3616:     }
                   3617:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3618:   for(h=1; h <=nhstepm; h++){
                   3619:     for(d=1; d <=hstepm; d++){
                   3620:       newm=savm;
                   3621:       /* Covariates have to be included here again */
                   3622:       cov[1]=1.;
1.214     brouard  3623:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3624:       cov[2]=agexact;
1.319     brouard  3625:       if(nagesqr==1){
1.227     brouard  3626:        cov[3]= agexact*agexact;
1.319     brouard  3627:       }
1.330     brouard  3628:       /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   3629:       /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   3630:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.332     brouard  3631:        if(Typevar[k1]==1){ /* A product with age */
                   3632:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   3633:        }else{
                   3634:          cov[2+nagesqr+k1]=precov[nres][k1];
                   3635:        }
                   3636:       }/* End of loop on model equation */
                   3637:        /* Old code */ 
                   3638: /*     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /\* Single dummy  *\/ */
                   3639: /* /\*    V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) *\/ */
                   3640: /* /\*       for (k=1; k<=nsd;k++) { /\\* For single dummy covariates only *\\/ *\/ */
                   3641: /* /\* /\\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\\/ *\/ */
                   3642: /*     /\* codtabm(ij,k)  (1 & (ij-1) >> (k-1))+1 *\/ */
                   3643: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3644: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3645: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
                   3646: /* /\*    nsd         1   2                              3 *\/ /\* Counting single dummies covar fixed or tv *\/ */
                   3647: /* /\*TvarsD[nsd]     4   3                              1 *\/ /\* ID of single dummy cova fixed or timevary*\/ */
                   3648: /* /\*TvarsDind[k]    2   3                              9 *\/ /\* position K of single dummy cova *\/ */
                   3649: /*       /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];or [codtabm(ij,TnsdVar[TvarsD[k]] *\/ */
                   3650: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]]; */
                   3651: /*       /\* 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]])); *\/ */
                   3652: /*       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); */
                   3653: /*       printf("hpxij new Dummy precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3654: /*     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /\* Single quantitative variables  *\/ */
                   3655: /*       /\* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline *\/ */
                   3656: /*       cov[2+nagesqr+k1]=Tqresult[nres][resultmodel[nres][k1]];  */
                   3657: /*       /\* for (k=1; k<=nsq;k++) { /\\* For single varying covariates only *\\/ *\/ */
                   3658: /*       /\*   /\\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\\/ *\/ */
                   3659: /*       /\*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   3660: /*       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]]); */
                   3661: /*       printf("hpxij new Quanti precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3662: /*     }else if( Dummy[k1]==2 ){ /\* For dummy with age product *\/ */
                   3663: /*       /\* Tvar[k1] Variable in the age product age*V1 is 1 *\/ */
                   3664: /*       /\* [Tinvresult[nres][V1] is its value in the resultline nres *\/ */
                   3665: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvar[k1]]*cov[2]; */
                   3666: /*       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]); */
                   3667: /*       printf("hpxij new Dummy with age product precov[nres=%d][k1=%d]=%.4f * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3668: 
                   3669: /*       /\* cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];    *\/ */
                   3670: /*       /\* for (k=1; k<=cptcovage;k++){ /\\* For product with age V1+V1*age +V4 +age*V3 *\\/ *\/ */
                   3671: /*       /\* 1+2 Tage[1]=2 TVar[2]=1 Dummy[2]=2, Tage[2]=4 TVar[4]=3 Dummy[4]=3 quant*\/ */
                   3672: /*       /\* *\/ */
1.330     brouard  3673: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3674: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3675: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
1.332     brouard  3676: /* /\*cptcovage=2                   1               2      *\/ */
                   3677: /* /\*Tage[k]=                      5               8      *\/  */
                   3678: /*     }else if( Dummy[k1]==3 ){ /\* For quant with age product *\/ */
                   3679: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];        */
                   3680: /*       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]]); */
                   3681: /*       printf("hpxij new Quanti with age product precov[nres=%d][k1=%d] * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3682: /*       /\* if(Dummy[Tage[k]]== 2){ /\\* dummy with age *\\/ *\/ */
                   3683: /*       /\* /\\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\\* dummy with age *\\\/ *\\/ *\/ */
                   3684: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\\/ *\/ */
                   3685: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\\/ *\/ */
                   3686: /*       /\*   cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\/ */
                   3687: /*       /\*   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); *\/ */
                   3688: /*       /\* } else if(Dummy[Tage[k]]== 3){ /\\* quantitative with age *\\/ *\/ */
                   3689: /*       /\*   cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; *\/ */
                   3690: /*       /\* } *\/ */
                   3691: /*       /\* 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]); *\/ */
                   3692: /*     }else if(Typevar[k1]==2 ){ /\* For product (not with age) *\/ */
                   3693: /* /\*       for (k=1; k<=cptcovprod;k++){ /\\*  For product without age *\\/ *\/ */
                   3694: /* /\* /\\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\\/ *\/ */
                   3695: /* /\* /\\*    k        1  2   3   4     5    6    7     8    9 *\\/ *\/ */
                   3696: /* /\* /\\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\\/ *\/ */
                   3697: /* /\* /\\*cptcovprod=1            1               2            *\\/ *\/ */
                   3698: /* /\* /\\*Tprod[]=                4               7            *\\/ *\/ */
                   3699: /* /\* /\\*Tvard[][1]             4               1             *\\/ *\/ */
                   3700: /* /\* /\\*Tvard[][2]               3               2           *\\/ *\/ */
1.330     brouard  3701:          
1.332     brouard  3702: /*       /\* 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])]); *\/ */
                   3703: /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3704: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];     */
                   3705: /*       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]]); */
                   3706: /*       printf("hpxij new Product no age product precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3707: 
                   3708: /*       /\* if(Dummy[Tvardk[k1][1]]==0){ *\/ */
                   3709: /*       /\*   if(Dummy[Tvardk[k1][2]]==0){ /\\* Product of dummies *\\/ *\/ */
                   3710: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3711: /*           /\* cov[2+nagesqr+k1]=Tinvresult[nres][Tvardk[k1][1]] * Tinvresult[nres][Tvardk[k1][2]];   *\/ */
                   3712: /*           /\* 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]])]; *\/ */
                   3713: /*         /\* }else{ /\\* Product of dummy by quantitative *\\/ *\/ */
                   3714: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,TnsdVar[Tvard[k][1]])] * Tqresult[nres][k]; *\/ */
                   3715: /*           /\* cov[2+nagesqr+k1]=Tresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]; *\/ */
                   3716: /*       /\*   } *\/ */
                   3717: /*       /\* }else{ /\\* Product of quantitative by...*\\/ *\/ */
                   3718: /*       /\*   if(Dummy[Tvard[k][2]]==0){  /\\* quant by dummy *\\/ *\/ */
                   3719: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][Tvard[k][1]]; *\\/ *\/ */
                   3720: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3721: /*       /\*   }else{ /\\* Product of two quant *\\/ *\/ */
                   3722: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\\/ *\/ */
                   3723: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3724: /*       /\*   } *\/ */
                   3725: /*       /\* }/\\*end of products quantitative *\\/ *\/ */
                   3726: /*     }/\*end of products *\/ */
                   3727:       /* } /\* End of loop on model equation *\/ */
1.235     brouard  3728:       /* for (k=1; k<=cptcovn;k++)  */
                   3729:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3730:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3731:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3732:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3733:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3734:       
                   3735:       
1.126     brouard  3736:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3737:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.319     brouard  3738:       /* right multiplication of oldm by the current matrix */
1.126     brouard  3739:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3740:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3741:       /* if((int)age == 70){ */
                   3742:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3743:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3744:       /*         printf("%d pmmij ",i); */
                   3745:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3746:       /*           printf("%f ",pmmij[i][j]); */
                   3747:       /*         } */
                   3748:       /*         printf(" oldm "); */
                   3749:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3750:       /*           printf("%f ",oldm[i][j]); */
                   3751:       /*         } */
                   3752:       /*         printf("\n"); */
                   3753:       /*       } */
                   3754:       /* } */
1.126     brouard  3755:       savm=oldm;
                   3756:       oldm=newm;
                   3757:     }
                   3758:     for(i=1; i<=nlstate+ndeath; i++)
                   3759:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  3760:        po[i][j][h]=newm[i][j];
                   3761:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3762:       }
1.128     brouard  3763:     /*printf("h=%d ",h);*/
1.126     brouard  3764:   } /* end h */
1.267     brouard  3765:   /*     printf("\n H=%d \n",h); */
1.126     brouard  3766:   return po;
                   3767: }
                   3768: 
1.217     brouard  3769: /************* Higher Back Matrix Product ***************/
1.218     brouard  3770: /* 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  3771: 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  3772: {
1.332     brouard  3773:   /* For dummy covariates given in each resultline (for historical, computes the corresponding combination ij),
                   3774:      computes the transition matrix starting at age 'age' over
1.217     brouard  3775:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3776:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3777:      nhstepm*hstepm matrices.
                   3778:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3779:      (typically every 2 years instead of every month which is too big
1.217     brouard  3780:      for the memory).
1.218     brouard  3781:      Model is determined by parameters x and covariates have to be
1.266     brouard  3782:      included manually here. Then we use a call to bmij(x and cov)
                   3783:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  3784:   */
1.217     brouard  3785: 
1.332     brouard  3786:   int i, j, d, h, k, k1;
1.266     brouard  3787:   double **out, cov[NCOVMAX+1], **bmij();
                   3788:   double **newm, ***newmm;
1.217     brouard  3789:   double agexact;
                   3790:   double agebegin, ageend;
1.222     brouard  3791:   double **oldm, **savm;
1.217     brouard  3792: 
1.266     brouard  3793:   newmm=po; /* To be saved */
                   3794:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  3795:   /* Hstepm could be zero and should return the unit matrix */
                   3796:   for (i=1;i<=nlstate+ndeath;i++)
                   3797:     for (j=1;j<=nlstate+ndeath;j++){
                   3798:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3799:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3800:     }
                   3801:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3802:   for(h=1; h <=nhstepm; h++){
                   3803:     for(d=1; d <=hstepm; d++){
                   3804:       newm=savm;
                   3805:       /* Covariates have to be included here again */
                   3806:       cov[1]=1.;
1.271     brouard  3807:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  3808:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
1.318     brouard  3809:         /* Debug */
                   3810:       /* printf("hBxij age=%lf, agexact=%lf\n", age, agexact); */
1.217     brouard  3811:       cov[2]=agexact;
1.332     brouard  3812:       if(nagesqr==1){
1.222     brouard  3813:        cov[3]= agexact*agexact;
1.332     brouard  3814:       }
                   3815:       /** New code */
                   3816:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   3817:        if(Typevar[k1]==1){ /* A product with age */
                   3818:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.325     brouard  3819:        }else{
1.332     brouard  3820:          cov[2+nagesqr+k1]=precov[nres][k1];
1.325     brouard  3821:        }
1.332     brouard  3822:       }/* End of loop on model equation */
                   3823:       /** End of new code */
                   3824:   /** This was old code */
                   3825:       /* for (k=1; k<=nsd;k++){ /\* For single dummy covariates only *\//\* cptcovn error *\/ */
                   3826:       /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3827:       /* /\* /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3828:       /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])];/\* Bug valgrind *\/ */
                   3829:       /*   /\* 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)); *\/ */
                   3830:       /* } */
                   3831:       /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3832:       /*       /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3833:       /*       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3834:       /*       /\* 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]); *\/ */
                   3835:       /* } */
                   3836:       /* for (k=1; k<=cptcovage;k++){ /\* Should start at cptcovn+1 *\//\* For product with age *\/ */
                   3837:       /*       /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age error!!!*\\/ *\/ */
                   3838:       /*       if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3839:       /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3840:       /*       } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3841:       /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];  */
                   3842:       /*       } */
                   3843:       /*       /\* 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]); *\/ */
                   3844:       /* } */
                   3845:       /* for (k=1; k<=cptcovprod;k++){ /\* Useless because included in cptcovn *\/ */
                   3846:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3847:       /*       if(Dummy[Tvard[k][1]]==0){ */
                   3848:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3849:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][1])]; */
                   3850:       /*         }else{ */
                   3851:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3852:       /*         } */
                   3853:       /*       }else{ */
                   3854:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3855:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3856:       /*         }else{ */
                   3857:       /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3858:       /*         } */
                   3859:       /*       } */
                   3860:       /* }                      */
                   3861:       /* /\*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*\/ */
                   3862:       /* /\*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*\/ */
                   3863: /** End of old code */
                   3864:       
1.218     brouard  3865:       /* Careful transposed matrix */
1.266     brouard  3866:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  3867:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3868:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3869:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.325     brouard  3870:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);/* Bug valgrind */
1.217     brouard  3871:       /* if((int)age == 70){ */
                   3872:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3873:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3874:       /*         printf("%d pmmij ",i); */
                   3875:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3876:       /*           printf("%f ",pmmij[i][j]); */
                   3877:       /*         } */
                   3878:       /*         printf(" oldm "); */
                   3879:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3880:       /*           printf("%f ",oldm[i][j]); */
                   3881:       /*         } */
                   3882:       /*         printf("\n"); */
                   3883:       /*       } */
                   3884:       /* } */
                   3885:       savm=oldm;
                   3886:       oldm=newm;
                   3887:     }
                   3888:     for(i=1; i<=nlstate+ndeath; i++)
                   3889:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3890:        po[i][j][h]=newm[i][j];
1.268     brouard  3891:        /* if(h==nhstepm) */
                   3892:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  3893:       }
1.268     brouard  3894:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  3895:   } /* end h */
1.268     brouard  3896:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  3897:   return po;
                   3898: }
                   3899: 
                   3900: 
1.162     brouard  3901: #ifdef NLOPT
                   3902:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3903:   double fret;
                   3904:   double *xt;
                   3905:   int j;
                   3906:   myfunc_data *d2 = (myfunc_data *) pd;
                   3907: /* xt = (p1-1); */
                   3908:   xt=vector(1,n); 
                   3909:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3910: 
                   3911:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3912:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3913:   printf("Function = %.12lf ",fret);
                   3914:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3915:   printf("\n");
                   3916:  free_vector(xt,1,n);
                   3917:   return fret;
                   3918: }
                   3919: #endif
1.126     brouard  3920: 
                   3921: /*************** log-likelihood *************/
                   3922: double func( double *x)
                   3923: {
1.336     brouard  3924:   int i, ii, j, k, mi, d, kk, kf=0;
1.226     brouard  3925:   int ioffset=0;
1.339     brouard  3926:   int ipos=0,iposold=0,ncovv=0;
                   3927: 
1.340     brouard  3928:   double cotvarv, cotvarvold;
1.226     brouard  3929:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3930:   double **out;
                   3931:   double lli; /* Individual log likelihood */
                   3932:   int s1, s2;
1.228     brouard  3933:   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  3934: 
1.226     brouard  3935:   double bbh, survp;
                   3936:   double agexact;
1.336     brouard  3937:   double agebegin, ageend;
1.226     brouard  3938:   /*extern weight */
                   3939:   /* We are differentiating ll according to initial status */
                   3940:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3941:   /*for(i=1;i<imx;i++) 
                   3942:     printf(" %d\n",s[4][i]);
                   3943:   */
1.162     brouard  3944: 
1.226     brouard  3945:   ++countcallfunc;
1.162     brouard  3946: 
1.226     brouard  3947:   cov[1]=1.;
1.126     brouard  3948: 
1.226     brouard  3949:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3950:   ioffset=0;
1.226     brouard  3951:   if(mle==1){
                   3952:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3953:       /* Computes the values of the ncovmodel covariates of the model
                   3954:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3955:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   3956:         to be observed in j being in i according to the model.
                   3957:       */
1.243     brouard  3958:       ioffset=2+nagesqr ;
1.233     brouard  3959:    /* Fixed */
1.345     brouard  3960:       for (kf=1; kf<=ncovf;kf++){ /* For each fixed covariate dummy or quant or prod */
1.319     brouard  3961:        /* # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi */
                   3962:         /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   3963:        /*  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  3964:         /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.336     brouard  3965:        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  3966:        /* V1*V2 (7)  TvarFind[2]=7, TvarFind[3]=9 */
1.234     brouard  3967:       }
1.226     brouard  3968:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.319     brouard  3969:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
1.226     brouard  3970:         has been calculated etc */
                   3971:       /* For an individual i, wav[i] gives the number of effective waves */
                   3972:       /* We compute the contribution to Likelihood of each effective transition
                   3973:         mw[mi][i] is real wave of the mi th effectve wave */
                   3974:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   3975:         s2=s[mw[mi+1][i]][i];
1.341     brouard  3976:         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  3977:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   3978:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   3979:       */
1.336     brouard  3980:       for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
                   3981:       /* Wave varying (but not age varying) */
1.339     brouard  3982:        /* 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*\/ */
                   3983:        /*   /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; but where is the crossproduct? *\/ */
                   3984:        /*   cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   3985:        /* } */
1.340     brouard  3986:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age )*/
                   3987:          itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   3988:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
1.345     brouard  3989:          if(FixedV[itv]!=0){ /* Not a fixed covariate */
1.341     brouard  3990:            cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* cotvar[wav][ncovcol+nqv+iv][i] */
1.340     brouard  3991:          }else{ /* fixed covariate */
1.345     brouard  3992:            cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
1.340     brouard  3993:          }
1.339     brouard  3994:          if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  3995:            cotvarvold=cotvarv;
                   3996:          }else{ /* A second product */
                   3997:            cotvarv=cotvarv*cotvarvold;
1.339     brouard  3998:          }
                   3999:          iposold=ipos;
1.340     brouard  4000:          cov[ioffset+ipos]=cotvarv;
1.234     brouard  4001:        }
1.339     brouard  4002:        /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
                   4003:        /*   iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4004:        /*   cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
                   4005:        /*   k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
                   4006:        /*   cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
                   4007:        /*   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]); */
                   4008:        /* } */
                   4009:        /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
                   4010:        /*   iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4011:        /*   /\* 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]); *\/ */
                   4012:        /*   cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
                   4013:        /* } */
                   4014:        /* for products of time varying to be done */
1.234     brouard  4015:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4016:          for (j=1;j<=nlstate+ndeath;j++){
                   4017:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4018:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4019:          }
1.336     brouard  4020: 
                   4021:        agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4022:        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  4023:        for(d=0; d<dh[mi][i]; d++){
                   4024:          newm=savm;
                   4025:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4026:          cov[2]=agexact;
                   4027:          if(nagesqr==1)
                   4028:            cov[3]= agexact*agexact;  /* Should be changed here */
                   4029:          for (kk=1; kk<=cptcovage;kk++) {
1.318     brouard  4030:            if(!FixedV[Tvar[Tage[kk]]])
                   4031:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4032:            else
1.341     brouard  4033:              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  4034:          }
                   4035:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4036:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4037:          savm=oldm;
                   4038:          oldm=newm;
                   4039:        } /* end mult */
                   4040:        
                   4041:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   4042:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   4043:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   4044:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   4045:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   4046:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   4047:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   4048:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  4049:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   4050:                                 * -stepm/2 to stepm/2 .
                   4051:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   4052:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   4053:                                 */
1.234     brouard  4054:        s1=s[mw[mi][i]][i];
                   4055:        s2=s[mw[mi+1][i]][i];
                   4056:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4057:        /* bias bh is positive if real duration
                   4058:         * is higher than the multiple of stepm and negative otherwise.
                   4059:         */
                   4060:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   4061:        if( s2 > nlstate){ 
                   4062:          /* i.e. if s2 is a death state and if the date of death is known 
                   4063:             then the contribution to the likelihood is the probability to 
                   4064:             die between last step unit time and current  step unit time, 
                   4065:             which is also equal to probability to die before dh 
                   4066:             minus probability to die before dh-stepm . 
                   4067:             In version up to 0.92 likelihood was computed
                   4068:             as if date of death was unknown. Death was treated as any other
                   4069:             health state: the date of the interview describes the actual state
                   4070:             and not the date of a change in health state. The former idea was
                   4071:             to consider that at each interview the state was recorded
                   4072:             (healthy, disable or death) and IMaCh was corrected; but when we
                   4073:             introduced the exact date of death then we should have modified
                   4074:             the contribution of an exact death to the likelihood. This new
                   4075:             contribution is smaller and very dependent of the step unit
                   4076:             stepm. It is no more the probability to die between last interview
                   4077:             and month of death but the probability to survive from last
                   4078:             interview up to one month before death multiplied by the
                   4079:             probability to die within a month. Thanks to Chris
                   4080:             Jackson for correcting this bug.  Former versions increased
                   4081:             mortality artificially. The bad side is that we add another loop
                   4082:             which slows down the processing. The difference can be up to 10%
                   4083:             lower mortality.
                   4084:          */
                   4085:          /* If, at the beginning of the maximization mostly, the
                   4086:             cumulative probability or probability to be dead is
                   4087:             constant (ie = 1) over time d, the difference is equal to
                   4088:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   4089:             s1 at precedent wave, to be dead a month before current
                   4090:             wave is equal to probability, being at state s1 at
                   4091:             precedent wave, to be dead at mont of the current
                   4092:             wave. Then the observed probability (that this person died)
                   4093:             is null according to current estimated parameter. In fact,
                   4094:             it should be very low but not zero otherwise the log go to
                   4095:             infinity.
                   4096:          */
1.183     brouard  4097: /* #ifdef INFINITYORIGINAL */
                   4098: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4099: /* #else */
                   4100: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   4101: /*         lli=log(mytinydouble); */
                   4102: /*       else */
                   4103: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4104: /* #endif */
1.226     brouard  4105:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4106:          
1.226     brouard  4107:        } else if  ( s2==-1 ) { /* alive */
                   4108:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4109:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4110:          /*survp += out[s1][j]; */
                   4111:          lli= log(survp);
                   4112:        }
1.336     brouard  4113:        /* else if  (s2==-4) {  */
                   4114:        /*   for (j=3,survp=0. ; j<=nlstate; j++)   */
                   4115:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4116:        /*   lli= log(survp);  */
                   4117:        /* }  */
                   4118:        /* else if  (s2==-5) {  */
                   4119:        /*   for (j=1,survp=0. ; j<=2; j++)   */
                   4120:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4121:        /*   lli= log(survp);  */
                   4122:        /* }  */
1.226     brouard  4123:        else{
                   4124:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4125:          /*  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 */
                   4126:        } 
                   4127:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   4128:        /*if(lli ==000.0)*/
1.340     brouard  4129:        /* 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  4130:        ipmx +=1;
                   4131:        sw += weight[i];
                   4132:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4133:        /* if (lli < log(mytinydouble)){ */
                   4134:        /*   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); */
                   4135:        /*   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]); */
                   4136:        /* } */
                   4137:       } /* end of wave */
                   4138:     } /* end of individual */
                   4139:   }  else if(mle==2){
                   4140:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.319     brouard  4141:       ioffset=2+nagesqr ;
                   4142:       for (k=1; k<=ncovf;k++)
                   4143:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];
1.226     brouard  4144:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  4145:        for(k=1; k <= ncovv ; k++){
1.341     brouard  4146:          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  4147:        }
1.226     brouard  4148:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4149:          for (j=1;j<=nlstate+ndeath;j++){
                   4150:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4151:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4152:          }
                   4153:        for(d=0; d<=dh[mi][i]; d++){
                   4154:          newm=savm;
                   4155:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4156:          cov[2]=agexact;
                   4157:          if(nagesqr==1)
                   4158:            cov[3]= agexact*agexact;
                   4159:          for (kk=1; kk<=cptcovage;kk++) {
                   4160:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4161:          }
                   4162:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4163:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4164:          savm=oldm;
                   4165:          oldm=newm;
                   4166:        } /* end mult */
                   4167:       
                   4168:        s1=s[mw[mi][i]][i];
                   4169:        s2=s[mw[mi+1][i]][i];
                   4170:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4171:        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 */
                   4172:        ipmx +=1;
                   4173:        sw += weight[i];
                   4174:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4175:       } /* end of wave */
                   4176:     } /* end of individual */
                   4177:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   4178:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4179:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4180:       for(mi=1; mi<= wav[i]-1; mi++){
                   4181:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4182:          for (j=1;j<=nlstate+ndeath;j++){
                   4183:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4184:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4185:          }
                   4186:        for(d=0; d<dh[mi][i]; d++){
                   4187:          newm=savm;
                   4188:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4189:          cov[2]=agexact;
                   4190:          if(nagesqr==1)
                   4191:            cov[3]= agexact*agexact;
                   4192:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  4193:            if(!FixedV[Tvar[Tage[kk]]])
                   4194:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4195:            else
1.341     brouard  4196:              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  4197:          }
                   4198:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4199:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4200:          savm=oldm;
                   4201:          oldm=newm;
                   4202:        } /* end mult */
                   4203:       
                   4204:        s1=s[mw[mi][i]][i];
                   4205:        s2=s[mw[mi+1][i]][i];
                   4206:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4207:        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 */
                   4208:        ipmx +=1;
                   4209:        sw += weight[i];
                   4210:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4211:       } /* end of wave */
                   4212:     } /* end of individual */
                   4213:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   4214:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4215:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4216:       for(mi=1; mi<= wav[i]-1; mi++){
                   4217:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4218:          for (j=1;j<=nlstate+ndeath;j++){
                   4219:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4220:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4221:          }
                   4222:        for(d=0; d<dh[mi][i]; d++){
                   4223:          newm=savm;
                   4224:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4225:          cov[2]=agexact;
                   4226:          if(nagesqr==1)
                   4227:            cov[3]= agexact*agexact;
                   4228:          for (kk=1; kk<=cptcovage;kk++) {
                   4229:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4230:          }
1.126     brouard  4231:        
1.226     brouard  4232:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4233:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4234:          savm=oldm;
                   4235:          oldm=newm;
                   4236:        } /* end mult */
                   4237:       
                   4238:        s1=s[mw[mi][i]][i];
                   4239:        s2=s[mw[mi+1][i]][i];
                   4240:        if( s2 > nlstate){ 
                   4241:          lli=log(out[s1][s2] - savm[s1][s2]);
                   4242:        } else if  ( s2==-1 ) { /* alive */
                   4243:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4244:            survp += out[s1][j];
                   4245:          lli= log(survp);
                   4246:        }else{
                   4247:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4248:        }
                   4249:        ipmx +=1;
                   4250:        sw += weight[i];
                   4251:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.343     brouard  4252:        /* 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  4253:       } /* end of wave */
                   4254:     } /* end of individual */
                   4255:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   4256:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4257:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4258:       for(mi=1; mi<= wav[i]-1; mi++){
                   4259:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4260:          for (j=1;j<=nlstate+ndeath;j++){
                   4261:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4262:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4263:          }
                   4264:        for(d=0; d<dh[mi][i]; d++){
                   4265:          newm=savm;
                   4266:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4267:          cov[2]=agexact;
                   4268:          if(nagesqr==1)
                   4269:            cov[3]= agexact*agexact;
                   4270:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  4271:            if(!FixedV[Tvar[Tage[kk]]])
                   4272:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4273:            else
1.341     brouard  4274:              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  4275:          }
1.126     brouard  4276:        
1.226     brouard  4277:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4278:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4279:          savm=oldm;
                   4280:          oldm=newm;
                   4281:        } /* end mult */
                   4282:       
                   4283:        s1=s[mw[mi][i]][i];
                   4284:        s2=s[mw[mi+1][i]][i];
                   4285:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4286:        ipmx +=1;
                   4287:        sw += weight[i];
                   4288:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4289:        /*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]);*/
                   4290:       } /* end of wave */
                   4291:     } /* end of individual */
                   4292:   } /* End of if */
                   4293:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   4294:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   4295:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4296:   return -l;
1.126     brouard  4297: }
                   4298: 
                   4299: /*************** log-likelihood *************/
                   4300: double funcone( double *x)
                   4301: {
1.228     brouard  4302:   /* Same as func but slower because of a lot of printf and if */
1.335     brouard  4303:   int i, ii, j, k, mi, d, kk, kf=0;
1.228     brouard  4304:   int ioffset=0;
1.339     brouard  4305:   int ipos=0,iposold=0,ncovv=0;
                   4306: 
1.340     brouard  4307:   double cotvarv, cotvarvold;
1.131     brouard  4308:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  4309:   double **out;
                   4310:   double lli; /* Individual log likelihood */
                   4311:   double llt;
                   4312:   int s1, s2;
1.228     brouard  4313:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   4314: 
1.126     brouard  4315:   double bbh, survp;
1.187     brouard  4316:   double agexact;
1.214     brouard  4317:   double agebegin, ageend;
1.126     brouard  4318:   /*extern weight */
                   4319:   /* We are differentiating ll according to initial status */
                   4320:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   4321:   /*for(i=1;i<imx;i++) 
                   4322:     printf(" %d\n",s[4][i]);
                   4323:   */
                   4324:   cov[1]=1.;
                   4325: 
                   4326:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  4327:   ioffset=0;
                   4328:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.336     brouard  4329:     /* Computes the values of the ncovmodel covariates of the model
                   4330:        depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   4331:        Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   4332:        to be observed in j being in i according to the model.
                   4333:     */
1.243     brouard  4334:     /* ioffset=2+nagesqr+cptcovage; */
                   4335:     ioffset=2+nagesqr;
1.232     brouard  4336:     /* Fixed */
1.224     brouard  4337:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  4338:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
1.335     brouard  4339:     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  4340:       /* printf("Debug3 TvarFind[%d]=%d",kf, TvarFind[kf]); */
                   4341:       /* printf(" Tvar[TvarFind[kf]]=%d", Tvar[TvarFind[kf]]); */
                   4342:       /* printf(" i=%d covar[Tvar[TvarFind[kf]]][i]=%f\n",i,covar[Tvar[TvarFind[kf]]][i]); */
1.335     brouard  4343:       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  4344: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   4345: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   4346: /*    cov[2+6]=covar[2][i]; V2  */
                   4347: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   4348: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   4349: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   4350: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   4351: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   4352: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  4353:     }
1.336     brouard  4354:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   4355:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
                   4356:         has been calculated etc */
                   4357:       /* For an individual i, wav[i] gives the number of effective waves */
                   4358:       /* We compute the contribution to Likelihood of each effective transition
                   4359:         mw[mi][i] is real wave of the mi th effectve wave */
                   4360:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   4361:         s2=s[mw[mi+1][i]][i];
1.341     brouard  4362:         And the iv th varying covariate in the DATA is the cotvar[mw[mi+1][i]][ncovcol+nqv+iv][i]
1.336     brouard  4363:       */
                   4364:     /* This part may be useless now because everythin should be in covar */
1.232     brouard  4365:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   4366:     /*   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?)*\/ */
                   4367:     /* } */
1.231     brouard  4368:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   4369:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   4370:     /* } */
1.225     brouard  4371:     
1.233     brouard  4372: 
                   4373:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.339     brouard  4374:       /* 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 */
                   4375:       /* for(k=1; k <= ncovv ; k++){ /\* Varying  covariates (single and product but no age )*\/ */
                   4376:       /*       /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; *\/ */
                   4377:       /*       cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   4378:       /* } */
                   4379:       
                   4380:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   4381:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   4382:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   4383:       /*  TvarVV[1]=V3 (first time varying in the model equation, TvarVV[2]=V1 (in V1*V3) TvarVV[3]=3(V3)  */
                   4384:       /* We need the position of the time varying or product in the model */
                   4385:       /* 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 */            
                   4386:       /* TvarVV gives the variable name */
1.340     brouard  4387:       /* Other example V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   4388:       *      k=         1   2     3     4         5        6        7       8        9
                   4389:       *  varying            1     2                                 3       4        5
                   4390:       *  ncovv              1     2                                3 4     5 6      7 8
1.343     brouard  4391:       * TvarVV[ncovv]      V3     5                                1 3     3 5      1 5
1.340     brouard  4392:       * TvarVVind           2     3                                7 7     8 8      9 9
                   4393:       * TvarFind[k]     1   0     0     0         0        0        0       0        0
                   4394:       */
1.345     brouard  4395:       /* Other model ncovcol=5 nqv=0 ntv=3 nqtv=0 nlstate=3
1.346     brouard  4396:        * V2 V3 V4 are fixed V6 V7 are timevarying so V8 and V5 are not in the model and product column will start at 9 Tvar[4]=6
1.345     brouard  4397:        * FixedV[ncovcol+qv+ntv+nqtv]       V5
                   4398:        *             V1  V2     V3    V4   V5 V6     V7  V8
                   4399:        *             0   0      0      0    0  1      1   1 
                   4400:        * model=          V2  +  V3  +  V4  +  V6  +  V7  +  V6*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4
                   4401:        * kmodel           1     2      3      4      5        6         7         8         9        10        11
                   4402:        * ncovf            1     2      3
                   4403:        * ncovvt=14                            1      2       3 4       5 6       7 8       9 10     11 12     13 14
                   4404:        * TvarVV[1]@14 = itv                   {6,     7,     6, 2,     7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
                   4405:        * TvarVVind[1]@14=                    {4,     5,      6, 6,     7, 7,     8, 8,      9, 9,   10, 10,   11, 11}
                   4406:        * TvarFind[1]@14= {1,    2,     3,     0 <repeats 12 times>}
                   4407:        * Tvar[1]@20=     {2,    3,     4,    6,      7,      9,      10,        11,       12,      13,       14}
                   4408:        * TvarFind[itv]                        0      0       0
                   4409:        * FixedV[itv]                          1      1       1  0      1 0       1 0       1 0       0
                   4410:        * Tvar[TvarFind[ncovf]]=[1]=2 [2]=3 [4]=4
                   4411:        * Tvar[TvarFind[itv]]                [0]=?      ?ncovv 1 à ncovvt]
                   4412:        *   Not a fixed cotvar[mw][itv][i]     6       7      6  2      7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
                   4413:        *   fixed covar[itv]                  [6]     [7]    [6][2]                            
                   4414:        */
                   4415: 
1.340     brouard  4416:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age) including individual from products */
1.345     brouard  4417:        itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product  */
1.340     brouard  4418:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
1.345     brouard  4419:        /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   4420:        if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   4421:          cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
1.340     brouard  4422:        }else{ /* fixed covariate */
1.345     brouard  4423:          /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
                   4424:          cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
1.340     brouard  4425:        }
1.339     brouard  4426:        if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  4427:          cotvarvold=cotvarv;
                   4428:        }else{ /* A second product */
                   4429:          cotvarv=cotvarv*cotvarvold;
1.339     brouard  4430:        }
                   4431:        iposold=ipos;
1.340     brouard  4432:        cov[ioffset+ipos]=cotvarv;
1.339     brouard  4433:        /* For products */
                   4434:       }
                   4435:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates single *\/ */
                   4436:       /*       iv=TvarVDind[itv]; /\* iv, position in the model equation of time varying covariate itv *\/ */
                   4437:       /*       /\*         "V1+V3+age*V1+age*V3+V1*V3" with V3 time varying *\/ */
                   4438:       /*       /\*           1  2   3      4      5                         *\/ */
                   4439:       /*       /\*itv           1                                           *\/ */
                   4440:       /*       /\* TvarVInd[1]= 2                                           *\/ */
                   4441:       /*       /\* iv= Tvar[Tmodelind[itv]]-ncovcol-nqv;  /\\* Counting the # varying covariate from 1 to ntveff *\\/ *\/ */
                   4442:       /*       /\* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; *\/ */
                   4443:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; *\/ */
                   4444:       /*       /\* k=ioffset-2-nagesqr-cptcovage+itv; /\\* position in simple model *\\/ *\/ */
                   4445:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; *\/ */
                   4446:       /*       cov[ioffset+iv]=cotvar[mw[mi][i]][itv][i]; */
                   4447:       /*       /\* 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]); *\/ */
                   4448:       /* } */
1.232     brouard  4449:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  4450:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4451:       /*       /\* 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]); *\/ */
                   4452:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  4453:       /* } */
1.126     brouard  4454:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  4455:        for (j=1;j<=nlstate+ndeath;j++){
                   4456:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4457:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4458:        }
1.214     brouard  4459:       
                   4460:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4461:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   4462:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  4463:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  4464:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4465:          and mw[mi+1][i]. dh depends on stepm.*/
                   4466:        newm=savm;
1.247     brouard  4467:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  4468:        cov[2]=agexact;
                   4469:        if(nagesqr==1)
                   4470:          cov[3]= agexact*agexact;
                   4471:        for (kk=1; kk<=cptcovage;kk++) {
                   4472:          if(!FixedV[Tvar[Tage[kk]]])
                   4473:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4474:          else
1.341     brouard  4475:            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  4476:        }
                   4477:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   4478:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4479:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4480:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4481:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   4482:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   4483:        savm=oldm;
                   4484:        oldm=newm;
1.126     brouard  4485:       } /* end mult */
1.336     brouard  4486:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   4487:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   4488:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   4489:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   4490:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   4491:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   4492:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   4493:         * probability in order to take into account the bias as a fraction of the way
                   4494:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   4495:                                 * -stepm/2 to stepm/2 .
                   4496:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   4497:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   4498:                                 */
1.126     brouard  4499:       s1=s[mw[mi][i]][i];
                   4500:       s2=s[mw[mi+1][i]][i];
1.217     brouard  4501:       /* if(s2==-1){ */
1.268     brouard  4502:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  4503:       /*       /\* exit(1); *\/ */
                   4504:       /* } */
1.126     brouard  4505:       bbh=(double)bh[mi][i]/(double)stepm; 
                   4506:       /* bias is positive if real duration
                   4507:        * is higher than the multiple of stepm and negative otherwise.
                   4508:        */
                   4509:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  4510:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4511:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  4512:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   4513:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4514:        lli= log(survp);
1.126     brouard  4515:       }else if (mle==1){
1.242     brouard  4516:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  4517:       } else if(mle==2){
1.242     brouard  4518:        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  4519:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  4520:        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  4521:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  4522:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  4523:       } else{  /* mle=0 back to 1 */
1.242     brouard  4524:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4525:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  4526:       } /* End of if */
                   4527:       ipmx +=1;
                   4528:       sw += weight[i];
                   4529:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.342     brouard  4530:       /* Printing covariates values for each contribution for checking */
1.343     brouard  4531:       /* 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  4532:       if(globpr){
1.246     brouard  4533:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  4534:  %11.6f %11.6f %11.6f ", \
1.242     brouard  4535:                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  4536:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.343     brouard  4537:        /*      printf("%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\ */
                   4538:        /* %11.6f %11.6f %11.6f ", \ */
                   4539:        /*              num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw, */
                   4540:        /*              2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
1.242     brouard  4541:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   4542:          llt +=ll[k]*gipmx/gsw;
                   4543:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
1.335     brouard  4544:          /* printf(" %10.6f",-ll[k]*gipmx/gsw); */
1.242     brouard  4545:        }
1.343     brouard  4546:        fprintf(ficresilk," %10.6f ", -llt);
1.335     brouard  4547:        /* printf(" %10.6f\n", -llt); */
1.342     brouard  4548:        /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
1.343     brouard  4549:        /* fprintf(ficresilk,"%09ld ", num[i]); */ /* not necessary */
                   4550:        for (kf=1; kf<=ncovf;kf++){ /* Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
                   4551:          fprintf(ficresilk," %g",covar[Tvar[TvarFind[kf]]][i]);
                   4552:        }
                   4553:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age) including individual from products */
                   4554:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4555:          if(ipos!=iposold){ /* Not a product or first of a product */
                   4556:            fprintf(ficresilk," %g",cov[ioffset+ipos]);
                   4557:            /* printf(" %g",cov[ioffset+ipos]); */
                   4558:          }else{
                   4559:            fprintf(ficresilk,"*");
                   4560:            /* printf("*"); */
1.342     brouard  4561:          }
1.343     brouard  4562:          iposold=ipos;
                   4563:        }
                   4564:        for (kk=1; kk<=cptcovage;kk++) {
                   4565:          if(!FixedV[Tvar[Tage[kk]]]){
                   4566:            fprintf(ficresilk," %g*age",covar[Tvar[Tage[kk]]][i]);
                   4567:            /* printf(" %g*age",covar[Tvar[Tage[kk]]][i]); */
                   4568:          }else{
                   4569:            fprintf(ficresilk," %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
                   4570:            /* 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  4571:          }
1.343     brouard  4572:        }
                   4573:        /* printf("\n"); */
1.342     brouard  4574:        /* } /\*  End debugILK *\/ */
                   4575:        fprintf(ficresilk,"\n");
                   4576:       } /* End if globpr */
1.335     brouard  4577:     } /* end of wave */
                   4578:   } /* end of individual */
                   4579:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
1.232     brouard  4580: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
1.335     brouard  4581:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4582:   if(globpr==0){ /* First time we count the contributions and weights */
                   4583:     gipmx=ipmx;
                   4584:     gsw=sw;
                   4585:   }
1.343     brouard  4586:   return -l;
1.126     brouard  4587: }
                   4588: 
                   4589: 
                   4590: /*************** function likelione ***********/
1.292     brouard  4591: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  4592: {
                   4593:   /* This routine should help understanding what is done with 
                   4594:      the selection of individuals/waves and
                   4595:      to check the exact contribution to the likelihood.
                   4596:      Plotting could be done.
1.342     brouard  4597:   */
                   4598:   void pstamp(FILE *ficres);
1.343     brouard  4599:   int k, kf, kk, kvar, ncovv, iposold, ipos;
1.126     brouard  4600: 
                   4601:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  4602:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  4603:     strcat(fileresilk,fileresu);
1.126     brouard  4604:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   4605:       printf("Problem with resultfile: %s\n", fileresilk);
                   4606:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   4607:     }
1.342     brouard  4608:     pstamp(ficresilk);fprintf(ficresilk,"# model=1+age+%s\n",model);
1.214     brouard  4609:     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");
                   4610:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  4611:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   4612:     for(k=1; k<=nlstate; k++) 
                   4613:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
1.342     brouard  4614:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total) ");
                   4615: 
                   4616:     /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
                   4617:       for(kf=1;kf <= ncovf; kf++){
                   4618:        fprintf(ficresilk,"V%d",Tvar[TvarFind[kf]]);
                   4619:        /* printf("V%d",Tvar[TvarFind[kf]]); */
                   4620:       }
                   4621:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){
1.343     brouard  4622:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
1.342     brouard  4623:        if(ipos!=iposold){ /* Not a product or first of a product */
                   4624:          /* printf(" %d",ipos); */
                   4625:          fprintf(ficresilk," V%d",TvarVV[ncovv]);
                   4626:        }else{
                   4627:          /* printf("*"); */
                   4628:          fprintf(ficresilk,"*");
1.343     brouard  4629:        }
1.342     brouard  4630:        iposold=ipos;
                   4631:       }
                   4632:       for (kk=1; kk<=cptcovage;kk++) {
                   4633:        if(!FixedV[Tvar[Tage[kk]]]){
                   4634:          /* printf(" %d*age(Fixed)",Tvar[Tage[kk]]); */
                   4635:          fprintf(ficresilk," %d*age(Fixed)",Tvar[Tage[kk]]);
                   4636:        }else{
                   4637:          fprintf(ficresilk," %d*age(Varying)",Tvar[Tage[kk]]);/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
                   4638:          /* printf(" %d*age(Varying)",Tvar[Tage[kk]]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
                   4639:        }
                   4640:       }
                   4641:     /* } /\* End if debugILK *\/ */
                   4642:     /* printf("\n"); */
                   4643:     fprintf(ficresilk,"\n");
                   4644:   } /* End glogpri */
1.126     brouard  4645: 
1.292     brouard  4646:   *fretone=(*func)(p);
1.126     brouard  4647:   if(*globpri !=0){
                   4648:     fclose(ficresilk);
1.205     brouard  4649:     if (mle ==0)
                   4650:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   4651:     else if(mle >=1)
                   4652:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   4653:     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  4654:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  4655:       
1.207     brouard  4656:     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  4657: <img src=\"%s-ori.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4658:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.343     brouard  4659: <img src=\"%s-dest.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
                   4660:     
                   4661:     for (k=1; k<= nlstate ; k++) {
                   4662:       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 \
                   4663: <img src=\"%s-p%dj.png\">\n",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   4664:       for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
                   4665:        /* kvar=Tvar[TvarFind[kf]]; */ /* variable */
                   4666:        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> \
                   4667: <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]]);
                   4668:       }
                   4669:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Loop on the time varying extended covariates (with extension of Vn*Vm */
                   4670:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   4671:        kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   4672:        /* 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]); */
                   4673:        if(ipos!=iposold){ /* Not a product or first of a product */
                   4674:          /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   4675:          /* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); */
                   4676:          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)  */
                   4677:            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> \
                   4678: <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);
                   4679:          } /* End only for dummies time varying (single?) */
                   4680:        }else{ /* Useless product */
                   4681:          /* printf("*"); */
                   4682:          /* fprintf(ficresilk,"*"); */ 
                   4683:        }
                   4684:        iposold=ipos;
                   4685:       } /* For each time varying covariate */
                   4686:     } /* End loop on states */
                   4687: 
                   4688: /*     if(debugILK){ */
                   4689: /*       for(kf=1; kf <= ncovf; kf++){ /\* For each simple dummy covariate of the model *\/ */
                   4690: /*     /\* kvar=Tvar[TvarFind[kf]]; *\/ /\* variable *\/ */
                   4691: /*     for (k=1; k<= nlstate ; k++) { */
                   4692: /*       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> \ */
                   4693: /* <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]]); */
                   4694: /*     } */
                   4695: /*       } */
                   4696: /*       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /\* Loop on the time varying extended covariates (with extension of Vn*Vm *\/ */
                   4697: /*     ipos=TvarVVind[ncovv]; /\* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate *\/ */
                   4698: /*     kvar=TvarVV[ncovv]; /\*  TvarVV={3, 1, 3} gives the name of each varying covariate *\/ */
                   4699: /*     /\* 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]); *\/ */
                   4700: /*     if(ipos!=iposold){ /\* Not a product or first of a product *\/ */
                   4701: /*       /\* fprintf(ficresilk," V%d",TvarVV[ncovv]); *\/ */
                   4702: /*       /\* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); *\/ */
                   4703: /*       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)  *\/ */
                   4704: /*         for (k=1; k<= nlstate ; k++) { */
                   4705: /*           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> \ */
                   4706: /* <img src=\"%s-p%dj-%d.png\">",k,k,kvar,kvar,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,kvar); */
                   4707: /*         } /\* End state *\/ */
                   4708: /*       } /\* End only for dummies time varying (single?) *\/ */
                   4709: /*     }else{ /\* Useless product *\/ */
                   4710: /*       /\* printf("*"); *\/ */
                   4711: /*       /\* fprintf(ficresilk,"*"); *\/  */
                   4712: /*     } */
                   4713: /*     iposold=ipos; */
                   4714: /*       } /\* For each time varying covariate *\/ */
                   4715: /*     }/\* End debugILK *\/ */
1.207     brouard  4716:     fflush(fichtm);
1.343     brouard  4717:   }/* End globpri */
1.126     brouard  4718:   return;
                   4719: }
                   4720: 
                   4721: 
                   4722: /*********** Maximum Likelihood Estimation ***************/
                   4723: 
                   4724: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   4725: {
1.319     brouard  4726:   int i,j,k, jk, jkk=0, iter=0;
1.126     brouard  4727:   double **xi;
                   4728:   double fret;
                   4729:   double fretone; /* Only one call to likelihood */
                   4730:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  4731: 
                   4732: #ifdef NLOPT
                   4733:   int creturn;
                   4734:   nlopt_opt opt;
                   4735:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   4736:   double *lb;
                   4737:   double minf; /* the minimum objective value, upon return */
                   4738:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   4739:   myfunc_data dinst, *d = &dinst;
                   4740: #endif
                   4741: 
                   4742: 
1.126     brouard  4743:   xi=matrix(1,npar,1,npar);
                   4744:   for (i=1;i<=npar;i++)
                   4745:     for (j=1;j<=npar;j++)
                   4746:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   4747:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  4748:   strcpy(filerespow,"POW_"); 
1.126     brouard  4749:   strcat(filerespow,fileres);
                   4750:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   4751:     printf("Problem with resultfile: %s\n", filerespow);
                   4752:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   4753:   }
                   4754:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   4755:   for (i=1;i<=nlstate;i++)
                   4756:     for(j=1;j<=nlstate+ndeath;j++)
                   4757:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   4758:   fprintf(ficrespow,"\n");
1.162     brouard  4759: #ifdef POWELL
1.319     brouard  4760: #ifdef LINMINORIGINAL
                   4761: #else /* LINMINORIGINAL */
                   4762:   
                   4763:   flatdir=ivector(1,npar); 
                   4764:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   4765: #endif /*LINMINORIGINAL */
                   4766: 
                   4767: #ifdef FLATSUP
                   4768:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4769:   /* reorganizing p by suppressing flat directions */
                   4770:   for(i=1, jk=1; i <=nlstate; i++){
                   4771:     for(k=1; k <=(nlstate+ndeath); k++){
                   4772:       if (k != i) {
                   4773:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4774:         if(flatdir[jk]==1){
                   4775:           printf(" To be skipped %d%d flatdir[%d]=%d ",i,k,jk, flatdir[jk]);
                   4776:         }
                   4777:         for(j=1; j <=ncovmodel; j++){
                   4778:           printf("%12.7f ",p[jk]);
                   4779:           jk++; 
                   4780:         }
                   4781:         printf("\n");
                   4782:       }
                   4783:     }
                   4784:   }
                   4785: /* skipping */
                   4786:   /* for(i=1, jk=1, jkk=1;(flatdir[jk]==0)&& (i <=nlstate); i++){ */
                   4787:   for(i=1, jk=1, jkk=1;i <=nlstate; i++){
                   4788:     for(k=1; k <=(nlstate+ndeath); k++){
                   4789:       if (k != i) {
                   4790:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4791:         if(flatdir[jk]==1){
                   4792:           printf(" To be skipped %d%d flatdir[%d]=%d jk=%d p[%d] ",i,k,jk, flatdir[jk],jk, jk);
                   4793:           for(j=1; j <=ncovmodel;  jk++,j++){
                   4794:             printf(" p[%d]=%12.7f",jk, p[jk]);
                   4795:             /*q[jjk]=p[jk];*/
                   4796:           }
                   4797:         }else{
                   4798:           printf(" To be kept %d%d flatdir[%d]=%d jk=%d q[%d]=p[%d] ",i,k,jk, flatdir[jk],jk, jkk, jk);
                   4799:           for(j=1; j <=ncovmodel;  jk++,jkk++,j++){
                   4800:             printf(" p[%d]=%12.7f=q[%d]",jk, p[jk],jkk);
                   4801:             /*q[jjk]=p[jk];*/
                   4802:           }
                   4803:         }
                   4804:         printf("\n");
                   4805:       }
                   4806:       fflush(stdout);
                   4807:     }
                   4808:   }
                   4809:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4810: #else  /* FLATSUP */
1.126     brouard  4811:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.319     brouard  4812: #endif  /* FLATSUP */
                   4813: 
                   4814: #ifdef LINMINORIGINAL
                   4815: #else
                   4816:       free_ivector(flatdir,1,npar); 
                   4817: #endif  /* LINMINORIGINAL*/
                   4818: #endif /* POWELL */
1.126     brouard  4819: 
1.162     brouard  4820: #ifdef NLOPT
                   4821: #ifdef NEWUOA
                   4822:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   4823: #else
                   4824:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   4825: #endif
                   4826:   lb=vector(0,npar-1);
                   4827:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   4828:   nlopt_set_lower_bounds(opt, lb);
                   4829:   nlopt_set_initial_step1(opt, 0.1);
                   4830:   
                   4831:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   4832:   d->function = func;
                   4833:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   4834:   nlopt_set_min_objective(opt, myfunc, d);
                   4835:   nlopt_set_xtol_rel(opt, ftol);
                   4836:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   4837:     printf("nlopt failed! %d\n",creturn); 
                   4838:   }
                   4839:   else {
                   4840:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   4841:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   4842:     iter=1; /* not equal */
                   4843:   }
                   4844:   nlopt_destroy(opt);
                   4845: #endif
1.319     brouard  4846: #ifdef FLATSUP
                   4847:   /* npared = npar -flatd/ncovmodel; */
                   4848:   /* xired= matrix(1,npared,1,npared); */
                   4849:   /* paramred= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */
                   4850:   /* powell(pred,xired,npared,ftol,&iter,&fret,flatdir,func); */
                   4851:   /* free_matrix(xire,1,npared,1,npared); */
                   4852: #else  /* FLATSUP */
                   4853: #endif /* FLATSUP */
1.126     brouard  4854:   free_matrix(xi,1,npar,1,npar);
                   4855:   fclose(ficrespow);
1.203     brouard  4856:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   4857:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  4858:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  4859: 
                   4860: }
                   4861: 
                   4862: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  4863: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  4864: {
                   4865:   double  **a,**y,*x,pd;
1.203     brouard  4866:   /* double **hess; */
1.164     brouard  4867:   int i, j;
1.126     brouard  4868:   int *indx;
                   4869: 
                   4870:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  4871:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  4872:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   4873:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   4874:   double gompertz(double p[]);
1.203     brouard  4875:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  4876: 
                   4877:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   4878:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   4879:   for (i=1;i<=npar;i++){
1.203     brouard  4880:     printf("%d-",i);fflush(stdout);
                   4881:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  4882:    
                   4883:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   4884:     
                   4885:     /*  printf(" %f ",p[i]);
                   4886:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   4887:   }
                   4888:   
                   4889:   for (i=1;i<=npar;i++) {
                   4890:     for (j=1;j<=npar;j++)  {
                   4891:       if (j>i) { 
1.203     brouard  4892:        printf(".%d-%d",i,j);fflush(stdout);
                   4893:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   4894:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  4895:        
                   4896:        hess[j][i]=hess[i][j];    
                   4897:        /*printf(" %lf ",hess[i][j]);*/
                   4898:       }
                   4899:     }
                   4900:   }
                   4901:   printf("\n");
                   4902:   fprintf(ficlog,"\n");
                   4903: 
                   4904:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4905:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4906:   
                   4907:   a=matrix(1,npar,1,npar);
                   4908:   y=matrix(1,npar,1,npar);
                   4909:   x=vector(1,npar);
                   4910:   indx=ivector(1,npar);
                   4911:   for (i=1;i<=npar;i++)
                   4912:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   4913:   ludcmp(a,npar,indx,&pd);
                   4914: 
                   4915:   for (j=1;j<=npar;j++) {
                   4916:     for (i=1;i<=npar;i++) x[i]=0;
                   4917:     x[j]=1;
                   4918:     lubksb(a,npar,indx,x);
                   4919:     for (i=1;i<=npar;i++){ 
                   4920:       matcov[i][j]=x[i];
                   4921:     }
                   4922:   }
                   4923: 
                   4924:   printf("\n#Hessian matrix#\n");
                   4925:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   4926:   for (i=1;i<=npar;i++) { 
                   4927:     for (j=1;j<=npar;j++) { 
1.203     brouard  4928:       printf("%.6e ",hess[i][j]);
                   4929:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  4930:     }
                   4931:     printf("\n");
                   4932:     fprintf(ficlog,"\n");
                   4933:   }
                   4934: 
1.203     brouard  4935:   /* printf("\n#Covariance matrix#\n"); */
                   4936:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   4937:   /* for (i=1;i<=npar;i++) {  */
                   4938:   /*   for (j=1;j<=npar;j++) {  */
                   4939:   /*     printf("%.6e ",matcov[i][j]); */
                   4940:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   4941:   /*   } */
                   4942:   /*   printf("\n"); */
                   4943:   /*   fprintf(ficlog,"\n"); */
                   4944:   /* } */
                   4945: 
1.126     brouard  4946:   /* Recompute Inverse */
1.203     brouard  4947:   /* for (i=1;i<=npar;i++) */
                   4948:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   4949:   /* ludcmp(a,npar,indx,&pd); */
                   4950: 
                   4951:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   4952: 
                   4953:   /* for (j=1;j<=npar;j++) { */
                   4954:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   4955:   /*   x[j]=1; */
                   4956:   /*   lubksb(a,npar,indx,x); */
                   4957:   /*   for (i=1;i<=npar;i++){  */
                   4958:   /*     y[i][j]=x[i]; */
                   4959:   /*     printf("%.3e ",y[i][j]); */
                   4960:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   4961:   /*   } */
                   4962:   /*   printf("\n"); */
                   4963:   /*   fprintf(ficlog,"\n"); */
                   4964:   /* } */
                   4965: 
                   4966:   /* Verifying the inverse matrix */
                   4967: #ifdef DEBUGHESS
                   4968:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  4969: 
1.203     brouard  4970:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   4971:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  4972: 
                   4973:   for (j=1;j<=npar;j++) {
                   4974:     for (i=1;i<=npar;i++){ 
1.203     brouard  4975:       printf("%.2f ",y[i][j]);
                   4976:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  4977:     }
                   4978:     printf("\n");
                   4979:     fprintf(ficlog,"\n");
                   4980:   }
1.203     brouard  4981: #endif
1.126     brouard  4982: 
                   4983:   free_matrix(a,1,npar,1,npar);
                   4984:   free_matrix(y,1,npar,1,npar);
                   4985:   free_vector(x,1,npar);
                   4986:   free_ivector(indx,1,npar);
1.203     brouard  4987:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  4988: 
                   4989: 
                   4990: }
                   4991: 
                   4992: /*************** hessian matrix ****************/
                   4993: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  4994: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  4995:   int i;
                   4996:   int l=1, lmax=20;
1.203     brouard  4997:   double k1,k2, res, fx;
1.132     brouard  4998:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  4999:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   5000:   int k=0,kmax=10;
                   5001:   double l1;
                   5002: 
                   5003:   fx=func(x);
                   5004:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  5005:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  5006:     l1=pow(10,l);
                   5007:     delts=delt;
                   5008:     for(k=1 ; k <kmax; k=k+1){
                   5009:       delt = delta*(l1*k);
                   5010:       p2[theta]=x[theta] +delt;
1.145     brouard  5011:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  5012:       p2[theta]=x[theta]-delt;
                   5013:       k2=func(p2)-fx;
                   5014:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  5015:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  5016:       
1.203     brouard  5017: #ifdef DEBUGHESSII
1.126     brouard  5018:       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);
                   5019:       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);
                   5020: #endif
                   5021:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   5022:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   5023:        k=kmax;
                   5024:       }
                   5025:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  5026:        k=kmax; l=lmax*10;
1.126     brouard  5027:       }
                   5028:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   5029:        delts=delt;
                   5030:       }
1.203     brouard  5031:     } /* End loop k */
1.126     brouard  5032:   }
                   5033:   delti[theta]=delts;
                   5034:   return res; 
                   5035:   
                   5036: }
                   5037: 
1.203     brouard  5038: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  5039: {
                   5040:   int i;
1.164     brouard  5041:   int l=1, lmax=20;
1.126     brouard  5042:   double k1,k2,k3,k4,res,fx;
1.132     brouard  5043:   double p2[MAXPARM+1];
1.203     brouard  5044:   int k, kmax=1;
                   5045:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  5046: 
                   5047:   int firstime=0;
1.203     brouard  5048:   
1.126     brouard  5049:   fx=func(x);
1.203     brouard  5050:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  5051:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  5052:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   5053:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  5054:     k1=func(p2)-fx;
                   5055:   
1.203     brouard  5056:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   5057:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  5058:     k2=func(p2)-fx;
                   5059:   
1.203     brouard  5060:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   5061:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  5062:     k3=func(p2)-fx;
                   5063:   
1.203     brouard  5064:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   5065:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  5066:     k4=func(p2)-fx;
1.203     brouard  5067:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   5068:     if(k1*k2*k3*k4 <0.){
1.208     brouard  5069:       firstime=1;
1.203     brouard  5070:       kmax=kmax+10;
1.208     brouard  5071:     }
                   5072:     if(kmax >=10 || firstime ==1){
1.246     brouard  5073:       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);
                   5074:       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  5075:       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);
                   5076:       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);
                   5077:     }
                   5078: #ifdef DEBUGHESSIJ
                   5079:     v1=hess[thetai][thetai];
                   5080:     v2=hess[thetaj][thetaj];
                   5081:     cv12=res;
                   5082:     /* Computing eigen value of Hessian matrix */
                   5083:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5084:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5085:     if ((lc2 <0) || (lc1 <0) ){
                   5086:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   5087:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   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:     }
1.126     brouard  5091: #endif
                   5092:   }
                   5093:   return res;
                   5094: }
                   5095: 
1.203     brouard  5096:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   5097: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   5098: /* { */
                   5099: /*   int i; */
                   5100: /*   int l=1, lmax=20; */
                   5101: /*   double k1,k2,k3,k4,res,fx; */
                   5102: /*   double p2[MAXPARM+1]; */
                   5103: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   5104: /*   int k=0,kmax=10; */
                   5105: /*   double l1; */
                   5106:   
                   5107: /*   fx=func(x); */
                   5108: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   5109: /*     l1=pow(10,l); */
                   5110: /*     delts=delt; */
                   5111: /*     for(k=1 ; k <kmax; k=k+1){ */
                   5112: /*       delt = delti*(l1*k); */
                   5113: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   5114: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   5115: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   5116: /*       k1=func(p2)-fx; */
                   5117:       
                   5118: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   5119: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   5120: /*       k2=func(p2)-fx; */
                   5121:       
                   5122: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   5123: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   5124: /*       k3=func(p2)-fx; */
                   5125:       
                   5126: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   5127: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   5128: /*       k4=func(p2)-fx; */
                   5129: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   5130: /* #ifdef DEBUGHESSIJ */
                   5131: /*       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); */
                   5132: /*       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); */
                   5133: /* #endif */
                   5134: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   5135: /*     k=kmax; */
                   5136: /*       } */
                   5137: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   5138: /*     k=kmax; l=lmax*10; */
                   5139: /*       } */
                   5140: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   5141: /*     delts=delt; */
                   5142: /*       } */
                   5143: /*     } /\* End loop k *\/ */
                   5144: /*   } */
                   5145: /*   delti[theta]=delts; */
                   5146: /*   return res;  */
                   5147: /* } */
                   5148: 
                   5149: 
1.126     brouard  5150: /************** Inverse of matrix **************/
                   5151: void ludcmp(double **a, int n, int *indx, double *d) 
                   5152: { 
                   5153:   int i,imax,j,k; 
                   5154:   double big,dum,sum,temp; 
                   5155:   double *vv; 
                   5156:  
                   5157:   vv=vector(1,n); 
                   5158:   *d=1.0; 
                   5159:   for (i=1;i<=n;i++) { 
                   5160:     big=0.0; 
                   5161:     for (j=1;j<=n;j++) 
                   5162:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  5163:     if (big == 0.0){
                   5164:       printf(" Singular Hessian matrix at row %d:\n",i);
                   5165:       for (j=1;j<=n;j++) {
                   5166:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   5167:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   5168:       }
                   5169:       fflush(ficlog);
                   5170:       fclose(ficlog);
                   5171:       nrerror("Singular matrix in routine ludcmp"); 
                   5172:     }
1.126     brouard  5173:     vv[i]=1.0/big; 
                   5174:   } 
                   5175:   for (j=1;j<=n;j++) { 
                   5176:     for (i=1;i<j;i++) { 
                   5177:       sum=a[i][j]; 
                   5178:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   5179:       a[i][j]=sum; 
                   5180:     } 
                   5181:     big=0.0; 
                   5182:     for (i=j;i<=n;i++) { 
                   5183:       sum=a[i][j]; 
                   5184:       for (k=1;k<j;k++) 
                   5185:        sum -= a[i][k]*a[k][j]; 
                   5186:       a[i][j]=sum; 
                   5187:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   5188:        big=dum; 
                   5189:        imax=i; 
                   5190:       } 
                   5191:     } 
                   5192:     if (j != imax) { 
                   5193:       for (k=1;k<=n;k++) { 
                   5194:        dum=a[imax][k]; 
                   5195:        a[imax][k]=a[j][k]; 
                   5196:        a[j][k]=dum; 
                   5197:       } 
                   5198:       *d = -(*d); 
                   5199:       vv[imax]=vv[j]; 
                   5200:     } 
                   5201:     indx[j]=imax; 
                   5202:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   5203:     if (j != n) { 
                   5204:       dum=1.0/(a[j][j]); 
                   5205:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   5206:     } 
                   5207:   } 
                   5208:   free_vector(vv,1,n);  /* Doesn't work */
                   5209: ;
                   5210: } 
                   5211: 
                   5212: void lubksb(double **a, int n, int *indx, double b[]) 
                   5213: { 
                   5214:   int i,ii=0,ip,j; 
                   5215:   double sum; 
                   5216:  
                   5217:   for (i=1;i<=n;i++) { 
                   5218:     ip=indx[i]; 
                   5219:     sum=b[ip]; 
                   5220:     b[ip]=b[i]; 
                   5221:     if (ii) 
                   5222:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   5223:     else if (sum) ii=i; 
                   5224:     b[i]=sum; 
                   5225:   } 
                   5226:   for (i=n;i>=1;i--) { 
                   5227:     sum=b[i]; 
                   5228:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   5229:     b[i]=sum/a[i][i]; 
                   5230:   } 
                   5231: } 
                   5232: 
                   5233: void pstamp(FILE *fichier)
                   5234: {
1.196     brouard  5235:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  5236: }
                   5237: 
1.297     brouard  5238: void date2dmy(double date,double *day, double *month, double *year){
                   5239:   double yp=0., yp1=0., yp2=0.;
                   5240:   
                   5241:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   5242:                        fractional in yp1 */
                   5243:   *year=yp;
                   5244:   yp2=modf((yp1*12),&yp);
                   5245:   *month=yp;
                   5246:   yp1=modf((yp2*30.5),&yp);
                   5247:   *day=yp;
                   5248:   if(*day==0) *day=1;
                   5249:   if(*month==0) *month=1;
                   5250: }
                   5251: 
1.253     brouard  5252: 
                   5253: 
1.126     brouard  5254: /************ Frequencies ********************/
1.251     brouard  5255: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  5256:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   5257:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  5258: {  /* Some frequencies as well as proposing some starting values */
1.332     brouard  5259:   /* Frequencies of any combination of dummy covariate used in the model equation */ 
1.265     brouard  5260:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  5261:   int iind=0, iage=0;
                   5262:   int mi; /* Effective wave */
                   5263:   int first;
                   5264:   double ***freq; /* Frequencies */
1.268     brouard  5265:   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 */
                   5266:   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  5267:   double *meanq, *stdq, *idq;
1.226     brouard  5268:   double **meanqt;
                   5269:   double *pp, **prop, *posprop, *pospropt;
                   5270:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   5271:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   5272:   double agebegin, ageend;
                   5273:     
                   5274:   pp=vector(1,nlstate);
1.251     brouard  5275:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  5276:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   5277:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   5278:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   5279:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  5280:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  5281:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  5282:   meanqt=matrix(1,lastpass,1,nqtveff);
                   5283:   strcpy(fileresp,"P_");
                   5284:   strcat(fileresp,fileresu);
                   5285:   /*strcat(fileresphtm,fileresu);*/
                   5286:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   5287:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   5288:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   5289:     exit(0);
                   5290:   }
1.240     brouard  5291:   
1.226     brouard  5292:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   5293:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   5294:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5295:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5296:     fflush(ficlog);
                   5297:     exit(70); 
                   5298:   }
                   5299:   else{
                   5300:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  5301: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  5302: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5303:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5304:   }
1.319     brouard  5305:   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  5306:   
1.226     brouard  5307:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   5308:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   5309:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5310:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5311:     fflush(ficlog);
                   5312:     exit(70); 
1.240     brouard  5313:   } else{
1.226     brouard  5314:     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  5315: ,<hr size=\"2\" color=\"#EC5E5E\"> \n                                  \
1.214     brouard  5316: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5317:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5318:   }
1.319     brouard  5319:   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  5320:   
1.253     brouard  5321:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   5322:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  5323:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  5324:   j1=0;
1.126     brouard  5325:   
1.227     brouard  5326:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
1.335     brouard  5327:   j=cptcoveff;  /* Only simple dummy covariates used in the model */
1.330     brouard  5328:   /* j=cptcovn;  /\* Only dummy covariates of the model *\/ */
1.226     brouard  5329:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  5330:   
                   5331:   
1.226     brouard  5332:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   5333:      reference=low_education V1=0,V2=0
                   5334:      med_educ                V1=1 V2=0, 
                   5335:      high_educ               V1=0 V2=1
1.330     brouard  5336:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcovn 
1.226     brouard  5337:   */
1.249     brouard  5338:   dateintsum=0;
                   5339:   k2cpt=0;
                   5340: 
1.253     brouard  5341:   if(cptcoveff == 0 )
1.265     brouard  5342:     nl=1;  /* Constant and age model only */
1.253     brouard  5343:   else
                   5344:     nl=2;
1.265     brouard  5345: 
                   5346:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   5347:   /* Loop on nj=1 or 2 if dummy covariates j!=0
1.335     brouard  5348:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
1.265     brouard  5349:    *     freq[s1][s2][iage] =0.
                   5350:    *     Loop on iind
                   5351:    *       ++freq[s1][s2][iage] weighted
                   5352:    *     end iind
                   5353:    *     if covariate and j!0
                   5354:    *       headers Variable on one line
                   5355:    *     endif cov j!=0
                   5356:    *     header of frequency table by age
                   5357:    *     Loop on age
                   5358:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   5359:    *       pos+=freq[s1][s2][iage] weighted
                   5360:    *       Loop on s1 initial state
                   5361:    *         fprintf(ficresp
                   5362:    *       end s1
                   5363:    *     end age
                   5364:    *     if j!=0 computes starting values
                   5365:    *     end compute starting values
                   5366:    *   end j1
                   5367:    * end nl 
                   5368:    */
1.253     brouard  5369:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   5370:     if(nj==1)
                   5371:       j=0;  /* First pass for the constant */
1.265     brouard  5372:     else{
1.335     brouard  5373:       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  5374:     }
1.251     brouard  5375:     first=1;
1.332     brouard  5376:     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  5377:       posproptt=0.;
1.330     brouard  5378:       /*printf("cptcovn=%d Tvaraff=%d", cptcovn,Tvaraff[1]);
1.251     brouard  5379:        scanf("%d", i);*/
                   5380:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  5381:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  5382:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  5383:            freq[i][s2][m]=0;
1.251     brouard  5384:       
                   5385:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  5386:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  5387:          prop[i][m]=0;
                   5388:        posprop[i]=0;
                   5389:        pospropt[i]=0;
                   5390:       }
1.283     brouard  5391:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  5392:         idq[z1]=0.;
                   5393:         meanq[z1]=0.;
                   5394:         stdq[z1]=0.;
1.283     brouard  5395:       }
                   5396:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  5397:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  5398:       /*         meanqt[m][z1]=0.; */
                   5399:       /*       } */
                   5400:       /* }       */
1.251     brouard  5401:       /* dateintsum=0; */
                   5402:       /* k2cpt=0; */
                   5403:       
1.265     brouard  5404:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  5405:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   5406:        bool=1;
                   5407:        if(j !=0){
                   5408:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.335     brouard  5409:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   5410:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
1.251     brouard  5411:                /* if(Tvaraff[z1] ==-20){ */
                   5412:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   5413:                /* }else  if(Tvaraff[z1] ==-10){ */
                   5414:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
1.330     brouard  5415:                /* }else  */ /* TODO TODO codtabm(j1,z1) or codtabm(j1,Tvaraff[z1]]z1)*/
1.335     brouard  5416:                /* 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); */
                   5417:                if(Tvaraff[z1]<1 || Tvaraff[z1]>=NCOVMAX)
1.338     brouard  5418:                  printf("Error Tvaraff[z1]=%d<1 or >=%d, cptcoveff=%d model=1+age+%s\n",Tvaraff[z1],NCOVMAX, cptcoveff, model);
1.332     brouard  5419:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]){ /* for combination j1 of covariates */
1.265     brouard  5420:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  5421:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
1.332     brouard  5422:                  /* 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", */
                   5423:                  /*   bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),*/
                   5424:                   /*   j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
1.251     brouard  5425:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   5426:                } /* Onlyf fixed */
                   5427:              } /* end z1 */
1.335     brouard  5428:            } /* cptcoveff > 0 */
1.251     brouard  5429:          } /* end any */
                   5430:        }/* end j==0 */
1.265     brouard  5431:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  5432:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  5433:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  5434:            m=mw[mi][iind];
                   5435:            if(j!=0){
                   5436:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
1.335     brouard  5437:                for (z1=1; z1<=cptcoveff; z1++) {
1.251     brouard  5438:                  if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  5439:                    /* iv= Tvar[Tmodelind[z1]]-ncovcol-nqv; /\* Good *\/ */
                   5440:                    iv= Tvar[Tmodelind[z1]]; /* Good *//* because cotvar starts now at first at ncovcol+nqv+ntv */ 
1.332     brouard  5441:                    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  5442:                                                                                      value is -1, we don't select. It differs from the 
                   5443:                                                                                      constant and age model which counts them. */
                   5444:                      bool=0; /* not selected */
                   5445:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
1.334     brouard  5446:                    /* i1=Tvaraff[z1]; */
                   5447:                    /* i2=TnsdVar[i1]; */
                   5448:                    /* i3=nbcode[i1][i2]; */
                   5449:                    /* i4=covar[i1][iind]; */
                   5450:                    /* if(i4 != i3){ */
                   5451:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) { /* Bug valgrind */
1.251     brouard  5452:                      bool=0;
                   5453:                    }
                   5454:                  }
                   5455:                }
                   5456:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   5457:            } /* end j==0 */
                   5458:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  5459:            if(bool==1){ /*Selected */
1.251     brouard  5460:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   5461:                 and mw[mi+1][iind]. dh depends on stepm. */
                   5462:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   5463:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   5464:              if(m >=firstpass && m <=lastpass){
                   5465:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   5466:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   5467:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   5468:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   5469:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   5470:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   5471:                if (m<lastpass) {
                   5472:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   5473:                  /*   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]); */
                   5474:                  if(s[m][iind]==-1)
                   5475:                    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.));
                   5476:                  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  5477:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
                   5478:                    if(!isnan(covar[ncovcol+z1][iind])){
1.332     brouard  5479:                      idq[z1]=idq[z1]+weight[iind];
                   5480:                      meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   5481:                      /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
                   5482:                      stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
1.311     brouard  5483:                    }
1.284     brouard  5484:                  }
1.251     brouard  5485:                  /* if((int)agev[m][iind] == 55) */
                   5486:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   5487:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   5488:                  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  5489:                }
1.251     brouard  5490:              } /* end if between passes */  
                   5491:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   5492:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   5493:                k2cpt++;
                   5494:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  5495:              }
1.251     brouard  5496:            }else{
                   5497:              bool=1;
                   5498:            }/* end bool 2 */
                   5499:          } /* end m */
1.284     brouard  5500:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   5501:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   5502:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   5503:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   5504:          /* } */
1.251     brouard  5505:        } /* end bool */
                   5506:       } /* end iind = 1 to imx */
1.319     brouard  5507:       /* prop[s][age] is fed for any initial and valid live state as well as
1.251     brouard  5508:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   5509:       
                   5510:       
                   5511:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.335     brouard  5512:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
1.265     brouard  5513:         pstamp(ficresp);
1.335     brouard  5514:       if  (cptcoveff>0 && j!=0){
1.265     brouard  5515:         pstamp(ficresp);
1.251     brouard  5516:        printf( "\n#********** Variable "); 
                   5517:        fprintf(ficresp, "\n#********** Variable "); 
                   5518:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   5519:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   5520:        fprintf(ficlog, "\n#********** Variable "); 
1.340     brouard  5521:        for (z1=1; z1<=cptcoveff; z1++){
1.251     brouard  5522:          if(!FixedV[Tvaraff[z1]]){
1.330     brouard  5523:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5524:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5525:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5526:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5527:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.250     brouard  5528:          }else{
1.330     brouard  5529:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5530:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5531:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5532:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5533:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.251     brouard  5534:          }
                   5535:        }
                   5536:        printf( "**********\n#");
                   5537:        fprintf(ficresp, "**********\n#");
                   5538:        fprintf(ficresphtm, "**********</h3>\n");
                   5539:        fprintf(ficresphtmfr, "**********</h3>\n");
                   5540:        fprintf(ficlog, "**********\n");
                   5541:       }
1.284     brouard  5542:       /*
                   5543:        Printing means of quantitative variables if any
                   5544:       */
                   5545:       for (z1=1; z1<= nqfveff; z1++) {
1.311     brouard  5546:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.312     brouard  5547:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
1.284     brouard  5548:        if(weightopt==1){
                   5549:          printf(" Weighted mean and standard deviation of");
                   5550:          fprintf(ficlog," Weighted mean and standard deviation of");
                   5551:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   5552:        }
1.311     brouard  5553:        /* mu = \frac{w x}{\sum w}
                   5554:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
                   5555:        */
                   5556:        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]));
                   5557:        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]));
                   5558:        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  5559:       }
                   5560:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   5561:       /*       for(m=1;m<=lastpass;m++){ */
                   5562:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   5563:       /*   } */
                   5564:       /* } */
1.283     brouard  5565: 
1.251     brouard  5566:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.335     brouard  5567:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
1.265     brouard  5568:         fprintf(ficresp, " Age");
1.335     brouard  5569:       if(nj==2) for (z1=1; z1<=cptcoveff; z1++) {
                   5570:          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]]);
                   5571:          fprintf(ficresp, " V%d=%d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5572:        }
1.251     brouard  5573:       for(i=1; i<=nlstate;i++) {
1.335     brouard  5574:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  5575:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   5576:       }
1.335     brouard  5577:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  5578:       fprintf(ficresphtm, "\n");
                   5579:       
                   5580:       /* Header of frequency table by age */
                   5581:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   5582:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  5583:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  5584:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5585:          if(s2!=0 && m!=0)
                   5586:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  5587:        }
1.226     brouard  5588:       }
1.251     brouard  5589:       fprintf(ficresphtmfr, "\n");
                   5590:     
                   5591:       /* For each age */
                   5592:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   5593:        fprintf(ficresphtm,"<tr>");
                   5594:        if(iage==iagemax+1){
                   5595:          fprintf(ficlog,"1");
                   5596:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   5597:        }else if(iage==iagemax+2){
                   5598:          fprintf(ficlog,"0");
                   5599:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   5600:        }else if(iage==iagemax+3){
                   5601:          fprintf(ficlog,"Total");
                   5602:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   5603:        }else{
1.240     brouard  5604:          if(first==1){
1.251     brouard  5605:            first=0;
                   5606:            printf("See log file for details...\n");
                   5607:          }
                   5608:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   5609:          fprintf(ficlog,"Age %d", iage);
                   5610:        }
1.265     brouard  5611:        for(s1=1; s1 <=nlstate ; s1++){
                   5612:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   5613:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  5614:        }
1.265     brouard  5615:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5616:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  5617:            pos += freq[s1][m][iage];
                   5618:          if(pp[s1]>=1.e-10){
1.251     brouard  5619:            if(first==1){
1.265     brouard  5620:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5621:            }
1.265     brouard  5622:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5623:          }else{
                   5624:            if(first==1)
1.265     brouard  5625:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   5626:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  5627:          }
                   5628:        }
                   5629:       
1.265     brouard  5630:        for(s1=1; s1 <=nlstate ; s1++){ 
                   5631:          /* posprop[s1]=0; */
                   5632:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   5633:            pp[s1] += freq[s1][m][iage];
                   5634:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   5635:       
                   5636:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   5637:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   5638:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5639:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5640:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5641:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5642:        }
                   5643:        
                   5644:        /* Writing ficresp */
1.335     brouard  5645:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5646:           if( iage <= iagemax){
                   5647:            fprintf(ficresp," %d",iage);
                   5648:           }
                   5649:         }else if( nj==2){
                   5650:           if( iage <= iagemax){
                   5651:            fprintf(ficresp," %d",iage);
1.335     brouard  5652:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.265     brouard  5653:           }
1.240     brouard  5654:        }
1.265     brouard  5655:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  5656:          if(pos>=1.e-5){
1.251     brouard  5657:            if(first==1)
1.265     brouard  5658:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   5659:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  5660:          }else{
                   5661:            if(first==1)
1.265     brouard  5662:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   5663:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  5664:          }
                   5665:          if( iage <= iagemax){
                   5666:            if(pos>=1.e-5){
1.335     brouard  5667:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5668:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5669:               }else if( nj==2){
                   5670:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5671:               }
                   5672:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5673:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   5674:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   5675:            } else{
1.335     brouard  5676:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
1.265     brouard  5677:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  5678:            }
1.240     brouard  5679:          }
1.265     brouard  5680:          pospropt[s1] +=posprop[s1];
                   5681:        } /* end loop s1 */
1.251     brouard  5682:        /* pospropt=0.; */
1.265     brouard  5683:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  5684:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5685:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  5686:              if(first==1){
1.265     brouard  5687:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5688:              }
1.265     brouard  5689:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   5690:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5691:            }
1.265     brouard  5692:            if(s1!=0 && m!=0)
                   5693:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  5694:          }
1.265     brouard  5695:        } /* end loop s1 */
1.251     brouard  5696:        posproptt=0.; 
1.265     brouard  5697:        for(s1=1; s1 <=nlstate; s1++){
                   5698:          posproptt += pospropt[s1];
1.251     brouard  5699:        }
                   5700:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  5701:        fprintf(ficresphtm,"</tr>\n");
1.335     brouard  5702:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
1.265     brouard  5703:          if(iage <= iagemax)
                   5704:            fprintf(ficresp,"\n");
1.240     brouard  5705:        }
1.251     brouard  5706:        if(first==1)
                   5707:          printf("Others in log...\n");
                   5708:        fprintf(ficlog,"\n");
                   5709:       } /* end loop age iage */
1.265     brouard  5710:       
1.251     brouard  5711:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  5712:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5713:        if(posproptt < 1.e-5){
1.265     brouard  5714:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  5715:        }else{
1.265     brouard  5716:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  5717:        }
1.226     brouard  5718:       }
1.251     brouard  5719:       fprintf(ficresphtm,"</tr>\n");
                   5720:       fprintf(ficresphtm,"</table>\n");
                   5721:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  5722:       if(posproptt < 1.e-5){
1.251     brouard  5723:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   5724:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  5725:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   5726:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  5727:        invalidvarcomb[j1]=1;
1.226     brouard  5728:       }else{
1.338     brouard  5729:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced (or no resultline).</p>",j1);
1.251     brouard  5730:        invalidvarcomb[j1]=0;
1.226     brouard  5731:       }
1.251     brouard  5732:       fprintf(ficresphtmfr,"</table>\n");
                   5733:       fprintf(ficlog,"\n");
                   5734:       if(j!=0){
                   5735:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  5736:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5737:          for(k=1; k <=(nlstate+ndeath); k++){
                   5738:            if (k != i) {
1.265     brouard  5739:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  5740:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  5741:                  if(j1==1){ /* All dummy covariates to zero */
                   5742:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   5743:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  5744:                    printf("%d%d ",i,k);
                   5745:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5746:                    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]));
                   5747:                    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]));
                   5748:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  5749:                  }
1.253     brouard  5750:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   5751:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   5752:                    x[iage]= (double)iage;
                   5753:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  5754:                    /* 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  5755:                  }
1.268     brouard  5756:                  /* Some are not finite, but linreg will ignore these ages */
                   5757:                  no=0;
1.253     brouard  5758:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  5759:                  pstart[s1]=b;
                   5760:                  pstart[s1-1]=a;
1.252     brouard  5761:                }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 */ 
                   5762:                  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]);
                   5763:                  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  5764:                  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  5765:                  printf("%d%d ",i,k);
                   5766:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5767:                  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  5768:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   5769:                  ;
                   5770:                }
                   5771:                /* printf("%12.7f )", param[i][jj][k]); */
                   5772:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5773:                s1++; 
1.251     brouard  5774:              } /* end jj */
                   5775:            } /* end k!= i */
                   5776:          } /* end k */
1.265     brouard  5777:        } /* end i, s1 */
1.251     brouard  5778:       } /* end j !=0 */
                   5779:     } /* end selected combination of covariate j1 */
                   5780:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   5781:       printf("#Freqsummary: Starting values for the constants:\n");
                   5782:       fprintf(ficlog,"\n");
1.265     brouard  5783:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5784:        for(k=1; k <=(nlstate+ndeath); k++){
                   5785:          if (k != i) {
                   5786:            printf("%d%d ",i,k);
                   5787:            fprintf(ficlog,"%d%d ",i,k);
                   5788:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  5789:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  5790:              if(jj==1){ /* Age has to be done */
1.265     brouard  5791:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   5792:                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]));
                   5793:                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  5794:              }
                   5795:              /* printf("%12.7f )", param[i][jj][k]); */
                   5796:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5797:              s1++; 
1.250     brouard  5798:            }
1.251     brouard  5799:            printf("\n");
                   5800:            fprintf(ficlog,"\n");
1.250     brouard  5801:          }
                   5802:        }
1.284     brouard  5803:       } /* end of state i */
1.251     brouard  5804:       printf("#Freqsummary\n");
                   5805:       fprintf(ficlog,"\n");
1.265     brouard  5806:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   5807:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   5808:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   5809:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5810:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5811:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   5812:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   5813:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  5814:          /* } */
                   5815:        }
1.265     brouard  5816:       } /* end loop s1 */
1.251     brouard  5817:       
                   5818:       printf("\n");
                   5819:       fprintf(ficlog,"\n");
                   5820:     } /* end j=0 */
1.249     brouard  5821:   } /* end j */
1.252     brouard  5822: 
1.253     brouard  5823:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  5824:     for(i=1, jk=1; i <=nlstate; i++){
                   5825:       for(j=1; j <=nlstate+ndeath; j++){
                   5826:        if(j!=i){
                   5827:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5828:          printf("%1d%1d",i,j);
                   5829:          fprintf(ficparo,"%1d%1d",i,j);
                   5830:          for(k=1; k<=ncovmodel;k++){
                   5831:            /*    printf(" %lf",param[i][j][k]); */
                   5832:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   5833:            p[jk]=pstart[jk];
                   5834:            printf(" %f ",pstart[jk]);
                   5835:            fprintf(ficparo," %f ",pstart[jk]);
                   5836:            jk++;
                   5837:          }
                   5838:          printf("\n");
                   5839:          fprintf(ficparo,"\n");
                   5840:        }
                   5841:       }
                   5842:     }
                   5843:   } /* end mle=-2 */
1.226     brouard  5844:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  5845:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  5846:   
1.226     brouard  5847:   fclose(ficresp);
                   5848:   fclose(ficresphtm);
                   5849:   fclose(ficresphtmfr);
1.283     brouard  5850:   free_vector(idq,1,nqfveff);
1.226     brouard  5851:   free_vector(meanq,1,nqfveff);
1.284     brouard  5852:   free_vector(stdq,1,nqfveff);
1.226     brouard  5853:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  5854:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   5855:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  5856:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5857:   free_vector(pospropt,1,nlstate);
                   5858:   free_vector(posprop,1,nlstate);
1.251     brouard  5859:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5860:   free_vector(pp,1,nlstate);
                   5861:   /* End of freqsummary */
                   5862: }
1.126     brouard  5863: 
1.268     brouard  5864: /* Simple linear regression */
                   5865: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   5866: 
                   5867:   /* y=a+bx regression */
                   5868:   double   sumx = 0.0;                        /* sum of x                      */
                   5869:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   5870:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   5871:   double   sumy = 0.0;                        /* sum of y                      */
                   5872:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   5873:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   5874:   double yhat;
                   5875:   
                   5876:   double denom=0;
                   5877:   int i;
                   5878:   int ne=*no;
                   5879:   
                   5880:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5881:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5882:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5883:       continue;
                   5884:     }
                   5885:     ne=ne+1;
                   5886:     sumx  += x[i];       
                   5887:     sumx2 += x[i]*x[i];  
                   5888:     sumxy += x[i] * y[i];
                   5889:     sumy  += y[i];      
                   5890:     sumy2 += y[i]*y[i]; 
                   5891:     denom = (ne * sumx2 - sumx*sumx);
                   5892:     /* 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); */
                   5893:   } 
                   5894:   
                   5895:   denom = (ne * sumx2 - sumx*sumx);
                   5896:   if (denom == 0) {
                   5897:     // vertical, slope m is infinity
                   5898:     *b = INFINITY;
                   5899:     *a = 0;
                   5900:     if (r) *r = 0;
                   5901:     return 1;
                   5902:   }
                   5903:   
                   5904:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   5905:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   5906:   if (r!=NULL) {
                   5907:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   5908:       sqrt((sumx2 - sumx*sumx/ne) *
                   5909:           (sumy2 - sumy*sumy/ne));
                   5910:   }
                   5911:   *no=ne;
                   5912:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5913:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5914:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5915:       continue;
                   5916:     }
                   5917:     ne=ne+1;
                   5918:     yhat = y[i] - *a -*b* x[i];
                   5919:     sume2  += yhat * yhat ;       
                   5920:     
                   5921:     denom = (ne * sumx2 - sumx*sumx);
                   5922:     /* 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); */
                   5923:   } 
                   5924:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   5925:   *sa= *sb * sqrt(sumx2/ne);
                   5926:   
                   5927:   return 0; 
                   5928: }
                   5929: 
1.126     brouard  5930: /************ Prevalence ********************/
1.227     brouard  5931: 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)
                   5932: {  
                   5933:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   5934:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   5935:      We still use firstpass and lastpass as another selection.
                   5936:   */
1.126     brouard  5937:  
1.227     brouard  5938:   int i, m, jk, j1, bool, z1,j, iv;
                   5939:   int mi; /* Effective wave */
                   5940:   int iage;
                   5941:   double agebegin, ageend;
                   5942: 
                   5943:   double **prop;
                   5944:   double posprop; 
                   5945:   double  y2; /* in fractional years */
                   5946:   int iagemin, iagemax;
                   5947:   int first; /** to stop verbosity which is redirected to log file */
                   5948: 
                   5949:   iagemin= (int) agemin;
                   5950:   iagemax= (int) agemax;
                   5951:   /*pp=vector(1,nlstate);*/
1.251     brouard  5952:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  5953:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   5954:   j1=0;
1.222     brouard  5955:   
1.227     brouard  5956:   /*j=cptcoveff;*/
                   5957:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  5958:   
1.288     brouard  5959:   first=0;
1.335     brouard  5960:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of simple dummy covariates */
1.227     brouard  5961:     for (i=1; i<=nlstate; i++)  
1.251     brouard  5962:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  5963:        prop[i][iage]=0.0;
                   5964:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   5965:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   5966:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   5967:     
                   5968:     for (i=1; i<=imx; i++) { /* Each individual */
                   5969:       bool=1;
                   5970:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   5971:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   5972:        m=mw[mi][i];
                   5973:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   5974:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   5975:        for (z1=1; z1<=cptcoveff; z1++){
                   5976:          if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  5977:            iv= Tvar[Tmodelind[z1]];/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
1.332     brouard  5978:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality */
1.227     brouard  5979:              bool=0;
                   5980:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
1.332     brouard  5981:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) {
1.227     brouard  5982:              bool=0;
                   5983:            }
                   5984:        }
                   5985:        if(bool==1){ /* Otherwise we skip that wave/person */
                   5986:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   5987:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   5988:          if(m >=firstpass && m <=lastpass){
                   5989:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   5990:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   5991:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   5992:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  5993:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  5994:                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); 
                   5995:                exit(1);
                   5996:              }
                   5997:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   5998:                /*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]]);*/
                   5999:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   6000:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   6001:              } /* end valid statuses */ 
                   6002:            } /* end selection of dates */
                   6003:          } /* end selection of waves */
                   6004:        } /* end bool */
                   6005:       } /* end wave */
                   6006:     } /* end individual */
                   6007:     for(i=iagemin; i <= iagemax+3; i++){  
                   6008:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   6009:        posprop += prop[jk][i]; 
                   6010:       } 
                   6011:       
                   6012:       for(jk=1; jk <=nlstate ; jk++){      
                   6013:        if( i <=  iagemax){ 
                   6014:          if(posprop>=1.e-5){ 
                   6015:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   6016:          } else{
1.288     brouard  6017:            if(!first){
                   6018:              first=1;
1.266     brouard  6019:              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]);
                   6020:            }else{
1.288     brouard  6021:              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  6022:            }
                   6023:          }
                   6024:        } 
                   6025:       }/* end jk */ 
                   6026:     }/* end i */ 
1.222     brouard  6027:      /*} *//* end i1 */
1.227     brouard  6028:   } /* end j1 */
1.222     brouard  6029:   
1.227     brouard  6030:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   6031:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  6032:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  6033: }  /* End of prevalence */
1.126     brouard  6034: 
                   6035: /************* Waves Concatenation ***************/
                   6036: 
                   6037: 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)
                   6038: {
1.298     brouard  6039:   /* 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  6040:      Death is a valid wave (if date is known).
                   6041:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   6042:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  6043:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  6044:   */
1.126     brouard  6045: 
1.224     brouard  6046:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  6047:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   6048:      double sum=0., jmean=0.;*/
1.224     brouard  6049:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  6050:   int j, k=0,jk, ju, jl;
                   6051:   double sum=0.;
                   6052:   first=0;
1.214     brouard  6053:   firstwo=0;
1.217     brouard  6054:   firsthree=0;
1.218     brouard  6055:   firstfour=0;
1.164     brouard  6056:   jmin=100000;
1.126     brouard  6057:   jmax=-1;
                   6058:   jmean=0.;
1.224     brouard  6059: 
                   6060: /* Treating live states */
1.214     brouard  6061:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  6062:     mi=0;  /* First valid wave */
1.227     brouard  6063:     mli=0; /* Last valid wave */
1.309     brouard  6064:     m=firstpass;  /* Loop on waves */
                   6065:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
1.227     brouard  6066:       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 */
                   6067:        mli=m-1;/* mw[++mi][i]=m-1; */
                   6068:       }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  6069:        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  6070:        mli=m;
1.224     brouard  6071:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   6072:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  6073:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  6074:       }
1.309     brouard  6075:       else{ /* m = lastpass, eventual special issue with warning */
1.224     brouard  6076: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  6077:        break;
1.224     brouard  6078: #else
1.317     brouard  6079:        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  6080:          if(firsthree == 0){
1.302     brouard  6081:            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  6082:            firsthree=1;
1.317     brouard  6083:          }else if(firsthree >=1 && firsthree < 10){
                   6084:            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);
                   6085:            firsthree++;
                   6086:          }else if(firsthree == 10){
                   6087:            printf("Information, too many Information flags: no more reported to log either\n");
                   6088:            fprintf(ficlog,"Information, too many Information flags: no more reported to log either\n");
                   6089:            firsthree++;
                   6090:          }else{
                   6091:            firsthree++;
1.227     brouard  6092:          }
1.309     brouard  6093:          mw[++mi][i]=m; /* Valid transition with unknown status */
1.227     brouard  6094:          mli=m;
                   6095:        }
                   6096:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   6097:          nbwarn++;
1.309     brouard  6098:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
1.227     brouard  6099:            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);
                   6100:            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);
                   6101:          }
                   6102:          break;
                   6103:        }
                   6104:        break;
1.224     brouard  6105: #endif
1.227     brouard  6106:       }/* End m >= lastpass */
1.126     brouard  6107:     }/* end while */
1.224     brouard  6108: 
1.227     brouard  6109:     /* 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  6110:     /* After last pass */
1.224     brouard  6111: /* Treating death states */
1.214     brouard  6112:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  6113:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   6114:       /* } */
1.126     brouard  6115:       mi++;    /* Death is another wave */
                   6116:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  6117:       /* Only death is a correct wave */
1.126     brouard  6118:       mw[mi][i]=m;
1.257     brouard  6119:     } /* else not in a death state */
1.224     brouard  6120: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  6121:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  6122:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.309     brouard  6123:        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  6124:          nbwarn++;
                   6125:          if(firstfiv==0){
1.309     brouard  6126:            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  6127:            firstfiv=1;
                   6128:          }else{
1.309     brouard  6129:            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  6130:          }
1.309     brouard  6131:            s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
                   6132:        }else{ /* Month of Death occured afer last wave month, potential bias */
1.227     brouard  6133:          nberr++;
                   6134:          if(firstwo==0){
1.309     brouard  6135:            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  6136:            firstwo=1;
                   6137:          }
1.309     brouard  6138:          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  6139:        }
1.257     brouard  6140:       }else{ /* if date of interview is unknown */
1.227     brouard  6141:        /* death is known but not confirmed by death status at any wave */
                   6142:        if(firstfour==0){
1.309     brouard  6143:          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  6144:          firstfour=1;
                   6145:        }
1.309     brouard  6146:        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  6147:       }
1.224     brouard  6148:     } /* end if date of death is known */
                   6149: #endif
1.309     brouard  6150:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
                   6151:     /* wav[i]=mw[mi][i];   */
1.126     brouard  6152:     if(mi==0){
                   6153:       nbwarn++;
                   6154:       if(first==0){
1.227     brouard  6155:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   6156:        first=1;
1.126     brouard  6157:       }
                   6158:       if(first==1){
1.227     brouard  6159:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  6160:       }
                   6161:     } /* end mi==0 */
                   6162:   } /* End individuals */
1.214     brouard  6163:   /* wav and mw are no more changed */
1.223     brouard  6164:        
1.317     brouard  6165:   printf("Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   6166:   fprintf(ficlog,"Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   6167: 
                   6168: 
1.126     brouard  6169:   for(i=1; i<=imx; i++){
                   6170:     for(mi=1; mi<wav[i];mi++){
                   6171:       if (stepm <=0)
1.227     brouard  6172:        dh[mi][i]=1;
1.126     brouard  6173:       else{
1.260     brouard  6174:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  6175:          if (agedc[i] < 2*AGESUP) {
                   6176:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   6177:            if(j==0) j=1;  /* Survives at least one month after exam */
                   6178:            else if(j<0){
                   6179:              nberr++;
                   6180:              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]);
                   6181:              j=1; /* Temporary Dangerous patch */
                   6182:              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);
                   6183:              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]);
                   6184:              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);
                   6185:            }
                   6186:            k=k+1;
                   6187:            if (j >= jmax){
                   6188:              jmax=j;
                   6189:              ijmax=i;
                   6190:            }
                   6191:            if (j <= jmin){
                   6192:              jmin=j;
                   6193:              ijmin=i;
                   6194:            }
                   6195:            sum=sum+j;
                   6196:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   6197:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   6198:          }
                   6199:        }
                   6200:        else{
                   6201:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  6202: /*       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  6203:                                        
1.227     brouard  6204:          k=k+1;
                   6205:          if (j >= jmax) {
                   6206:            jmax=j;
                   6207:            ijmax=i;
                   6208:          }
                   6209:          else if (j <= jmin){
                   6210:            jmin=j;
                   6211:            ijmin=i;
                   6212:          }
                   6213:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   6214:          /*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]);*/
                   6215:          if(j<0){
                   6216:            nberr++;
                   6217:            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]);
                   6218:            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]);
                   6219:          }
                   6220:          sum=sum+j;
                   6221:        }
                   6222:        jk= j/stepm;
                   6223:        jl= j -jk*stepm;
                   6224:        ju= j -(jk+1)*stepm;
                   6225:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   6226:          if(jl==0){
                   6227:            dh[mi][i]=jk;
                   6228:            bh[mi][i]=0;
                   6229:          }else{ /* We want a negative bias in order to only have interpolation ie
                   6230:                  * to avoid the price of an extra matrix product in likelihood */
                   6231:            dh[mi][i]=jk+1;
                   6232:            bh[mi][i]=ju;
                   6233:          }
                   6234:        }else{
                   6235:          if(jl <= -ju){
                   6236:            dh[mi][i]=jk;
                   6237:            bh[mi][i]=jl;       /* bias is positive if real duration
                   6238:                                 * is higher than the multiple of stepm and negative otherwise.
                   6239:                                 */
                   6240:          }
                   6241:          else{
                   6242:            dh[mi][i]=jk+1;
                   6243:            bh[mi][i]=ju;
                   6244:          }
                   6245:          if(dh[mi][i]==0){
                   6246:            dh[mi][i]=1; /* At least one step */
                   6247:            bh[mi][i]=ju; /* At least one step */
                   6248:            /*  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);*/
                   6249:          }
                   6250:        } /* end if mle */
1.126     brouard  6251:       }
                   6252:     } /* end wave */
                   6253:   }
                   6254:   jmean=sum/k;
                   6255:   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  6256:   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  6257: }
1.126     brouard  6258: 
                   6259: /*********** Tricode ****************************/
1.220     brouard  6260:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  6261:  {
                   6262:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   6263:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   6264:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   6265:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   6266:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   6267:     */
1.130     brouard  6268: 
1.242     brouard  6269:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   6270:    int modmaxcovj=0; /* Modality max of covariates j */
                   6271:    int cptcode=0; /* Modality max of covariates j */
                   6272:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  6273: 
                   6274: 
1.242     brouard  6275:    /* cptcoveff=0;  */
                   6276:    /* *cptcov=0; */
1.126     brouard  6277:  
1.242     brouard  6278:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  6279:    for (k=1; k <= maxncov; k++)
                   6280:      for(j=1; j<=2; j++)
                   6281:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  6282: 
1.242     brouard  6283:    /* Loop on covariates without age and products and no quantitative variable */
1.335     brouard  6284:    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  6285:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
1.343     brouard  6286:      /* printf("Testing k=%d, cptcovt=%d\n",k, cptcovt); */
1.339     brouard  6287:      if(Dummy[k]==0 && Typevar[k] !=1 && Typevar[k] != 2){ /* Dummy covariate and not age product nor fixed product */ 
1.242     brouard  6288:        switch(Fixed[k]) {
                   6289:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.311     brouard  6290:         modmaxcovj=0;
                   6291:         modmincovj=0;
1.242     brouard  6292:         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  6293:           /* 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  6294:           ij=(int)(covar[Tvar[k]][i]);
                   6295:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   6296:            * If product of Vn*Vm, still boolean *:
                   6297:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   6298:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   6299:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   6300:              modality of the nth covariate of individual i. */
                   6301:           if (ij > modmaxcovj)
                   6302:             modmaxcovj=ij; 
                   6303:           else if (ij < modmincovj) 
                   6304:             modmincovj=ij; 
1.287     brouard  6305:           if (ij <0 || ij >1 ){
1.311     brouard  6306:             printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6307:             fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6308:             fflush(ficlog);
                   6309:             exit(1);
1.287     brouard  6310:           }
                   6311:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  6312:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   6313:             exit(1);
                   6314:           }else
                   6315:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   6316:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   6317:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   6318:           /* getting the maximum value of the modality of the covariate
                   6319:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   6320:              female ies 1, then modmaxcovj=1.
                   6321:           */
                   6322:         } /* end for loop on individuals i */
                   6323:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6324:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6325:         cptcode=modmaxcovj;
                   6326:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   6327:         /*for (i=0; i<=cptcode; i++) {*/
                   6328:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   6329:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6330:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6331:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   6332:             if( j != -1){
                   6333:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   6334:                                  covariate for which somebody answered excluding 
                   6335:                                  undefined. Usually 2: 0 and 1. */
                   6336:             }
                   6337:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   6338:                                     covariate for which somebody answered including 
                   6339:                                     undefined. Usually 3: -1, 0 and 1. */
                   6340:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   6341:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   6342:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  6343:                        
1.242     brouard  6344:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   6345:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   6346:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   6347:         /* modmincovj=3; modmaxcovj = 7; */
                   6348:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   6349:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   6350:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   6351:         /* nbcode[Tvar[j]][ij]=k; */
                   6352:         /* nbcode[Tvar[j]][1]=0; */
                   6353:         /* nbcode[Tvar[j]][2]=1; */
                   6354:         /* nbcode[Tvar[j]][3]=2; */
                   6355:         /* To be continued (not working yet). */
                   6356:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  6357: 
                   6358:         /* 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*/
                   6359:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   6360:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   6361:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   6362:         /*, could be restored in the future */
                   6363:         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  6364:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   6365:             break;
                   6366:           }
                   6367:           ij++;
1.287     brouard  6368:           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  6369:           cptcode = ij; /* New max modality for covar j */
                   6370:         } /* end of loop on modality i=-1 to 1 or more */
                   6371:         break;
                   6372:        case 1: /* Testing on varying covariate, could be simple and
                   6373:                * should look at waves or product of fixed *
                   6374:                * varying. No time to test -1, assuming 0 and 1 only */
                   6375:         ij=0;
                   6376:         for(i=0; i<=1;i++){
                   6377:           nbcode[Tvar[k]][++ij]=i;
                   6378:         }
                   6379:         break;
                   6380:        default:
                   6381:         break;
                   6382:        } /* end switch */
                   6383:      } /* end dummy test */
1.342     brouard  6384:      if(Dummy[k]==1 && Typevar[k] !=1 && Fixed ==0){ /* Fixed Quantitative covariate and not age product */ 
1.311     brouard  6385:        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  6386:         if(Tvar[k]<=0 || Tvar[k]>=NCOVMAX){
                   6387:           printf("Error k=%d \n",k);
                   6388:           exit(1);
                   6389:         }
1.311     brouard  6390:         if(isnan(covar[Tvar[k]][i])){
                   6391:           printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6392:           fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6393:           fflush(ficlog);
                   6394:           exit(1);
                   6395:          }
                   6396:        }
1.335     brouard  6397:      } /* end Quanti */
1.287     brouard  6398:    } /* 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  6399:   
                   6400:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   6401:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   6402:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   6403:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   6404:      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 */ 
                   6405:      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 */
                   6406:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   6407:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   6408:   
                   6409:    ij=0;
                   6410:    /* 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  6411:    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 */
                   6412:      /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
1.242     brouard  6413:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   6414:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
1.335     brouard  6415:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy simple and non empty in the model */
                   6416:        /* Typevar[k] =0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for product */
                   6417:        /* 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  6418:        /* If product not in single variable we don't print results */
                   6419:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
1.335     brouard  6420:        ++ij;/*    V5 + V4 + V3 + V4*V3 + V5*age + V2 +  V1*V2 + V1*age + V1, *//* V5 quanti, V2 quanti, V4, V3, V1 dummies */
                   6421:        /* k=       1    2   3     4       5       6      7       8        9  */
                   6422:        /* Tvar[k]= 5    4    3    6       5       2      7       1        1  */
                   6423:        /* ij            1    2                                            3  */  
                   6424:        /* Tvaraff[ij]=  4    3                                            1  */
                   6425:        /* Tmodelind[ij]=2    3                                            9  */
                   6426:        /* TmodelInvind[ij]=2 1                                            1  */
1.242     brouard  6427:        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*/
                   6428:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   6429:        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 */
                   6430:        if(Fixed[k]!=0)
                   6431:         anyvaryingduminmodel=1;
                   6432:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   6433:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6434:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   6435:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   6436:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   6437:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6438:      } 
                   6439:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   6440:    /* ij--; */
                   6441:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
1.335     brouard  6442:    *cptcov=ij; /* cptcov= Number of total real effective simple dummies (fixed or time  arying) effective (used as cptcoveff in other functions)
1.242     brouard  6443:                * because they can be excluded from the model and real
                   6444:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   6445:    for(j=ij+1; j<= cptcovt; j++){
                   6446:      Tvaraff[j]=0;
                   6447:      Tmodelind[j]=0;
                   6448:    }
                   6449:    for(j=ntveff+1; j<= cptcovt; j++){
                   6450:      TmodelInvind[j]=0;
                   6451:    }
                   6452:    /* To be sorted */
                   6453:    ;
                   6454:  }
1.126     brouard  6455: 
1.145     brouard  6456: 
1.126     brouard  6457: /*********** Health Expectancies ****************/
                   6458: 
1.235     brouard  6459:  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  6460: 
                   6461: {
                   6462:   /* Health expectancies, no variances */
1.329     brouard  6463:   /* cij is the combination in the list of combination of dummy covariates */
                   6464:   /* strstart is a string of time at start of computing */
1.164     brouard  6465:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  6466:   int nhstepma, nstepma; /* Decreasing with age */
                   6467:   double age, agelim, hf;
                   6468:   double ***p3mat;
                   6469:   double eip;
                   6470: 
1.238     brouard  6471:   /* pstamp(ficreseij); */
1.126     brouard  6472:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   6473:   fprintf(ficreseij,"# Age");
                   6474:   for(i=1; i<=nlstate;i++){
                   6475:     for(j=1; j<=nlstate;j++){
                   6476:       fprintf(ficreseij," e%1d%1d ",i,j);
                   6477:     }
                   6478:     fprintf(ficreseij," e%1d. ",i);
                   6479:   }
                   6480:   fprintf(ficreseij,"\n");
                   6481: 
                   6482:   
                   6483:   if(estepm < stepm){
                   6484:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6485:   }
                   6486:   else  hstepm=estepm;   
                   6487:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6488:    * This is mainly to measure the difference between two models: for example
                   6489:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6490:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6491:    * progression in between and thus overestimating or underestimating according
                   6492:    * to the curvature of the survival function. If, for the same date, we 
                   6493:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6494:    * to compare the new estimate of Life expectancy with the same linear 
                   6495:    * hypothesis. A more precise result, taking into account a more precise
                   6496:    * curvature will be obtained if estepm is as small as stepm. */
                   6497: 
                   6498:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6499:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6500:      nhstepm is the number of hstepm from age to agelim 
                   6501:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  6502:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  6503:      and note for a fixed period like estepm months */
                   6504:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6505:      survival function given by stepm (the optimization length). Unfortunately it
                   6506:      means that if the survival funtion is printed only each two years of age and if
                   6507:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6508:      results. So we changed our mind and took the option of the best precision.
                   6509:   */
                   6510:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6511: 
                   6512:   agelim=AGESUP;
                   6513:   /* If stepm=6 months */
                   6514:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   6515:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   6516:     
                   6517: /* nhstepm age range expressed in number of stepm */
                   6518:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6519:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6520:   /* if (stepm >= YEARM) hstepm=1;*/
                   6521:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6522:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6523: 
                   6524:   for (age=bage; age<=fage; age ++){ 
                   6525:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6526:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6527:     /* if (stepm >= YEARM) hstepm=1;*/
                   6528:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   6529: 
                   6530:     /* If stepm=6 months */
                   6531:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6532:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
1.330     brouard  6533:     /* 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  6534:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  6535:     
                   6536:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6537:     
                   6538:     printf("%d|",(int)age);fflush(stdout);
                   6539:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6540:     
                   6541:     /* Computing expectancies */
                   6542:     for(i=1; i<=nlstate;i++)
                   6543:       for(j=1; j<=nlstate;j++)
                   6544:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6545:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   6546:          
                   6547:          /* 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]);*/
                   6548: 
                   6549:        }
                   6550: 
                   6551:     fprintf(ficreseij,"%3.0f",age );
                   6552:     for(i=1; i<=nlstate;i++){
                   6553:       eip=0;
                   6554:       for(j=1; j<=nlstate;j++){
                   6555:        eip +=eij[i][j][(int)age];
                   6556:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   6557:       }
                   6558:       fprintf(ficreseij,"%9.4f", eip );
                   6559:     }
                   6560:     fprintf(ficreseij,"\n");
                   6561:     
                   6562:   }
                   6563:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6564:   printf("\n");
                   6565:   fprintf(ficlog,"\n");
                   6566:   
                   6567: }
                   6568: 
1.235     brouard  6569:  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  6570: 
                   6571: {
                   6572:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  6573:      to initial status i, ei. .
1.126     brouard  6574:   */
1.336     brouard  6575:   /* Very time consuming function, but already optimized with precov */
1.126     brouard  6576:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   6577:   int nhstepma, nstepma; /* Decreasing with age */
                   6578:   double age, agelim, hf;
                   6579:   double ***p3matp, ***p3matm, ***varhe;
                   6580:   double **dnewm,**doldm;
                   6581:   double *xp, *xm;
                   6582:   double **gp, **gm;
                   6583:   double ***gradg, ***trgradg;
                   6584:   int theta;
                   6585: 
                   6586:   double eip, vip;
                   6587: 
                   6588:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   6589:   xp=vector(1,npar);
                   6590:   xm=vector(1,npar);
                   6591:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   6592:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   6593:   
                   6594:   pstamp(ficresstdeij);
                   6595:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   6596:   fprintf(ficresstdeij,"# Age");
                   6597:   for(i=1; i<=nlstate;i++){
                   6598:     for(j=1; j<=nlstate;j++)
                   6599:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   6600:     fprintf(ficresstdeij," e%1d. ",i);
                   6601:   }
                   6602:   fprintf(ficresstdeij,"\n");
                   6603: 
                   6604:   pstamp(ficrescveij);
                   6605:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   6606:   fprintf(ficrescveij,"# Age");
                   6607:   for(i=1; i<=nlstate;i++)
                   6608:     for(j=1; j<=nlstate;j++){
                   6609:       cptj= (j-1)*nlstate+i;
                   6610:       for(i2=1; i2<=nlstate;i2++)
                   6611:        for(j2=1; j2<=nlstate;j2++){
                   6612:          cptj2= (j2-1)*nlstate+i2;
                   6613:          if(cptj2 <= cptj)
                   6614:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   6615:        }
                   6616:     }
                   6617:   fprintf(ficrescveij,"\n");
                   6618:   
                   6619:   if(estepm < stepm){
                   6620:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6621:   }
                   6622:   else  hstepm=estepm;   
                   6623:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6624:    * This is mainly to measure the difference between two models: for example
                   6625:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6626:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6627:    * progression in between and thus overestimating or underestimating according
                   6628:    * to the curvature of the survival function. If, for the same date, we 
                   6629:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6630:    * to compare the new estimate of Life expectancy with the same linear 
                   6631:    * hypothesis. A more precise result, taking into account a more precise
                   6632:    * curvature will be obtained if estepm is as small as stepm. */
                   6633: 
                   6634:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6635:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6636:      nhstepm is the number of hstepm from age to agelim 
                   6637:      nstepm is the number of stepm from age to agelin. 
                   6638:      Look at hpijx to understand the reason of that which relies in memory size
                   6639:      and note for a fixed period like estepm months */
                   6640:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6641:      survival function given by stepm (the optimization length). Unfortunately it
                   6642:      means that if the survival funtion is printed only each two years of age and if
                   6643:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6644:      results. So we changed our mind and took the option of the best precision.
                   6645:   */
                   6646:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6647: 
                   6648:   /* If stepm=6 months */
                   6649:   /* nhstepm age range expressed in number of stepm */
                   6650:   agelim=AGESUP;
                   6651:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   6652:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6653:   /* if (stepm >= YEARM) hstepm=1;*/
                   6654:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6655:   
                   6656:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6657:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6658:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   6659:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   6660:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   6661:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   6662: 
                   6663:   for (age=bage; age<=fage; age ++){ 
                   6664:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6665:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6666:     /* if (stepm >= YEARM) hstepm=1;*/
                   6667:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  6668:                
1.126     brouard  6669:     /* If stepm=6 months */
                   6670:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6671:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   6672:     
                   6673:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  6674:                
1.126     brouard  6675:     /* Computing  Variances of health expectancies */
                   6676:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   6677:        decrease memory allocation */
                   6678:     for(theta=1; theta <=npar; theta++){
                   6679:       for(i=1; i<=npar; i++){ 
1.222     brouard  6680:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6681:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  6682:       }
1.235     brouard  6683:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   6684:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  6685:                        
1.126     brouard  6686:       for(j=1; j<= nlstate; j++){
1.222     brouard  6687:        for(i=1; i<=nlstate; i++){
                   6688:          for(h=0; h<=nhstepm-1; h++){
                   6689:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   6690:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   6691:          }
                   6692:        }
1.126     brouard  6693:       }
1.218     brouard  6694:                        
1.126     brouard  6695:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  6696:        for(h=0; h<=nhstepm-1; h++){
                   6697:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   6698:        }
1.126     brouard  6699:     }/* End theta */
                   6700:     
                   6701:     
                   6702:     for(h=0; h<=nhstepm-1; h++)
                   6703:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  6704:        for(theta=1; theta <=npar; theta++)
                   6705:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  6706:     
1.218     brouard  6707:                
1.222     brouard  6708:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  6709:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  6710:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  6711:                
1.222     brouard  6712:     printf("%d|",(int)age);fflush(stdout);
                   6713:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6714:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  6715:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  6716:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   6717:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   6718:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   6719:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   6720:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  6721:       }
                   6722:     }
1.320     brouard  6723:     /* if((int)age ==50){ */
                   6724:     /*   printf(" age=%d cij=%d nres=%d varhe[%d][%d]=%f ",(int)age, cij, nres, 1,2,varhe[1][2]); */
                   6725:     /* } */
1.126     brouard  6726:     /* Computing expectancies */
1.235     brouard  6727:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  6728:     for(i=1; i<=nlstate;i++)
                   6729:       for(j=1; j<=nlstate;j++)
1.222     brouard  6730:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6731:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  6732:                                        
1.222     brouard  6733:          /* 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  6734:                                        
1.222     brouard  6735:        }
1.269     brouard  6736: 
                   6737:     /* Standard deviation of expectancies ij */                
1.126     brouard  6738:     fprintf(ficresstdeij,"%3.0f",age );
                   6739:     for(i=1; i<=nlstate;i++){
                   6740:       eip=0.;
                   6741:       vip=0.;
                   6742:       for(j=1; j<=nlstate;j++){
1.222     brouard  6743:        eip += eij[i][j][(int)age];
                   6744:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   6745:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   6746:        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  6747:       }
                   6748:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   6749:     }
                   6750:     fprintf(ficresstdeij,"\n");
1.218     brouard  6751:                
1.269     brouard  6752:     /* Variance of expectancies ij */          
1.126     brouard  6753:     fprintf(ficrescveij,"%3.0f",age );
                   6754:     for(i=1; i<=nlstate;i++)
                   6755:       for(j=1; j<=nlstate;j++){
1.222     brouard  6756:        cptj= (j-1)*nlstate+i;
                   6757:        for(i2=1; i2<=nlstate;i2++)
                   6758:          for(j2=1; j2<=nlstate;j2++){
                   6759:            cptj2= (j2-1)*nlstate+i2;
                   6760:            if(cptj2 <= cptj)
                   6761:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   6762:          }
1.126     brouard  6763:       }
                   6764:     fprintf(ficrescveij,"\n");
1.218     brouard  6765:                
1.126     brouard  6766:   }
                   6767:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   6768:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   6769:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   6770:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   6771:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6772:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6773:   printf("\n");
                   6774:   fprintf(ficlog,"\n");
1.218     brouard  6775:        
1.126     brouard  6776:   free_vector(xm,1,npar);
                   6777:   free_vector(xp,1,npar);
                   6778:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   6779:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   6780:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   6781: }
1.218     brouard  6782:  
1.126     brouard  6783: /************ Variance ******************/
1.235     brouard  6784:  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  6785:  {
1.279     brouard  6786:    /** Variance of health expectancies 
                   6787:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   6788:     * double **newm;
                   6789:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   6790:     */
1.218     brouard  6791:   
                   6792:    /* int movingaverage(); */
                   6793:    double **dnewm,**doldm;
                   6794:    double **dnewmp,**doldmp;
                   6795:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  6796:    int first=0;
1.218     brouard  6797:    int k;
                   6798:    double *xp;
1.279     brouard  6799:    double **gp, **gm;  /**< for var eij */
                   6800:    double ***gradg, ***trgradg; /**< for var eij */
                   6801:    double **gradgp, **trgradgp; /**< for var p point j */
                   6802:    double *gpp, *gmp; /**< for var p point j */
                   6803:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
1.218     brouard  6804:    double ***p3mat;
                   6805:    double age,agelim, hf;
                   6806:    /* double ***mobaverage; */
                   6807:    int theta;
                   6808:    char digit[4];
                   6809:    char digitp[25];
                   6810: 
                   6811:    char fileresprobmorprev[FILENAMELENGTH];
                   6812: 
                   6813:    if(popbased==1){
                   6814:      if(mobilav!=0)
                   6815:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   6816:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   6817:    }
                   6818:    else 
                   6819:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  6820: 
1.218     brouard  6821:    /* if (mobilav!=0) { */
                   6822:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6823:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   6824:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   6825:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   6826:    /*   } */
                   6827:    /* } */
                   6828: 
                   6829:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   6830:    sprintf(digit,"%-d",ij);
                   6831:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   6832:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   6833:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   6834:    strcat(fileresprobmorprev,fileresu);
                   6835:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   6836:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   6837:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   6838:    }
                   6839:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6840:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6841:    pstamp(ficresprobmorprev);
                   6842:    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  6843:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
1.337     brouard  6844: 
                   6845:    /* We use TinvDoQresult[nres][resultmodel[nres][j] we sort according to the equation model and the resultline: it is a choice */
                   6846:    /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ /\* To be done*\/ */
                   6847:    /*   fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   6848:    /* } */
                   6849:    for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */ /* To be done*/
1.344     brouard  6850:      /* fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); */
1.337     brouard  6851:      fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  6852:    }
1.337     brouard  6853:    /* for(j=1;j<=cptcoveff;j++)  */
                   6854:    /*   fprintf(ficresprobmorprev," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,TnsdVar[Tvaraff[j]])]); */
1.238     brouard  6855:    fprintf(ficresprobmorprev,"\n");
                   6856: 
1.218     brouard  6857:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   6858:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6859:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   6860:      for(i=1; i<=nlstate;i++)
                   6861:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   6862:    }  
                   6863:    fprintf(ficresprobmorprev,"\n");
                   6864:   
                   6865:    fprintf(ficgp,"\n# Routine varevsij");
                   6866:    fprintf(ficgp,"\nunset title \n");
                   6867:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   6868:    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");
                   6869:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  6870: 
1.218     brouard  6871:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6872:    pstamp(ficresvij);
                   6873:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   6874:    if(popbased==1)
                   6875:      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);
                   6876:    else
                   6877:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   6878:    fprintf(ficresvij,"# Age");
                   6879:    for(i=1; i<=nlstate;i++)
                   6880:      for(j=1; j<=nlstate;j++)
                   6881:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   6882:    fprintf(ficresvij,"\n");
                   6883: 
                   6884:    xp=vector(1,npar);
                   6885:    dnewm=matrix(1,nlstate,1,npar);
                   6886:    doldm=matrix(1,nlstate,1,nlstate);
                   6887:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   6888:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6889: 
                   6890:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   6891:    gpp=vector(nlstate+1,nlstate+ndeath);
                   6892:    gmp=vector(nlstate+1,nlstate+ndeath);
                   6893:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  6894:   
1.218     brouard  6895:    if(estepm < stepm){
                   6896:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   6897:    }
                   6898:    else  hstepm=estepm;   
                   6899:    /* For example we decided to compute the life expectancy with the smallest unit */
                   6900:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6901:       nhstepm is the number of hstepm from age to agelim 
                   6902:       nstepm is the number of stepm from age to agelim. 
                   6903:       Look at function hpijx to understand why because of memory size limitations, 
                   6904:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   6905:       survival function given by stepm (the optimization length). Unfortunately it
                   6906:       means that if the survival funtion is printed every two years of age and if
                   6907:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6908:       results. So we changed our mind and took the option of the best precision.
                   6909:    */
                   6910:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6911:    agelim = AGESUP;
                   6912:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6913:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6914:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6915:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6916:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   6917:      gp=matrix(0,nhstepm,1,nlstate);
                   6918:      gm=matrix(0,nhstepm,1,nlstate);
                   6919:                
                   6920:                
                   6921:      for(theta=1; theta <=npar; theta++){
                   6922:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   6923:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6924:        }
1.279     brouard  6925:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   6926:        * returns into prlim .
1.288     brouard  6927:        */
1.242     brouard  6928:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  6929: 
                   6930:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  6931:        if (popbased==1) {
                   6932:         if(mobilav ==0){
                   6933:           for(i=1; i<=nlstate;i++)
                   6934:             prlim[i][i]=probs[(int)age][i][ij];
                   6935:         }else{ /* mobilav */ 
                   6936:           for(i=1; i<=nlstate;i++)
                   6937:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6938:         }
                   6939:        }
1.295     brouard  6940:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  6941:        */                      
                   6942:        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  6943:        /**< 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  6944:        * at horizon h in state j including mortality.
                   6945:        */
1.218     brouard  6946:        for(j=1; j<= nlstate; j++){
                   6947:         for(h=0; h<=nhstepm; h++){
                   6948:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   6949:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6950:         }
                   6951:        }
1.279     brouard  6952:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  6953:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  6954:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  6955:        */
                   6956:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6957:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   6958:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  6959:        }
                   6960:        
                   6961:        /* Again with minus shift */
1.218     brouard  6962:                        
                   6963:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   6964:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6965: 
1.242     brouard  6966:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  6967:                        
                   6968:        if (popbased==1) {
                   6969:         if(mobilav ==0){
                   6970:           for(i=1; i<=nlstate;i++)
                   6971:             prlim[i][i]=probs[(int)age][i][ij];
                   6972:         }else{ /* mobilav */ 
                   6973:           for(i=1; i<=nlstate;i++)
                   6974:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6975:         }
                   6976:        }
                   6977:                        
1.235     brouard  6978:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  6979:                        
                   6980:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   6981:         for(h=0; h<=nhstepm; h++){
                   6982:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   6983:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6984:         }
                   6985:        }
                   6986:        /* This for computing probability of death (h=1 means
                   6987:          computed over hstepm matrices product = hstepm*stepm months) 
                   6988:          as a weighted average of prlim.
                   6989:        */
                   6990:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6991:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   6992:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   6993:        }    
1.279     brouard  6994:        /* end shifting computations */
                   6995: 
                   6996:        /**< Computing gradient matrix at horizon h 
                   6997:        */
1.218     brouard  6998:        for(j=1; j<= nlstate; j++) /* vareij */
                   6999:         for(h=0; h<=nhstepm; h++){
                   7000:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   7001:         }
1.279     brouard  7002:        /**< Gradient of overall mortality p.3 (or p.j) 
                   7003:        */
                   7004:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
1.218     brouard  7005:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   7006:        }
                   7007:                        
                   7008:      } /* End theta */
1.279     brouard  7009:      
                   7010:      /* We got the gradient matrix for each theta and state j */               
1.218     brouard  7011:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   7012:                
                   7013:      for(h=0; h<=nhstepm; h++) /* veij */
                   7014:        for(j=1; j<=nlstate;j++)
                   7015:         for(theta=1; theta <=npar; theta++)
                   7016:           trgradg[h][j][theta]=gradg[h][theta][j];
                   7017:                
                   7018:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   7019:        for(theta=1; theta <=npar; theta++)
                   7020:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  7021:      /**< as well as its transposed matrix 
                   7022:       */               
1.218     brouard  7023:                
                   7024:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   7025:      for(i=1;i<=nlstate;i++)
                   7026:        for(j=1;j<=nlstate;j++)
                   7027:         vareij[i][j][(int)age] =0.;
1.279     brouard  7028: 
                   7029:      /* Computing trgradg by matcov by gradg at age and summing over h
                   7030:       * and k (nhstepm) formula 15 of article
                   7031:       * Lievre-Brouard-Heathcote
                   7032:       */
                   7033:      
1.218     brouard  7034:      for(h=0;h<=nhstepm;h++){
                   7035:        for(k=0;k<=nhstepm;k++){
                   7036:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   7037:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   7038:         for(i=1;i<=nlstate;i++)
                   7039:           for(j=1;j<=nlstate;j++)
                   7040:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   7041:        }
                   7042:      }
                   7043:                
1.279     brouard  7044:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
                   7045:       * p.j overall mortality formula 49 but computed directly because
                   7046:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   7047:       * wix is independent of theta.
                   7048:       */
1.218     brouard  7049:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   7050:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   7051:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   7052:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   7053:         varppt[j][i]=doldmp[j][i];
                   7054:      /* end ppptj */
                   7055:      /*  x centered again */
                   7056:                
1.242     brouard  7057:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  7058:                
                   7059:      if (popbased==1) {
                   7060:        if(mobilav ==0){
                   7061:         for(i=1; i<=nlstate;i++)
                   7062:           prlim[i][i]=probs[(int)age][i][ij];
                   7063:        }else{ /* mobilav */ 
                   7064:         for(i=1; i<=nlstate;i++)
                   7065:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   7066:        }
                   7067:      }
                   7068:                
                   7069:      /* This for computing probability of death (h=1 means
                   7070:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   7071:        as a weighted average of prlim.
                   7072:      */
1.235     brouard  7073:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  7074:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   7075:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   7076:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   7077:      }    
                   7078:      /* end probability of death */
                   7079:                
                   7080:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   7081:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   7082:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   7083:        for(i=1; i<=nlstate;i++){
                   7084:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   7085:        }
                   7086:      } 
                   7087:      fprintf(ficresprobmorprev,"\n");
                   7088:                
                   7089:      fprintf(ficresvij,"%.0f ",age );
                   7090:      for(i=1; i<=nlstate;i++)
                   7091:        for(j=1; j<=nlstate;j++){
                   7092:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   7093:        }
                   7094:      fprintf(ficresvij,"\n");
                   7095:      free_matrix(gp,0,nhstepm,1,nlstate);
                   7096:      free_matrix(gm,0,nhstepm,1,nlstate);
                   7097:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   7098:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   7099:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7100:    } /* End age */
                   7101:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   7102:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   7103:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   7104:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   7105:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   7106:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   7107:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   7108:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   7109:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   7110:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   7111:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   7112:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   7113:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   7114:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   7115:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   7116:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   7117:    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);
                   7118:    /*  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  7119:     */
1.218     brouard  7120:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   7121:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  7122: 
1.218     brouard  7123:    free_vector(xp,1,npar);
                   7124:    free_matrix(doldm,1,nlstate,1,nlstate);
                   7125:    free_matrix(dnewm,1,nlstate,1,npar);
                   7126:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7127:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   7128:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7129:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7130:    fclose(ficresprobmorprev);
                   7131:    fflush(ficgp);
                   7132:    fflush(fichtm); 
                   7133:  }  /* end varevsij */
1.126     brouard  7134: 
                   7135: /************ Variance of prevlim ******************/
1.269     brouard  7136:  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  7137: {
1.205     brouard  7138:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  7139:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  7140: 
1.268     brouard  7141:   double **dnewmpar,**doldm;
1.126     brouard  7142:   int i, j, nhstepm, hstepm;
                   7143:   double *xp;
                   7144:   double *gp, *gm;
                   7145:   double **gradg, **trgradg;
1.208     brouard  7146:   double **mgm, **mgp;
1.126     brouard  7147:   double age,agelim;
                   7148:   int theta;
                   7149:   
                   7150:   pstamp(ficresvpl);
1.288     brouard  7151:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  7152:   fprintf(ficresvpl,"# Age ");
                   7153:   if(nresult >=1)
                   7154:     fprintf(ficresvpl," Result# ");
1.126     brouard  7155:   for(i=1; i<=nlstate;i++)
                   7156:       fprintf(ficresvpl," %1d-%1d",i,i);
                   7157:   fprintf(ficresvpl,"\n");
                   7158: 
                   7159:   xp=vector(1,npar);
1.268     brouard  7160:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  7161:   doldm=matrix(1,nlstate,1,nlstate);
                   7162:   
                   7163:   hstepm=1*YEARM; /* Every year of age */
                   7164:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   7165:   agelim = AGESUP;
                   7166:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   7167:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7168:     if (stepm >= YEARM) hstepm=1;
                   7169:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7170:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  7171:     mgp=matrix(1,npar,1,nlstate);
                   7172:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  7173:     gp=vector(1,nlstate);
                   7174:     gm=vector(1,nlstate);
                   7175: 
                   7176:     for(theta=1; theta <=npar; theta++){
                   7177:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   7178:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7179:       }
1.288     brouard  7180:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   7181:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   7182:       /* else */
                   7183:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  7184:       for(i=1;i<=nlstate;i++){
1.126     brouard  7185:        gp[i] = prlim[i][i];
1.208     brouard  7186:        mgp[theta][i] = prlim[i][i];
                   7187:       }
1.126     brouard  7188:       for(i=1; i<=npar; i++) /* Computes gradient */
                   7189:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  7190:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   7191:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   7192:       /* else */
                   7193:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  7194:       for(i=1;i<=nlstate;i++){
1.126     brouard  7195:        gm[i] = prlim[i][i];
1.208     brouard  7196:        mgm[theta][i] = prlim[i][i];
                   7197:       }
1.126     brouard  7198:       for(i=1;i<=nlstate;i++)
                   7199:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  7200:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  7201:     } /* End theta */
                   7202: 
                   7203:     trgradg =matrix(1,nlstate,1,npar);
                   7204: 
                   7205:     for(j=1; j<=nlstate;j++)
                   7206:       for(theta=1; theta <=npar; theta++)
                   7207:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  7208:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7209:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7210:     /*   for(j=1; j<=nlstate;j++){ */
                   7211:     /*         printf(" %d ",j); */
                   7212:     /*         for(theta=1; theta <=npar; theta++) */
                   7213:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7214:     /*         printf("\n "); */
                   7215:     /*   } */
                   7216:     /* } */
                   7217:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7218:     /*   printf("\n gradg %d ",(int)age); */
                   7219:     /*   for(j=1; j<=nlstate;j++){ */
                   7220:     /*         printf("%d ",j); */
                   7221:     /*         for(theta=1; theta <=npar; theta++) */
                   7222:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7223:     /*         printf("\n "); */
                   7224:     /*   } */
                   7225:     /* } */
1.126     brouard  7226: 
                   7227:     for(i=1;i<=nlstate;i++)
                   7228:       varpl[i][(int)age] =0.;
1.209     brouard  7229:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  7230:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7231:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  7232:     }else{
1.268     brouard  7233:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7234:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  7235:     }
1.126     brouard  7236:     for(i=1;i<=nlstate;i++)
                   7237:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7238: 
                   7239:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  7240:     if(nresult >=1)
                   7241:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  7242:     for(i=1; i<=nlstate;i++){
1.126     brouard  7243:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  7244:       /* for(j=1;j<=nlstate;j++) */
                   7245:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   7246:     }
1.126     brouard  7247:     fprintf(ficresvpl,"\n");
                   7248:     free_vector(gp,1,nlstate);
                   7249:     free_vector(gm,1,nlstate);
1.208     brouard  7250:     free_matrix(mgm,1,npar,1,nlstate);
                   7251:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  7252:     free_matrix(gradg,1,npar,1,nlstate);
                   7253:     free_matrix(trgradg,1,nlstate,1,npar);
                   7254:   } /* End age */
                   7255: 
                   7256:   free_vector(xp,1,npar);
                   7257:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  7258:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   7259: 
                   7260: }
                   7261: 
                   7262: 
                   7263: /************ Variance of backprevalence limit ******************/
1.269     brouard  7264:  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  7265: {
                   7266:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   7267:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   7268: 
                   7269:   double **dnewmpar,**doldm;
                   7270:   int i, j, nhstepm, hstepm;
                   7271:   double *xp;
                   7272:   double *gp, *gm;
                   7273:   double **gradg, **trgradg;
                   7274:   double **mgm, **mgp;
                   7275:   double age,agelim;
                   7276:   int theta;
                   7277:   
                   7278:   pstamp(ficresvbl);
                   7279:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   7280:   fprintf(ficresvbl,"# Age ");
                   7281:   if(nresult >=1)
                   7282:     fprintf(ficresvbl," Result# ");
                   7283:   for(i=1; i<=nlstate;i++)
                   7284:       fprintf(ficresvbl," %1d-%1d",i,i);
                   7285:   fprintf(ficresvbl,"\n");
                   7286: 
                   7287:   xp=vector(1,npar);
                   7288:   dnewmpar=matrix(1,nlstate,1,npar);
                   7289:   doldm=matrix(1,nlstate,1,nlstate);
                   7290:   
                   7291:   hstepm=1*YEARM; /* Every year of age */
                   7292:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   7293:   agelim = AGEINF;
                   7294:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   7295:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7296:     if (stepm >= YEARM) hstepm=1;
                   7297:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7298:     gradg=matrix(1,npar,1,nlstate);
                   7299:     mgp=matrix(1,npar,1,nlstate);
                   7300:     mgm=matrix(1,npar,1,nlstate);
                   7301:     gp=vector(1,nlstate);
                   7302:     gm=vector(1,nlstate);
                   7303: 
                   7304:     for(theta=1; theta <=npar; theta++){
                   7305:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   7306:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7307:       }
                   7308:       if(mobilavproj > 0 )
                   7309:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7310:       else
                   7311:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7312:       for(i=1;i<=nlstate;i++){
                   7313:        gp[i] = bprlim[i][i];
                   7314:        mgp[theta][i] = bprlim[i][i];
                   7315:       }
                   7316:      for(i=1; i<=npar; i++) /* Computes gradient */
                   7317:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   7318:        if(mobilavproj > 0 )
                   7319:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7320:        else
                   7321:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7322:       for(i=1;i<=nlstate;i++){
                   7323:        gm[i] = bprlim[i][i];
                   7324:        mgm[theta][i] = bprlim[i][i];
                   7325:       }
                   7326:       for(i=1;i<=nlstate;i++)
                   7327:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   7328:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   7329:     } /* End theta */
                   7330: 
                   7331:     trgradg =matrix(1,nlstate,1,npar);
                   7332: 
                   7333:     for(j=1; j<=nlstate;j++)
                   7334:       for(theta=1; theta <=npar; theta++)
                   7335:        trgradg[j][theta]=gradg[theta][j];
                   7336:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7337:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7338:     /*   for(j=1; j<=nlstate;j++){ */
                   7339:     /*         printf(" %d ",j); */
                   7340:     /*         for(theta=1; theta <=npar; theta++) */
                   7341:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7342:     /*         printf("\n "); */
                   7343:     /*   } */
                   7344:     /* } */
                   7345:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7346:     /*   printf("\n gradg %d ",(int)age); */
                   7347:     /*   for(j=1; j<=nlstate;j++){ */
                   7348:     /*         printf("%d ",j); */
                   7349:     /*         for(theta=1; theta <=npar; theta++) */
                   7350:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7351:     /*         printf("\n "); */
                   7352:     /*   } */
                   7353:     /* } */
                   7354: 
                   7355:     for(i=1;i<=nlstate;i++)
                   7356:       varbpl[i][(int)age] =0.;
                   7357:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   7358:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7359:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7360:     }else{
                   7361:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7362:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7363:     }
                   7364:     for(i=1;i<=nlstate;i++)
                   7365:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7366: 
                   7367:     fprintf(ficresvbl,"%.0f ",age );
                   7368:     if(nresult >=1)
                   7369:       fprintf(ficresvbl,"%d ",nres );
                   7370:     for(i=1; i<=nlstate;i++)
                   7371:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   7372:     fprintf(ficresvbl,"\n");
                   7373:     free_vector(gp,1,nlstate);
                   7374:     free_vector(gm,1,nlstate);
                   7375:     free_matrix(mgm,1,npar,1,nlstate);
                   7376:     free_matrix(mgp,1,npar,1,nlstate);
                   7377:     free_matrix(gradg,1,npar,1,nlstate);
                   7378:     free_matrix(trgradg,1,nlstate,1,npar);
                   7379:   } /* End age */
                   7380: 
                   7381:   free_vector(xp,1,npar);
                   7382:   free_matrix(doldm,1,nlstate,1,npar);
                   7383:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  7384: 
                   7385: }
                   7386: 
                   7387: /************ Variance of one-step probabilities  ******************/
                   7388: 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  7389:  {
                   7390:    int i, j=0,  k1, l1, tj;
                   7391:    int k2, l2, j1,  z1;
                   7392:    int k=0, l;
                   7393:    int first=1, first1, first2;
1.326     brouard  7394:    int nres=0; /* New */
1.222     brouard  7395:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   7396:    double **dnewm,**doldm;
                   7397:    double *xp;
                   7398:    double *gp, *gm;
                   7399:    double **gradg, **trgradg;
                   7400:    double **mu;
                   7401:    double age, cov[NCOVMAX+1];
                   7402:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   7403:    int theta;
                   7404:    char fileresprob[FILENAMELENGTH];
                   7405:    char fileresprobcov[FILENAMELENGTH];
                   7406:    char fileresprobcor[FILENAMELENGTH];
                   7407:    double ***varpij;
                   7408: 
                   7409:    strcpy(fileresprob,"PROB_"); 
                   7410:    strcat(fileresprob,fileres);
                   7411:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   7412:      printf("Problem with resultfile: %s\n", fileresprob);
                   7413:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   7414:    }
                   7415:    strcpy(fileresprobcov,"PROBCOV_"); 
                   7416:    strcat(fileresprobcov,fileresu);
                   7417:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   7418:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   7419:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   7420:    }
                   7421:    strcpy(fileresprobcor,"PROBCOR_"); 
                   7422:    strcat(fileresprobcor,fileresu);
                   7423:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   7424:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   7425:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   7426:    }
                   7427:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7428:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7429:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7430:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7431:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7432:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7433:    pstamp(ficresprob);
                   7434:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   7435:    fprintf(ficresprob,"# Age");
                   7436:    pstamp(ficresprobcov);
                   7437:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   7438:    fprintf(ficresprobcov,"# Age");
                   7439:    pstamp(ficresprobcor);
                   7440:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   7441:    fprintf(ficresprobcor,"# Age");
1.126     brouard  7442: 
                   7443: 
1.222     brouard  7444:    for(i=1; i<=nlstate;i++)
                   7445:      for(j=1; j<=(nlstate+ndeath);j++){
                   7446:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   7447:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   7448:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   7449:      }  
                   7450:    /* fprintf(ficresprob,"\n");
                   7451:       fprintf(ficresprobcov,"\n");
                   7452:       fprintf(ficresprobcor,"\n");
                   7453:    */
                   7454:    xp=vector(1,npar);
                   7455:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7456:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7457:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   7458:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   7459:    first=1;
                   7460:    fprintf(ficgp,"\n# Routine varprob");
                   7461:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   7462:    fprintf(fichtm,"\n");
                   7463: 
1.288     brouard  7464:    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  7465:    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);
                   7466:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  7467: and drawn. It helps understanding how is the covariance between two incidences.\
                   7468:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  7469:    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  7470: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   7471: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   7472: standard deviations wide on each axis. <br>\
                   7473:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   7474:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   7475: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   7476: 
1.222     brouard  7477:    cov[1]=1;
                   7478:    /* tj=cptcoveff; */
1.225     brouard  7479:    tj = (int) pow(2,cptcoveff);
1.222     brouard  7480:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   7481:    j1=0;
1.332     brouard  7482: 
                   7483:    for(nres=1;nres <=nresult; nres++){ /* For each resultline */
                   7484:    for(j1=1; j1<=tj;j1++){ /* For any combination of dummy covariates, fixed and varying */
1.342     brouard  7485:      /* 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  7486:      if(tj != 1 && TKresult[nres]!= j1)
                   7487:        continue;
                   7488: 
                   7489:    /* for(j1=1; j1<=tj;j1++){  /\* For each valid combination of covariates or only once*\/ */
                   7490:      /* for(nres=1;nres <=1; nres++){ /\* For each resultline *\/ */
                   7491:      /* /\* for(nres=1;nres <=nresult; nres++){ /\\* For each resultline *\\/ *\/ */
1.222     brouard  7492:      if  (cptcovn>0) {
1.334     brouard  7493:        fprintf(ficresprob, "\n#********** Variable ");
                   7494:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   7495:        fprintf(ficgp, "\n#********** Variable ");
                   7496:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   7497:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   7498: 
                   7499:        /* Including quantitative variables of the resultline to be done */
                   7500:        for (z1=1; z1<=cptcovs; z1++){ /* Loop on each variable of this resultline  */
1.343     brouard  7501:         /* printf("Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model); */
1.338     brouard  7502:         fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model);
                   7503:         /* 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  7504:         if(Dummy[modelresult[nres][z1]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to z1 in resultline  */
                   7505:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed referenced to model equation */
                   7506:             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  */
                   7507:             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  */
                   7508:             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  */
                   7509:             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  */
                   7510:             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  */
                   7511:             fprintf(ficresprob,"fixed ");
                   7512:             fprintf(ficresprobcov,"fixed ");
                   7513:             fprintf(ficgp,"fixed ");
                   7514:             fprintf(fichtmcov,"fixed ");
                   7515:             fprintf(ficresprobcor,"fixed ");
                   7516:           }else{
                   7517:             fprintf(ficresprob,"varyi ");
                   7518:             fprintf(ficresprobcov,"varyi ");
                   7519:             fprintf(ficgp,"varyi ");
                   7520:             fprintf(fichtmcov,"varyi ");
                   7521:             fprintf(ficresprobcor,"varyi ");
                   7522:           }
                   7523:         }else if(Dummy[modelresult[nres][z1]]==1){ /* Quanti variable */
                   7524:           /* For each selected (single) quantitative value */
1.337     brouard  7525:           fprintf(ficresprob," V%d=%lg ",Tvqresult[nres][z1],Tqresult[nres][z1]);
1.334     brouard  7526:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed */
                   7527:             fprintf(ficresprob,"fixed ");
                   7528:             fprintf(ficresprobcov,"fixed ");
                   7529:             fprintf(ficgp,"fixed ");
                   7530:             fprintf(fichtmcov,"fixed ");
                   7531:             fprintf(ficresprobcor,"fixed ");
                   7532:           }else{
                   7533:             fprintf(ficresprob,"varyi ");
                   7534:             fprintf(ficresprobcov,"varyi ");
                   7535:             fprintf(ficgp,"varyi ");
                   7536:             fprintf(fichtmcov,"varyi ");
                   7537:             fprintf(ficresprobcor,"varyi ");
                   7538:           }
                   7539:         }else{
                   7540:           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 */
                   7541:           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 */
                   7542:           exit(1);
                   7543:         }
                   7544:        } /* End loop on variable of this resultline */
                   7545:        /* for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]); */
1.222     brouard  7546:        fprintf(ficresprob, "**********\n#\n");
                   7547:        fprintf(ficresprobcov, "**********\n#\n");
                   7548:        fprintf(ficgp, "**********\n#\n");
                   7549:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   7550:        fprintf(ficresprobcor, "**********\n#");    
                   7551:        if(invalidvarcomb[j1]){
                   7552:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   7553:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   7554:         continue;
                   7555:        }
                   7556:      }
                   7557:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   7558:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7559:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   7560:      gm=vector(1,(nlstate)*(nlstate+ndeath));
1.334     brouard  7561:      for (age=bage; age<=fage; age ++){ /* Fo each age we feed the model equation with covariates, using precov as in hpxij() ? */
1.222     brouard  7562:        cov[2]=age;
                   7563:        if(nagesqr==1)
                   7564:         cov[3]= age*age;
1.334     brouard  7565:        /* New code end of combination but for each resultline */
                   7566:        for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   7567:         if(Typevar[k1]==1){ /* A product with age */
                   7568:           cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.326     brouard  7569:         }else{
1.334     brouard  7570:           cov[2+nagesqr+k1]=precov[nres][k1];
1.326     brouard  7571:         }
1.334     brouard  7572:        }/* End of loop on model equation */
                   7573: /* Old code */
                   7574:        /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   7575:        /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)]; *\/ */
                   7576:        /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   7577:        /*       /\* Here comes the value of the covariate 'j1' after renumbering k with single dummy covariates *\/ */
                   7578:        /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(j1,TnsdVar[TvarsD[k]])]; */
                   7579:        /*       /\*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*\//\* j1 1 2 3 4 */
                   7580:        /*                                                                  * 1  1 1 1 1 */
                   7581:        /*                                                                  * 2  2 1 1 1 */
                   7582:        /*                                                                  * 3  1 2 1 1 */
                   7583:        /*                                                                  *\/ */
                   7584:        /*       /\* nbcode[1][1]=0 nbcode[1][2]=1;*\/ */
                   7585:        /* } */
                   7586:        /* /\* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   7587:        /* /\* ) p nbcode[Tvar[Tage[k]]][(1 & (ij-1) >> (k-1))+1] *\/ */
                   7588:        /* /\*for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; *\/ */
                   7589:        /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   7590:        /*       if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   7591:        /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(j1,TnsdVar[Tvar[Tage[k]]])]*cov[2]; */
                   7592:        /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7593:        /*       } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   7594:        /*         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]); */
                   7595:        /*         /\* cov[2+nagesqr+Tage[k]]=meanq[k]/idq[k]*cov[2];/\\* Using the mean of quantitative variable Tvar[Tage[k]] /\\* Tqresult[nres][k]; *\\/ *\/ */
                   7596:        /*         /\* exit(1); *\/ */
                   7597:        /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   7598:        /*       } */
                   7599:        /*       /\* cov[2+Tage[k]+nagesqr]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7600:        /* } */
                   7601:        /* for (k=1; k<=cptcovprod;k++){/\* For product without age *\/ */
                   7602:        /*       if(Dummy[Tvard[k][1]]==0){ */
                   7603:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7604:        /*           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]])]; */
                   7605:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7606:        /*         }else{ /\* Should we use the mean of the quantitative variables? *\/ */
                   7607:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,TnsdVar[Tvard[k][1]])] * Tqresult[nres][resultmodel[nres][k]]; */
                   7608:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   7609:        /*         } */
                   7610:        /*       }else{ */
                   7611:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7612:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(j1,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][TnsdVar[Tvard[k][1]]]; */
                   7613:        /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   7614:        /*         }else{ */
                   7615:        /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][TnsdVar[Tvard[k][1]]]*  Tqinvresult[nres][TnsdVar[Tvard[k][2]]]; */
                   7616:        /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   7617:        /*         } */
                   7618:        /*       } */
                   7619:        /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7620:        /* } */                 
1.326     brouard  7621: /* For each age and combination of dummy covariates we slightly move the parameters of delti in order to get the gradient*/                    
1.222     brouard  7622:        for(theta=1; theta <=npar; theta++){
                   7623:         for(i=1; i<=npar; i++)
                   7624:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  7625:                                
1.222     brouard  7626:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  7627:                                
1.222     brouard  7628:         k=0;
                   7629:         for(i=1; i<= (nlstate); i++){
                   7630:           for(j=1; j<=(nlstate+ndeath);j++){
                   7631:             k=k+1;
                   7632:             gp[k]=pmmij[i][j];
                   7633:           }
                   7634:         }
1.220     brouard  7635:                                
1.222     brouard  7636:         for(i=1; i<=npar; i++)
                   7637:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  7638:                                
1.222     brouard  7639:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   7640:         k=0;
                   7641:         for(i=1; i<=(nlstate); i++){
                   7642:           for(j=1; j<=(nlstate+ndeath);j++){
                   7643:             k=k+1;
                   7644:             gm[k]=pmmij[i][j];
                   7645:           }
                   7646:         }
1.220     brouard  7647:                                
1.222     brouard  7648:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   7649:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   7650:        }
1.126     brouard  7651: 
1.222     brouard  7652:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   7653:         for(theta=1; theta <=npar; theta++)
                   7654:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  7655:                        
1.222     brouard  7656:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   7657:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  7658:                        
1.222     brouard  7659:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  7660:                        
1.222     brouard  7661:        k=0;
                   7662:        for(i=1; i<=(nlstate); i++){
                   7663:         for(j=1; j<=(nlstate+ndeath);j++){
                   7664:           k=k+1;
                   7665:           mu[k][(int) age]=pmmij[i][j];
                   7666:         }
                   7667:        }
                   7668:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   7669:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   7670:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  7671:                        
1.222     brouard  7672:        /*printf("\n%d ",(int)age);
                   7673:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7674:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7675:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7676:         }*/
1.220     brouard  7677:                        
1.222     brouard  7678:        fprintf(ficresprob,"\n%d ",(int)age);
                   7679:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   7680:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  7681:                        
1.222     brouard  7682:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   7683:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   7684:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7685:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   7686:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   7687:        }
                   7688:        i=0;
                   7689:        for (k=1; k<=(nlstate);k++){
                   7690:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   7691:           i++;
                   7692:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   7693:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   7694:           for (j=1; j<=i;j++){
                   7695:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   7696:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   7697:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   7698:           }
                   7699:         }
                   7700:        }/* end of loop for state */
                   7701:      } /* end of loop for age */
                   7702:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7703:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7704:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7705:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7706:     
                   7707:      /* Confidence intervalle of pij  */
                   7708:      /*
                   7709:        fprintf(ficgp,"\nunset parametric;unset label");
                   7710:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   7711:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   7712:        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);
                   7713:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   7714:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   7715:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   7716:      */
                   7717:                
                   7718:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   7719:      first1=1;first2=2;
                   7720:      for (k2=1; k2<=(nlstate);k2++){
                   7721:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   7722:         if(l2==k2) continue;
                   7723:         j=(k2-1)*(nlstate+ndeath)+l2;
                   7724:         for (k1=1; k1<=(nlstate);k1++){
                   7725:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   7726:             if(l1==k1) continue;
                   7727:             i=(k1-1)*(nlstate+ndeath)+l1;
                   7728:             if(i<=j) continue;
                   7729:             for (age=bage; age<=fage; age ++){ 
                   7730:               if ((int)age %5==0){
                   7731:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   7732:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7733:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7734:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   7735:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   7736:                 c12=cv12/sqrt(v1*v2);
                   7737:                 /* Computing eigen value of matrix of covariance */
                   7738:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7739:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7740:                 if ((lc2 <0) || (lc1 <0) ){
                   7741:                   if(first2==1){
                   7742:                     first1=0;
                   7743:                     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);
                   7744:                   }
                   7745:                   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);
                   7746:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   7747:                   /* lc2=fabs(lc2); */
                   7748:                 }
1.220     brouard  7749:                                                                
1.222     brouard  7750:                 /* Eigen vectors */
1.280     brouard  7751:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   7752:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7753:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7754:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   7755:                 }else
                   7756:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  7757:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   7758:                 v21=(lc1-v1)/cv12*v11;
                   7759:                 v12=-v21;
                   7760:                 v22=v11;
                   7761:                 tnalp=v21/v11;
                   7762:                 if(first1==1){
                   7763:                   first1=0;
                   7764:                   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);
                   7765:                 }
                   7766:                 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);
                   7767:                 /*printf(fignu*/
                   7768:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   7769:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   7770:                 if(first==1){
                   7771:                   first=0;
                   7772:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   7773:                   fprintf(ficgp,"\nset parametric;unset label");
                   7774:                   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);
                   7775:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  7776:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  7777:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  7778: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  7779:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   7780:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7781:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7782:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   7783:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7784:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7785:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7786:                   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  7787:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   7788:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  7789:                 }else{
                   7790:                   first=0;
                   7791:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   7792:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7793:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7794:                   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  7795:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   7796:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  7797:                 }/* if first */
                   7798:               } /* age mod 5 */
                   7799:             } /* end loop age */
                   7800:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7801:             first=1;
                   7802:           } /*l12 */
                   7803:         } /* k12 */
                   7804:        } /*l1 */
                   7805:      }/* k1 */
1.332     brouard  7806:    }  /* loop on combination of covariates j1 */
1.326     brouard  7807:    } /* loop on nres */
1.222     brouard  7808:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   7809:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   7810:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7811:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   7812:    free_vector(xp,1,npar);
                   7813:    fclose(ficresprob);
                   7814:    fclose(ficresprobcov);
                   7815:    fclose(ficresprobcor);
                   7816:    fflush(ficgp);
                   7817:    fflush(fichtmcov);
                   7818:  }
1.126     brouard  7819: 
                   7820: 
                   7821: /******************* Printing html file ***********/
1.201     brouard  7822: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  7823:                  int lastpass, int stepm, int weightopt, char model[],\
                   7824:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  7825:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   7826:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   7827:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.237     brouard  7828:   int jj1, k1, i1, cpt, k4, nres;
1.319     brouard  7829:   /* In fact some results are already printed in fichtm which is open */
1.126     brouard  7830:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   7831:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   7832: </ul>");
1.319     brouard  7833: /*    fprintf(fichtm,"<ul><li> model=1+age+%s\n \ */
                   7834: /* </ul>", model); */
1.214     brouard  7835:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   7836:    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",
                   7837:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
1.332     brouard  7838:    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  7839:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   7840:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  7841:    fprintf(fichtm,"\
                   7842:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  7843:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  7844:    fprintf(fichtm,"\
1.217     brouard  7845:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   7846:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   7847:    fprintf(fichtm,"\
1.288     brouard  7848:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7849:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  7850:    fprintf(fichtm,"\
1.288     brouard  7851:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  7852:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   7853:    fprintf(fichtm,"\
1.211     brouard  7854:  - (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  7855:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7856:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  7857:    if(prevfcast==1){
                   7858:      fprintf(fichtm,"\
                   7859:  - Prevalence projections by age and states:                           \
1.201     brouard  7860:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  7861:    }
1.126     brouard  7862: 
                   7863: 
1.225     brouard  7864:    m=pow(2,cptcoveff);
1.222     brouard  7865:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7866: 
1.317     brouard  7867:    fprintf(fichtm," \n<ul><li><b>Graphs (first order)</b></li><p>");
1.264     brouard  7868: 
                   7869:    jj1=0;
                   7870: 
                   7871:    fprintf(fichtm," \n<ul>");
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 no result */
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.264     brouard  7879:      jj1++;
                   7880:      if (cptcovn > 0) {
                   7881:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
1.337     brouard  7882:        for (cpt=1; cpt<=cptcovs;cpt++){ /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   7883:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  7884:        }
1.337     brouard  7885:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   7886:        /*       fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   7887:        /* } */
                   7888:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   7889:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   7890:        /* } */
1.264     brouard  7891:        fprintf(fichtm,"\">");
                   7892:        
                   7893:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   7894:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  7895:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   7896:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  7897:        }
1.337     brouard  7898:        /* fprintf(fichtm,"************ Results for covariates"); */
                   7899:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   7900:        /*       fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   7901:        /* } */
                   7902:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   7903:        /*       fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   7904:        /* } */
1.264     brouard  7905:        if(invalidvarcomb[k1]){
                   7906:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   7907:         continue;
                   7908:        }
                   7909:        fprintf(fichtm,"</a></li>");
                   7910:      } /* cptcovn >0 */
                   7911:    }
1.317     brouard  7912:    fprintf(fichtm," \n</ul>");
1.264     brouard  7913: 
1.222     brouard  7914:    jj1=0;
1.237     brouard  7915: 
1.337     brouard  7916:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   7917:      /* k1=nres; */
1.338     brouard  7918:      k1=TKresult[nres];
                   7919:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  7920:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   7921:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   7922:    /*     continue; */
1.220     brouard  7923: 
1.222     brouard  7924:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7925:      jj1++;
                   7926:      if (cptcovn > 0) {
1.264     brouard  7927:        fprintf(fichtm,"\n<p><a name=\"rescov");
1.337     brouard  7928:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   7929:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  7930:        }
1.337     brouard  7931:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   7932:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   7933:        /* } */
1.264     brouard  7934:        fprintf(fichtm,"\"</a>");
                   7935:  
1.222     brouard  7936:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  7937:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   7938:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   7939:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  7940:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   7941:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  7942:        }
1.230     brouard  7943:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.338     brouard  7944:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.222     brouard  7945:        if(invalidvarcomb[k1]){
                   7946:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   7947:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   7948:         continue;
                   7949:        }
                   7950:      }
                   7951:      /* aij, bij */
1.259     brouard  7952:      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  7953: <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  7954:      /* Pij */
1.241     brouard  7955:      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> \
                   7956: <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  7957:      /* Quasi-incidences */
                   7958:      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  7959:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  7960:  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  7961: 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> \
                   7962: <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  7963:      /* Survival functions (period) in state j */
                   7964:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  7965:        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);
                   7966:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   7967:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.222     brouard  7968:      }
                   7969:      /* State specific survival functions (period) */
                   7970:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  7971:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
                   7972:  And probability to be observed in various states (up to %d) being in state %d at different ages.      \
1.329     brouard  7973:  <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);
                   7974:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   7975:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.222     brouard  7976:      }
1.288     brouard  7977:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  7978:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  7979:        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  7980:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
1.329     brouard  7981:       fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.222     brouard  7982:      }
1.296     brouard  7983:      if(prevbcast==1){
1.288     brouard  7984:        /* Backward prevalence in each health state */
1.222     brouard  7985:        for(cpt=1; cpt<=nlstate;cpt++){
1.338     brouard  7986:         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);
                   7987:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJB_"),subdirf2(optionfilefiname,"PIJB_"));
                   7988:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.222     brouard  7989:        }
1.217     brouard  7990:      }
1.222     brouard  7991:      if(prevfcast==1){
1.288     brouard  7992:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  7993:        for(cpt=1; cpt<=nlstate;cpt++){
1.314     brouard  7994:         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);
                   7995:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
                   7996:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
                   7997:                 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  7998:        }
                   7999:      }
1.296     brouard  8000:      if(prevbcast==1){
1.268     brouard  8001:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   8002:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  8003:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
                   8004:  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 \
                   8005:  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  8006: 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);
                   8007:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
                   8008:         fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
1.268     brouard  8009:        }
                   8010:      }
1.220     brouard  8011:         
1.222     brouard  8012:      for(cpt=1; cpt<=nlstate;cpt++) {
1.314     brouard  8013:        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);
                   8014:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
                   8015:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
1.222     brouard  8016:      }
                   8017:      /* } /\* end i1 *\/ */
1.337     brouard  8018:    }/* End k1=nres */
1.222     brouard  8019:    fprintf(fichtm,"</ul>");
1.126     brouard  8020: 
1.222     brouard  8021:    fprintf(fichtm,"\
1.126     brouard  8022: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  8023:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  8024:  - 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  8025: But because parameters are usually highly correlated (a higher incidence of disability \
                   8026: and a higher incidence of recovery can give very close observed transition) it might \
                   8027: be very useful to look not only at linear confidence intervals estimated from the \
                   8028: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   8029: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   8030: covariance matrix of the one-step probabilities. \
                   8031: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  8032: 
1.222     brouard  8033:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   8034:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   8035:    fprintf(fichtm,"\
1.126     brouard  8036:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  8037:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  8038: 
1.222     brouard  8039:    fprintf(fichtm,"\
1.126     brouard  8040:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  8041:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   8042:    fprintf(fichtm,"\
1.126     brouard  8043:  - 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): \
                   8044:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  8045:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  8046:    fprintf(fichtm,"\
1.126     brouard  8047:  - (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): \
                   8048:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  8049:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  8050:    fprintf(fichtm,"\
1.288     brouard  8051:  - 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  8052:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   8053:    fprintf(fichtm,"\
1.128     brouard  8054:  - 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  8055:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   8056:    fprintf(fichtm,"\
1.288     brouard  8057:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  8058:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  8059: 
                   8060: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   8061: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   8062: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   8063: /*     <br>",fileres,fileres,fileres,fileres); */
                   8064: /*  else  */
1.338     brouard  8065: /*    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  8066:    fflush(fichtm);
1.126     brouard  8067: 
1.225     brouard  8068:    m=pow(2,cptcoveff);
1.222     brouard  8069:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  8070: 
1.317     brouard  8071:    fprintf(fichtm," <ul><li><b>Graphs (second order)</b></li><p>");
                   8072: 
                   8073:   jj1=0;
                   8074: 
                   8075:    fprintf(fichtm," \n<ul>");
1.337     brouard  8076:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8077:      /* k1=nres; */
1.338     brouard  8078:      k1=TKresult[nres];
1.337     brouard  8079:      /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   8080:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8081:      /*   continue; */
1.317     brouard  8082:      jj1++;
                   8083:      if (cptcovn > 0) {
                   8084:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescovsecond");
1.337     brouard  8085:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8086:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8087:        }
                   8088:        fprintf(fichtm,"\">");
                   8089:        
                   8090:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   8091:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  8092:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8093:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8094:        }
                   8095:        if(invalidvarcomb[k1]){
                   8096:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   8097:         continue;
                   8098:        }
                   8099:        fprintf(fichtm,"</a></li>");
                   8100:      } /* cptcovn >0 */
1.337     brouard  8101:    } /* End nres */
1.317     brouard  8102:    fprintf(fichtm," \n</ul>");
                   8103: 
1.222     brouard  8104:    jj1=0;
1.237     brouard  8105: 
1.241     brouard  8106:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8107:      /* k1=nres; */
1.338     brouard  8108:      k1=TKresult[nres];
                   8109:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8110:      /* for(k1=1; k1<=m;k1++){ */
                   8111:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8112:      /*   continue; */
1.222     brouard  8113:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   8114:      jj1++;
1.126     brouard  8115:      if (cptcovn > 0) {
1.317     brouard  8116:        fprintf(fichtm,"\n<p><a name=\"rescovsecond");
1.337     brouard  8117:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8118:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8119:        }
                   8120:        fprintf(fichtm,"\"</a>");
                   8121:        
1.126     brouard  8122:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  8123:        for (cpt=1; cpt<=cptcovs;cpt++){  /**< cptcoveff number of variables */
                   8124:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8125:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  8126:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
1.317     brouard  8127:        }
1.237     brouard  8128: 
1.338     brouard  8129:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.220     brouard  8130: 
1.222     brouard  8131:        if(invalidvarcomb[k1]){
                   8132:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   8133:         continue;
                   8134:        }
1.337     brouard  8135:      } /* If cptcovn >0 */
1.126     brouard  8136:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  8137:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.314     brouard  8138: 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);
                   8139:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   8140:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
1.126     brouard  8141:      }
                   8142:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.314     brouard  8143: health expectancies in each live states (1 to %d). If popbased=1 the smooth (due to the model) \
1.128     brouard  8144: true period expectancies (those weighted with period prevalences are also\
                   8145:  drawn in addition to the population based expectancies computed using\
1.314     brouard  8146:  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);
                   8147:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
                   8148:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  8149:      /* } /\* end i1 *\/ */
1.241     brouard  8150:   }/* End nres */
1.222     brouard  8151:    fprintf(fichtm,"</ul>");
                   8152:    fflush(fichtm);
1.126     brouard  8153: }
                   8154: 
                   8155: /******************* Gnuplot file **************/
1.296     brouard  8156: 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  8157: 
                   8158:   char dirfileres[132],optfileres[132];
1.264     brouard  8159:   char gplotcondition[132], gplotlabel[132];
1.343     brouard  8160:   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  8161:   int lv=0, vlv=0, kl=0;
1.130     brouard  8162:   int ng=0;
1.201     brouard  8163:   int vpopbased;
1.223     brouard  8164:   int ioffset; /* variable offset for columns */
1.270     brouard  8165:   int iyearc=1; /* variable column for year of projection  */
                   8166:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  8167:   int nres=0; /* Index of resultline */
1.266     brouard  8168:   int istart=1; /* For starting graphs in projections */
1.219     brouard  8169: 
1.126     brouard  8170: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   8171: /*     printf("Problem with file %s",optionfilegnuplot); */
                   8172: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   8173: /*   } */
                   8174: 
                   8175:   /*#ifdef windows */
                   8176:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  8177:   /*#endif */
1.225     brouard  8178:   m=pow(2,cptcoveff);
1.126     brouard  8179: 
1.274     brouard  8180:   /* diagram of the model */
                   8181:   fprintf(ficgp,"\n#Diagram of the model \n");
                   8182:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   8183:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   8184:   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);
                   8185: 
1.343     brouard  8186:   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  8187:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   8188:   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);
                   8189:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   8190:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   8191:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   8192:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   8193: 
1.202     brouard  8194:   /* Contribution to likelihood */
                   8195:   /* Plot the probability implied in the likelihood */
1.223     brouard  8196:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   8197:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   8198:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   8199:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  8200: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  8201:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   8202: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  8203:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   8204:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8205:   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));
                   8206:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8207:   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));
                   8208:   for (i=1; i<= nlstate ; i ++) {
                   8209:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   8210:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   8211:     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);
                   8212:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   8213:       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);
                   8214:     }
                   8215:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8216:   }
                   8217:   /* 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 */               
                   8218:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   8219:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   8220:   fprintf(ficgp,"\nset out;unset log\n");
                   8221:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  8222: 
1.343     brouard  8223:   /* Plot the probability implied in the likelihood by covariate value */
                   8224:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
                   8225:   /* if(debugILK==1){ */
                   8226:   for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
1.347   ! brouard  8227:     kvar=Tvar[TvarFind[kf]]; /* variable name */
        !          8228:     /* k=18+Tvar[TvarFind[kf]];/\*offset because there are 18 columns in the ILK_ file but could be placed else where *\/ */
        !          8229:     k=18+kf;/*offset because there are 18 columns in the ILK_ file */
1.343     brouard  8230:     for (i=1; i<= nlstate ; i ++) {
                   8231:       fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   8232:       fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
                   8233:       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);
                   8234:       for (j=2; j<= nlstate+ndeath ; j ++) {
                   8235:        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);
                   8236:       }
                   8237:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8238:     }
                   8239:   } /* End of each covariate dummy */
                   8240:   for(ncovv=1, iposold=0, kk=0; ncovv <= ncovvt ; ncovv++){
                   8241:     /* Other example        V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   8242:      *     kmodel       =     1   2     3     4         5        6        7       8        9
                   8243:      *  varying                   1     2                                 3       4        5
                   8244:      *  ncovv                     1     2                                3 4     5 6      7 8
                   8245:      * TvarVV[ncovv]             V3     5                                1 3     3 5      1 5
                   8246:      * TvarVVind[ncovv]=kmodel    2     3                                7 7     8 8      9 9
                   8247:      * TvarFind[kmodel]       1   0     0     0         0        0        0       0        0
                   8248:      * kdata     ncovcol=[V1 V2] nqv=0 ntv=[V3 V4] nqtv=V5
                   8249:      * Dummy[kmodel]          0   0     1     2         2        3        1       1        1
                   8250:      */
                   8251:     ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   8252:     kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   8253:     /* 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]); */
                   8254:     if(ipos!=iposold){ /* Not a product or first of a product */
                   8255:       /* printf(" %d",ipos); */
                   8256:       /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   8257:       /* printf(" DebugILK ficgp suite ipos=%d != iposold=%d\n", ipos, iposold); */
                   8258:       kk++; /* Position of the ncovv column in ILK_ */
                   8259:       k=18+ncovf+kk; /*offset because there are 18 columns in the ILK_ file plus ncovf fixed covariate */
                   8260:       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)  */
                   8261:        for (i=1; i<= nlstate ; i ++) {
                   8262:          fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   8263:          fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
                   8264: 
                   8265:          if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
                   8266:            /* printf("DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
                   8267:            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);
                   8268:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   8269:              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);
                   8270:            }
                   8271:          }else{
                   8272:            /* printf("DebugILK gnuplotversion=%g <5.2\n",gnuplotversion); */
                   8273:            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);
                   8274:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   8275:              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);
                   8276:            }
                   8277:          }
                   8278:          fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8279:        }
                   8280:       }/* End if dummy varying */
                   8281:     }else{ /*Product */
                   8282:       /* printf("*"); */
                   8283:       /* fprintf(ficresilk,"*"); */
                   8284:     }
                   8285:     iposold=ipos;
                   8286:   } /* For each time varying covariate */
                   8287:   /* } /\* debugILK==1 *\/ */
                   8288:   /* 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 */               
                   8289:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   8290:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   8291:   fprintf(ficgp,"\nset out;unset log\n");
                   8292:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
                   8293: 
                   8294: 
                   8295:   
1.126     brouard  8296:   strcpy(dirfileres,optionfilefiname);
                   8297:   strcpy(optfileres,"vpl");
1.223     brouard  8298:   /* 1eme*/
1.238     brouard  8299:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
1.337     brouard  8300:     /* for (k1=1; k1<= m ; k1 ++){ /\* For each valid combination of covariate *\/ */
1.236     brouard  8301:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8302:        k1=TKresult[nres];
1.338     brouard  8303:        if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.238     brouard  8304:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.337     brouard  8305:        /* if(m != 1 && TKresult[nres]!= k1) */
                   8306:        /*   continue; */
1.238     brouard  8307:        /* We are interested in selected combination by the resultline */
1.246     brouard  8308:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  8309:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  8310:        strcpy(gplotlabel,"(");
1.337     brouard  8311:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8312:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8313:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8314: 
                   8315:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate k get corresponding value lv for combination k1 *\/ */
                   8316:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the value of the covariate corresponding to k1 combination *\\/ *\/ */
                   8317:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8318:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8319:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8320:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8321:        /*   vlv= nbcode[Tvaraff[k]][lv]; /\* vlv is the value of the covariate lv, 0 or 1 *\/ */
                   8322:        /*   /\* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv *\/ */
                   8323:        /*   /\* printf(" V%d=%d ",Tvaraff[k],vlv); *\/ */
                   8324:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8325:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8326:        /* } */
                   8327:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8328:        /*   /\* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); *\/ */
                   8329:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8330:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.264     brouard  8331:        }
                   8332:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  8333:        /* printf("\n#\n"); */
1.238     brouard  8334:        fprintf(ficgp,"\n#\n");
                   8335:        if(invalidvarcomb[k1]){
1.260     brouard  8336:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  8337:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8338:          continue;
                   8339:        }
1.235     brouard  8340:       
1.241     brouard  8341:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   8342:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  8343:        /* 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  8344:        fprintf(ficgp,"set title \"Alive state %d %s model=1+age+%s\" font \"Helvetica,12\"\n",cpt,gplotlabel,model);
1.260     brouard  8345:        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);
                   8346:        /* 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); */
                   8347:       /* k1-1 error should be nres-1*/
1.238     brouard  8348:        for (i=1; i<= nlstate ; i ++) {
                   8349:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8350:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   8351:        }
1.288     brouard  8352:        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  8353:        for (i=1; i<= nlstate ; i ++) {
                   8354:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8355:          else fprintf(ficgp," %%*lf (%%*lf)");
                   8356:        } 
1.260     brouard  8357:        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  8358:        for (i=1; i<= nlstate ; i ++) {
                   8359:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8360:          else fprintf(ficgp," %%*lf (%%*lf)");
                   8361:        }  
1.265     brouard  8362:        /* 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)); */
                   8363:        
                   8364:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   8365:         if(cptcoveff ==0){
1.271     brouard  8366:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  8367:        }else{
                   8368:          kl=0;
                   8369:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  8370:            /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8371:            lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.265     brouard  8372:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8373:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8374:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8375:            vlv= nbcode[Tvaraff[k]][lv];
                   8376:            kl++;
                   8377:            /* 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 *\/ */
                   8378:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8379:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8380:            /* ''  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*/
                   8381:            if(k==cptcoveff){
                   8382:              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], \
                   8383:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   8384:            }else{
                   8385:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   8386:              kl++;
                   8387:            }
                   8388:          } /* end covariate */
                   8389:        } /* end if no covariate */
                   8390: 
1.296     brouard  8391:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  8392:          /* 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  8393:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  8394:          if(cptcoveff ==0){
1.245     brouard  8395:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  8396:          }else{
                   8397:            kl=0;
                   8398:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  8399:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8400:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.238     brouard  8401:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8402:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8403:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8404:              /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8405:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.223     brouard  8406:              kl++;
1.238     brouard  8407:              /* 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 *\/ */
                   8408:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8409:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8410:              /* ''  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*/
                   8411:              if(k==cptcoveff){
1.245     brouard  8412:                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  8413:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  8414:              }else{
1.332     brouard  8415:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]);
1.238     brouard  8416:                kl++;
                   8417:              }
                   8418:            } /* end covariate */
                   8419:          } /* end if no covariate */
1.296     brouard  8420:          if(prevbcast == 1){
1.268     brouard  8421:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   8422:            /* k1-1 error should be nres-1*/
                   8423:            for (i=1; i<= nlstate ; i ++) {
                   8424:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8425:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   8426:            }
1.271     brouard  8427:            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  8428:            for (i=1; i<= nlstate ; i ++) {
                   8429:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8430:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8431:            } 
1.276     brouard  8432:            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  8433:            for (i=1; i<= nlstate ; i ++) {
                   8434:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8435:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8436:            } 
1.274     brouard  8437:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  8438:          } /* end if backprojcast */
1.296     brouard  8439:        } /* end if prevbcast */
1.276     brouard  8440:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   8441:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  8442:       } /* nres */
1.337     brouard  8443:     /* } /\* k1 *\/ */
1.201     brouard  8444:   } /* cpt */
1.235     brouard  8445: 
                   8446:   
1.126     brouard  8447:   /*2 eme*/
1.337     brouard  8448:   /* for (k1=1; k1<= m ; k1 ++){   */
1.238     brouard  8449:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8450:       k1=TKresult[nres];
1.338     brouard  8451:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8452:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8453:       /*       continue; */
1.238     brouard  8454:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  8455:       strcpy(gplotlabel,"(");
1.337     brouard  8456:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8457:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8458:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8459:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8460:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8461:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8462:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8463:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8464:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8465:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8466:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8467:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8468:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8469:       /* } */
                   8470:       /* /\* for(k=1; k <= ncovds; k++){ *\/ */
                   8471:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8472:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8473:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8474:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  8475:       }
1.264     brouard  8476:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8477:       fprintf(ficgp,"\n#\n");
1.223     brouard  8478:       if(invalidvarcomb[k1]){
                   8479:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8480:        continue;
                   8481:       }
1.219     brouard  8482:                        
1.241     brouard  8483:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  8484:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  8485:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   8486:        if(vpopbased==0){
1.238     brouard  8487:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  8488:        }else
1.238     brouard  8489:          fprintf(ficgp,"\nreplot ");
                   8490:        for (i=1; i<= nlstate+1 ; i ++) {
                   8491:          k=2*i;
1.261     brouard  8492:          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  8493:          for (j=1; j<= nlstate+1 ; j ++) {
                   8494:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8495:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8496:          }   
                   8497:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   8498:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
1.261     brouard  8499:          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  8500:          for (j=1; j<= nlstate+1 ; j ++) {
                   8501:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8502:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8503:          }   
                   8504:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  8505:          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  8506:          for (j=1; j<= nlstate+1 ; j ++) {
                   8507:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8508:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8509:          }   
                   8510:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   8511:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   8512:        } /* state */
                   8513:       } /* vpopbased */
1.264     brouard  8514:       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  8515:     } /* end nres */
1.337     brouard  8516:   /* } /\* k1 end 2 eme*\/ */
1.238     brouard  8517:        
                   8518:        
                   8519:   /*3eme*/
1.337     brouard  8520:   /* for (k1=1; k1<= m ; k1 ++){ */
1.238     brouard  8521:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8522:       k1=TKresult[nres];
1.338     brouard  8523:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8524:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8525:       /*       continue; */
1.238     brouard  8526: 
1.332     brouard  8527:       for (cpt=1; cpt<= nlstate ; cpt ++) { /* Fragile no verification of covariate values */
1.261     brouard  8528:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  8529:        strcpy(gplotlabel,"(");
1.337     brouard  8530:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8531:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8532:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8533:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8534:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8535:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8536:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8537:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8538:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8539:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8540:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8541:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8542:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8543:        /* } */
                   8544:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8545:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   8546:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   8547:        }
1.264     brouard  8548:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8549:        fprintf(ficgp,"\n#\n");
                   8550:        if(invalidvarcomb[k1]){
                   8551:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8552:          continue;
                   8553:        }
                   8554:                        
                   8555:        /*       k=2+nlstate*(2*cpt-2); */
                   8556:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  8557:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  8558:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  8559:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  8560: 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  8561:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8562:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8563:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   8564:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8565:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8566:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  8567:                                
1.238     brouard  8568:        */
                   8569:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  8570:          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  8571:          /*    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  8572:                                
1.238     brouard  8573:        } 
1.261     brouard  8574:        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  8575:       }
1.264     brouard  8576:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  8577:     } /* end nres */
1.337     brouard  8578:   /* } /\* end kl 3eme *\/ */
1.126     brouard  8579:   
1.223     brouard  8580:   /* 4eme */
1.201     brouard  8581:   /* Survival functions (period) from state i in state j by initial state i */
1.337     brouard  8582:   /* for (k1=1; k1<=m; k1++){    /\* For each covariate and each value *\/ */
1.238     brouard  8583:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8584:       k1=TKresult[nres];
1.338     brouard  8585:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8586:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8587:       /*       continue; */
1.238     brouard  8588:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  8589:        strcpy(gplotlabel,"(");
1.337     brouard  8590:        fprintf(ficgp,"\n#\n#\n# Survival functions in state %d : 'LIJ_' files, cov=%d state=%d", cpt, k1, cpt);
                   8591:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8592:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8593:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8594:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8595:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8596:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8597:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8598:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8599:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8600:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8601:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8602:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8603:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8604:        /* } */
                   8605:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8606:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8607:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  8608:        }       
1.264     brouard  8609:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8610:        fprintf(ficgp,"\n#\n");
                   8611:        if(invalidvarcomb[k1]){
                   8612:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8613:          continue;
1.223     brouard  8614:        }
1.238     brouard  8615:       
1.241     brouard  8616:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  8617:        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  8618:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8619: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8620:        k=3;
                   8621:        for (i=1; i<= nlstate ; i ++){
                   8622:          if(i==1){
                   8623:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8624:          }else{
                   8625:            fprintf(ficgp,", '' ");
                   8626:          }
                   8627:          l=(nlstate+ndeath)*(i-1)+1;
                   8628:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8629:          for (j=2; j<= nlstate+ndeath ; j ++)
                   8630:            fprintf(ficgp,"+$%d",k+l+j-1);
                   8631:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   8632:        } /* nlstate */
1.264     brouard  8633:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8634:       } /* end cpt state*/ 
                   8635:     } /* end nres */
1.337     brouard  8636:   /* } /\* end covariate k1 *\/   */
1.238     brouard  8637: 
1.220     brouard  8638: /* 5eme */
1.201     brouard  8639:   /* Survival functions (period) from state i in state j by final state j */
1.337     brouard  8640:   /* for (k1=1; k1<= m ; k1++){ /\* For each covariate combination if any *\/ */
1.238     brouard  8641:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8642:       k1=TKresult[nres];
1.338     brouard  8643:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8644:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8645:       /*       continue; */
1.238     brouard  8646:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  8647:        strcpy(gplotlabel,"(");
1.238     brouard  8648:        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  8649:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8650:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8651:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8652:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8653:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8654:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8655:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8656:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8657:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8658:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8659:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8660:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8661:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8662:        /* } */
                   8663:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8664:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8665:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  8666:        }       
1.264     brouard  8667:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8668:        fprintf(ficgp,"\n#\n");
                   8669:        if(invalidvarcomb[k1]){
                   8670:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8671:          continue;
                   8672:        }
1.227     brouard  8673:       
1.241     brouard  8674:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  8675:        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  8676:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8677: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8678:        k=3;
                   8679:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8680:          if(j==1)
                   8681:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8682:          else
                   8683:            fprintf(ficgp,", '' ");
                   8684:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8685:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   8686:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   8687:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   8688:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   8689:        } /* nlstate */
                   8690:        fprintf(ficgp,", '' ");
                   8691:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   8692:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8693:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8694:          if(j < nlstate)
                   8695:            fprintf(ficgp,"$%d +",k+l);
                   8696:          else
                   8697:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   8698:        }
1.264     brouard  8699:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8700:       } /* end cpt state*/ 
1.337     brouard  8701:     /* } /\* end covariate *\/   */
1.238     brouard  8702:   } /* end nres */
1.227     brouard  8703:   
1.220     brouard  8704: /* 6eme */
1.202     brouard  8705:   /* CV preval stable (period) for each covariate */
1.337     brouard  8706:   /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8707:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8708:      k1=TKresult[nres];
1.338     brouard  8709:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8710:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8711:      /*  continue; */
1.255     brouard  8712:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  8713:       strcpy(gplotlabel,"(");      
1.288     brouard  8714:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8715:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8716:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8717:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8718:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8719:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8720:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8721:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8722:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8723:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8724:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8725:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8726:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8727:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8728:       /* } */
                   8729:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8730:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8731:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8732:       }        
1.264     brouard  8733:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8734:       fprintf(ficgp,"\n#\n");
1.223     brouard  8735:       if(invalidvarcomb[k1]){
1.227     brouard  8736:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8737:        continue;
1.223     brouard  8738:       }
1.227     brouard  8739:       
1.241     brouard  8740:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  8741:       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  8742:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8743: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  8744:       k=3; /* Offset */
1.255     brouard  8745:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  8746:        if(i==1)
                   8747:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8748:        else
                   8749:          fprintf(ficgp,", '' ");
1.255     brouard  8750:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  8751:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8752:        for (j=2; j<= nlstate ; j ++)
                   8753:          fprintf(ficgp,"+$%d",k+l+j-1);
                   8754:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  8755:       } /* nlstate */
1.264     brouard  8756:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  8757:     } /* end cpt state*/ 
                   8758:   } /* end covariate */  
1.227     brouard  8759:   
                   8760:   
1.220     brouard  8761: /* 7eme */
1.296     brouard  8762:   if(prevbcast == 1){
1.288     brouard  8763:     /* CV backward prevalence  for each covariate */
1.337     brouard  8764:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8765:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8766:       k1=TKresult[nres];
1.338     brouard  8767:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8768:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8769:       /*       continue; */
1.268     brouard  8770:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  8771:        strcpy(gplotlabel,"(");      
1.288     brouard  8772:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8773:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8774:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8775:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8776:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8777:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8778:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8779:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8780:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8781:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8782:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8783:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8784:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8785:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8786:        /* } */
                   8787:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8788:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8789:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8790:        }       
1.264     brouard  8791:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8792:        fprintf(ficgp,"\n#\n");
                   8793:        if(invalidvarcomb[k1]){
                   8794:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8795:          continue;
                   8796:        }
                   8797:        
1.241     brouard  8798:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  8799:        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  8800:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8801: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  8802:        k=3; /* Offset */
1.268     brouard  8803:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  8804:          if(i==1)
                   8805:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   8806:          else
                   8807:            fprintf(ficgp,", '' ");
                   8808:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  8809:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.324     brouard  8810:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   8811:          /* 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  8812:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  8813:          /* for (j=2; j<= nlstate ; j ++) */
                   8814:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   8815:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  8816:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  8817:        } /* nlstate */
1.264     brouard  8818:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  8819:       } /* end cpt state*/ 
                   8820:     } /* end covariate */  
1.296     brouard  8821:   } /* End if prevbcast */
1.218     brouard  8822:   
1.223     brouard  8823:   /* 8eme */
1.218     brouard  8824:   if(prevfcast==1){
1.288     brouard  8825:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  8826:     
1.337     brouard  8827:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8828:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8829:       k1=TKresult[nres];
1.338     brouard  8830:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8831:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8832:       /*       continue; */
1.211     brouard  8833:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  8834:        strcpy(gplotlabel,"(");      
1.288     brouard  8835:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8836:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8837:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8838:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8839:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   8840:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   8841:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8842:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8843:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8844:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8845:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8846:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8847:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8848:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8849:        /* } */
                   8850:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8851:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8852:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8853:        }       
1.264     brouard  8854:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8855:        fprintf(ficgp,"\n#\n");
                   8856:        if(invalidvarcomb[k1]){
                   8857:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8858:          continue;
                   8859:        }
                   8860:        
                   8861:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  8862:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  8863:        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  8864:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  8865: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  8866: 
                   8867:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   8868:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8869:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8870:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  8871:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8872:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8873:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8874:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  8875:          if(i==istart){
1.227     brouard  8876:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   8877:          }else{
                   8878:            fprintf(ficgp,",\\\n '' ");
                   8879:          }
                   8880:          if(cptcoveff ==0){ /* No covariate */
                   8881:            ioffset=2; /* Age is in 2 */
                   8882:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8883:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8884:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8885:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8886:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  8887:            if(i==nlstate+1){
1.270     brouard  8888:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  8889:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   8890:              fprintf(ficgp,",\\\n '' ");
                   8891:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  8892:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  8893:                     offyear,                           \
1.268     brouard  8894:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  8895:            }else
1.227     brouard  8896:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   8897:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8898:          }else{ /* more than 2 covariates */
1.270     brouard  8899:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   8900:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8901:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   8902:            iyearc=ioffset-1;
                   8903:            iagec=ioffset;
1.227     brouard  8904:            fprintf(ficgp," u %d:(",ioffset); 
                   8905:            kl=0;
                   8906:            strcpy(gplotcondition,"(");
                   8907:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
1.332     brouard  8908:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8909:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.227     brouard  8910:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8911:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8912:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8913:              /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   8914:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.227     brouard  8915:              kl++;
                   8916:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   8917:              kl++;
                   8918:              if(k <cptcoveff && cptcoveff>1)
                   8919:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   8920:            }
                   8921:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   8922:            /* 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 *\/ */
                   8923:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8924:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8925:            /* ''  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*/
                   8926:            if(i==nlstate+1){
1.270     brouard  8927:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   8928:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  8929:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  8930:              fprintf(ficgp," u %d:(",iagec); 
                   8931:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   8932:                      iyearc, iagec, offyear,                           \
                   8933:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  8934: /*  '' 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  8935:            }else{
                   8936:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   8937:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8938:            }
                   8939:          } /* end if covariate */
                   8940:        } /* nlstate */
1.264     brouard  8941:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  8942:       } /* end cpt state*/
                   8943:     } /* end covariate */
                   8944:   } /* End if prevfcast */
1.227     brouard  8945:   
1.296     brouard  8946:   if(prevbcast==1){
1.268     brouard  8947:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   8948:     
1.337     brouard  8949:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.268     brouard  8950:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8951:      k1=TKresult[nres];
1.338     brouard  8952:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8953:        /* if(m != 1 && TKresult[nres]!= k1) */
                   8954:        /*      continue; */
1.268     brouard  8955:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   8956:        strcpy(gplotlabel,"(");      
                   8957:        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  8958:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8959:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8960:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8961:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   8962:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   8963:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8964:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8965:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8966:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8967:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8968:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8969:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8970:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8971:        /* } */
                   8972:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8973:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8974:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.268     brouard  8975:        }       
                   8976:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   8977:        fprintf(ficgp,"\n#\n");
                   8978:        if(invalidvarcomb[k1]){
                   8979:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8980:          continue;
                   8981:        }
                   8982:        
                   8983:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   8984:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   8985:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   8986:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   8987: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8988: 
                   8989:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   8990:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8991:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8992:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   8993:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8994:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8995:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8996:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8997:          if(i==istart){
                   8998:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   8999:          }else{
                   9000:            fprintf(ficgp,",\\\n '' ");
                   9001:          }
                   9002:          if(cptcoveff ==0){ /* No covariate */
                   9003:            ioffset=2; /* Age is in 2 */
                   9004:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9005:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9006:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9007:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9008:            fprintf(ficgp," u %d:(", ioffset); 
                   9009:            if(i==nlstate+1){
1.270     brouard  9010:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  9011:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   9012:              fprintf(ficgp,",\\\n '' ");
                   9013:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  9014:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  9015:                     offbyear,                          \
                   9016:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   9017:            }else
                   9018:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   9019:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   9020:          }else{ /* more than 2 covariates */
1.270     brouard  9021:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   9022:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9023:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   9024:            iyearc=ioffset-1;
                   9025:            iagec=ioffset;
1.268     brouard  9026:            fprintf(ficgp," u %d:(",ioffset); 
                   9027:            kl=0;
                   9028:            strcpy(gplotcondition,"(");
1.337     brouard  9029:            for (k=1; k<=cptcovs; k++){    /* For each covariate k of the resultline, get corresponding value lv for combination k1 */
1.338     brouard  9030:              if(Dummy[modelresult[nres][k]]==0){  /* To be verified */
1.337     brouard  9031:                /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
                   9032:                /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9033:                /* lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9034:                lv=Tvresult[nres][k];
                   9035:                vlv=TinvDoQresult[nres][Tvresult[nres][k]];
                   9036:                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   9037:                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   9038:                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   9039:                /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   9040:                /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9041:                kl++;
                   9042:                /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
                   9043:                sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%lg " ,kl,Tvresult[nres][k], kl+1,TinvDoQresult[nres][Tvresult[nres][k]]);
                   9044:                kl++;
1.338     brouard  9045:                if(k <cptcovs && cptcovs>1)
1.337     brouard  9046:                  sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   9047:              }
1.268     brouard  9048:            }
                   9049:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   9050:            /* 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 *\/ */
                   9051:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   9052:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   9053:            /* ''  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*/
                   9054:            if(i==nlstate+1){
1.270     brouard  9055:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   9056:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  9057:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  9058:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  9059:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  9060:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   9061:                      iyearc,iagec,offbyear,                            \
                   9062:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  9063: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   9064:            }else{
                   9065:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   9066:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   9067:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   9068:            }
                   9069:          } /* end if covariate */
                   9070:        } /* nlstate */
                   9071:        fprintf(ficgp,"\nset out; unset label;\n");
                   9072:       } /* end cpt state*/
                   9073:     } /* end covariate */
1.296     brouard  9074:   } /* End if prevbcast */
1.268     brouard  9075:   
1.227     brouard  9076:   
1.238     brouard  9077:   /* 9eme writing MLE parameters */
                   9078:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  9079:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  9080:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  9081:     for(k=1; k <=(nlstate+ndeath); k++){
                   9082:       if (k != i) {
1.227     brouard  9083:        fprintf(ficgp,"#   current state %d\n",k);
                   9084:        for(j=1; j <=ncovmodel; j++){
                   9085:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   9086:          jk++; 
                   9087:        }
                   9088:        fprintf(ficgp,"\n");
1.126     brouard  9089:       }
                   9090:     }
1.223     brouard  9091:   }
1.187     brouard  9092:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  9093:   
1.145     brouard  9094:   /*goto avoid;*/
1.238     brouard  9095:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   9096:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  9097:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   9098:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   9099:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   9100:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   9101:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9102:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   9103:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9104:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   9105:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   9106:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9107:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   9108:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   9109:   fprintf(ficgp,"#\n");
1.223     brouard  9110:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  9111:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.338     brouard  9112:     fprintf(ficgp,"#model=1+age+%s \n",model);
1.238     brouard  9113:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.264     brouard  9114:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
1.337     brouard  9115:     /* for(k1=1; k1 <=m; k1++)  /\* For each combination of covariate *\/ */
1.237     brouard  9116:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  9117:      /* k1=nres; */
1.338     brouard  9118:       k1=TKresult[nres];
                   9119:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9120:       fprintf(ficgp,"\n\n# Resultline k1=%d ",k1);
1.264     brouard  9121:       strcpy(gplotlabel,"(");
1.276     brouard  9122:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.337     brouard  9123:       for (k=1; k<=cptcovs; k++){  /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   9124:        /* for each resultline nres, and position k, Tvresult[nres][k] gives the name of the variable and
                   9125:           TinvDoQresult[nres][Tvresult[nres][k]] gives its value double or integer) */
                   9126:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9127:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9128:       }
                   9129:       /* if(m != 1 && TKresult[nres]!= k1) */
                   9130:       /*       continue; */
                   9131:       /* fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1); */
                   9132:       /* strcpy(gplotlabel,"("); */
                   9133:       /* /\*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*\/ */
                   9134:       /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   9135:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   9136:       /*       lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9137:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9138:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9139:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9140:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9141:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9142:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9143:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9144:       /* } */
                   9145:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9146:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9147:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9148:       /* }      */
1.264     brouard  9149:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  9150:       fprintf(ficgp,"\n#\n");
1.264     brouard  9151:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  9152:       fprintf(ficgp,"\nset key outside ");
                   9153:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   9154:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  9155:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   9156:       if (ng==1){
                   9157:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   9158:        fprintf(ficgp,"\nunset log y");
                   9159:       }else if (ng==2){
                   9160:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   9161:        fprintf(ficgp,"\nset log y");
                   9162:       }else if (ng==3){
                   9163:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   9164:        fprintf(ficgp,"\nset log y");
                   9165:       }else
                   9166:        fprintf(ficgp,"\nunset title ");
                   9167:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   9168:       i=1;
                   9169:       for(k2=1; k2<=nlstate; k2++) {
                   9170:        k3=i;
                   9171:        for(k=1; k<=(nlstate+ndeath); k++) {
                   9172:          if (k != k2){
                   9173:            switch( ng) {
                   9174:            case 1:
                   9175:              if(nagesqr==0)
                   9176:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   9177:              else /* nagesqr =1 */
                   9178:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   9179:              break;
                   9180:            case 2: /* ng=2 */
                   9181:              if(nagesqr==0)
                   9182:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   9183:              else /* nagesqr =1 */
                   9184:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   9185:              break;
                   9186:            case 3:
                   9187:              if(nagesqr==0)
                   9188:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   9189:              else /* nagesqr =1 */
                   9190:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   9191:              break;
                   9192:            }
                   9193:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  9194:            ijp=1; /* product no age */
                   9195:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   9196:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  9197:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.329     brouard  9198:              switch(Typevar[j]){
                   9199:              case 1:
                   9200:                if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   9201:                  if(j==Tage[ij]) { /* Product by age  To be looked at!!*//* Bug valgrind */
                   9202:                    if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   9203:                      if(DummyV[j]==0){/* Bug valgrind */
                   9204:                        fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   9205:                      }else{ /* quantitative */
                   9206:                        fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   9207:                        /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9208:                      }
                   9209:                      ij++;
1.268     brouard  9210:                    }
1.237     brouard  9211:                  }
1.329     brouard  9212:                }
                   9213:                break;
                   9214:              case 2:
                   9215:                if(cptcovprod >0){
                   9216:                  if(j==Tprod[ijp]) { /* */ 
                   9217:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9218:                    if(ijp <=cptcovprod) { /* Product */
                   9219:                      if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   9220:                        if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   9221:                          /* 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)]); */
                   9222:                          fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9223:                        }else{ /* Vn is dummy and Vm is quanti */
                   9224:                          /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9225:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9226:                        }
                   9227:                      }else{ /* Vn*Vm Vn is quanti */
                   9228:                        if(DummyV[Tvard[ijp][2]]==0){
                   9229:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   9230:                        }else{ /* Both quanti */
                   9231:                          fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9232:                        }
1.268     brouard  9233:                      }
1.329     brouard  9234:                      ijp++;
1.237     brouard  9235:                    }
1.329     brouard  9236:                  } /* end Tprod */
                   9237:                }
                   9238:                break;
                   9239:              case 0:
                   9240:                /* simple covariate */
1.264     brouard  9241:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  9242:                if(Dummy[j]==0){
                   9243:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   9244:                }else{ /* quantitative */
                   9245:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  9246:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  9247:                }
1.329     brouard  9248:               /* end simple */
                   9249:                break;
                   9250:              default:
                   9251:                break;
                   9252:              } /* end switch */
1.237     brouard  9253:            } /* end j */
1.329     brouard  9254:          }else{ /* k=k2 */
                   9255:            if(ng !=1 ){ /* For logit formula of log p11 is more difficult to get */
                   9256:              fprintf(ficgp," (1.");i=i-ncovmodel;
                   9257:            }else
                   9258:              i=i-ncovmodel;
1.223     brouard  9259:          }
1.227     brouard  9260:          
1.223     brouard  9261:          if(ng != 1){
                   9262:            fprintf(ficgp,")/(1");
1.227     brouard  9263:            
1.264     brouard  9264:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  9265:              if(nagesqr==0)
1.264     brouard  9266:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  9267:              else /* nagesqr =1 */
1.264     brouard  9268:                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  9269:               
1.223     brouard  9270:              ij=1;
1.329     brouard  9271:              ijp=1;
                   9272:              /* for(j=3; j <=ncovmodel-nagesqr; j++){ */
                   9273:              for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
                   9274:                switch(Typevar[j]){
                   9275:                case 1:
                   9276:                  if(cptcovage >0){ 
                   9277:                    if(j==Tage[ij]) { /* Bug valgrind */
                   9278:                      if(ij <=cptcovage) { /* Bug valgrind */
                   9279:                        if(DummyV[j]==0){/* Bug valgrind */
                   9280:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]); */
                   9281:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,nbcode[Tvar[j]][codtabm(k1,j)]); */
                   9282:                          fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]);
                   9283:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);; */
                   9284:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9285:                        }else{ /* quantitative */
                   9286:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   9287:                          fprintf(ficgp,"+p%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   9288:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   9289:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9290:                        }
                   9291:                        ij++;
                   9292:                      }
                   9293:                    }
                   9294:                  }
                   9295:                  break;
                   9296:                case 2:
                   9297:                  if(cptcovprod >0){
                   9298:                    if(j==Tprod[ijp]) { /* */ 
                   9299:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9300:                      if(ijp <=cptcovprod) { /* Product */
                   9301:                        if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   9302:                          if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   9303:                            /* 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)]); */
                   9304:                            fprintf(ficgp,"+p%d*%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9305:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   9306:                          }else{ /* Vn is dummy and Vm is quanti */
                   9307:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9308:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9309:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9310:                          }
                   9311:                        }else{ /* Vn*Vm Vn is quanti */
                   9312:                          if(DummyV[Tvard[ijp][2]]==0){
                   9313:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   9314:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   9315:                          }else{ /* Both quanti */
                   9316:                            fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9317:                            /* fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9318:                          } 
                   9319:                        }
                   9320:                        ijp++;
                   9321:                      }
                   9322:                    } /* end Tprod */
                   9323:                  } /* end if */
                   9324:                  break;
                   9325:                case 0: 
                   9326:                  /* simple covariate */
                   9327:                  /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
                   9328:                  if(Dummy[j]==0){
                   9329:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   9330:                    fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]); /*  */
                   9331:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   9332:                  }else{ /* quantitative */
                   9333:                    fprintf(ficgp,"+p%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* */
                   9334:                    /* fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* *\/ */
                   9335:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9336:                  }
                   9337:                  /* end simple */
                   9338:                  /* fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);/\* Valgrind bug nbcode *\/ */
                   9339:                  break;
                   9340:                default:
                   9341:                  break;
                   9342:                } /* end switch */
1.223     brouard  9343:              }
                   9344:              fprintf(ficgp,")");
                   9345:            }
                   9346:            fprintf(ficgp,")");
                   9347:            if(ng ==2)
1.276     brouard  9348:              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  9349:            else /* ng= 3 */
1.276     brouard  9350:              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  9351:           }else{ /* end ng <> 1 */
1.223     brouard  9352:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  9353:              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  9354:          }
                   9355:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   9356:            fprintf(ficgp,",");
                   9357:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   9358:            fprintf(ficgp,",");
                   9359:          i=i+ncovmodel;
                   9360:        } /* end k */
                   9361:       } /* end k2 */
1.276     brouard  9362:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   9363:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.337     brouard  9364:     } /* end resultline */
1.223     brouard  9365:   } /* end ng */
                   9366:   /* avoid: */
                   9367:   fflush(ficgp); 
1.126     brouard  9368: }  /* end gnuplot */
                   9369: 
                   9370: 
                   9371: /*************** Moving average **************/
1.219     brouard  9372: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  9373:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  9374:    
1.222     brouard  9375:    int i, cpt, cptcod;
                   9376:    int modcovmax =1;
                   9377:    int mobilavrange, mob;
                   9378:    int iage=0;
1.288     brouard  9379:    int firstA1=0, firstA2=0;
1.222     brouard  9380: 
1.266     brouard  9381:    double sum=0., sumr=0.;
1.222     brouard  9382:    double age;
1.266     brouard  9383:    double *sumnewp, *sumnewm, *sumnewmr;
                   9384:    double *agemingood, *agemaxgood; 
                   9385:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  9386:   
                   9387:   
1.278     brouard  9388:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   9389:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  9390: 
                   9391:    sumnewp = vector(1,ncovcombmax);
                   9392:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  9393:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  9394:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  9395:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  9396:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  9397:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  9398: 
                   9399:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  9400:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  9401:      sumnewp[cptcod]=0.;
1.266     brouard  9402:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   9403:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  9404:    }
                   9405:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   9406:   
1.266     brouard  9407:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   9408:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  9409:      else mobilavrange=mobilav;
                   9410:      for (age=bage; age<=fage; age++)
                   9411:        for (i=1; i<=nlstate;i++)
                   9412:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   9413:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9414:      /* We keep the original values on the extreme ages bage, fage and for 
                   9415:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   9416:        we use a 5 terms etc. until the borders are no more concerned. 
                   9417:      */ 
                   9418:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   9419:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  9420:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   9421:           sumnewm[cptcod]=0.;
                   9422:           for (i=1; i<=nlstate;i++){
1.222     brouard  9423:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   9424:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   9425:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   9426:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   9427:             }
                   9428:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  9429:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9430:           } /* end i */
                   9431:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   9432:         } /* end cptcod */
1.222     brouard  9433:        }/* end age */
                   9434:      }/* end mob */
1.266     brouard  9435:    }else{
                   9436:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  9437:      return -1;
1.266     brouard  9438:    }
                   9439: 
                   9440:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  9441:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   9442:      if(invalidvarcomb[cptcod]){
                   9443:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   9444:        continue;
                   9445:      }
1.219     brouard  9446: 
1.266     brouard  9447:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   9448:        sumnewm[cptcod]=0.;
                   9449:        sumnewmr[cptcod]=0.;
                   9450:        for (i=1; i<=nlstate;i++){
                   9451:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9452:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9453:        }
                   9454:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9455:         agemingoodr[cptcod]=age;
                   9456:        }
                   9457:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9458:           agemingood[cptcod]=age;
                   9459:        }
                   9460:      } /* age */
                   9461:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  9462:        sumnewm[cptcod]=0.;
1.266     brouard  9463:        sumnewmr[cptcod]=0.;
1.222     brouard  9464:        for (i=1; i<=nlstate;i++){
                   9465:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9466:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9467:        }
                   9468:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9469:         agemaxgoodr[cptcod]=age;
1.222     brouard  9470:        }
                   9471:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  9472:         agemaxgood[cptcod]=age;
                   9473:        }
                   9474:      } /* age */
                   9475:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   9476:      /* but they will change */
1.288     brouard  9477:      firstA1=0;firstA2=0;
1.266     brouard  9478:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   9479:        sumnewm[cptcod]=0.;
                   9480:        sumnewmr[cptcod]=0.;
                   9481:        for (i=1; i<=nlstate;i++){
                   9482:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9483:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9484:        }
                   9485:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9486:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9487:           agemaxgoodr[cptcod]=age;  /* age min */
                   9488:           for (i=1; i<=nlstate;i++)
                   9489:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9490:         }else{ /* bad we change the value with the values of good ages */
                   9491:           for (i=1; i<=nlstate;i++){
                   9492:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   9493:           } /* i */
                   9494:         } /* end bad */
                   9495:        }else{
                   9496:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9497:           agemaxgood[cptcod]=age;
                   9498:         }else{ /* bad we change the value with the values of good ages */
                   9499:           for (i=1; i<=nlstate;i++){
                   9500:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   9501:           } /* i */
                   9502:         } /* end bad */
                   9503:        }/* end else */
                   9504:        sum=0.;sumr=0.;
                   9505:        for (i=1; i<=nlstate;i++){
                   9506:         sum+=mobaverage[(int)age][i][cptcod];
                   9507:         sumr+=probs[(int)age][i][cptcod];
                   9508:        }
                   9509:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  9510:         if(!firstA1){
                   9511:           firstA1=1;
                   9512:           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);
                   9513:         }
                   9514:         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  9515:        } /* end bad */
                   9516:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9517:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  9518:         if(!firstA2){
                   9519:           firstA2=1;
                   9520:           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);
                   9521:         }
                   9522:         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  9523:        } /* end bad */
                   9524:      }/* age */
1.266     brouard  9525: 
                   9526:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  9527:        sumnewm[cptcod]=0.;
1.266     brouard  9528:        sumnewmr[cptcod]=0.;
1.222     brouard  9529:        for (i=1; i<=nlstate;i++){
                   9530:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9531:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9532:        } 
                   9533:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9534:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   9535:           agemingoodr[cptcod]=age;
                   9536:           for (i=1; i<=nlstate;i++)
                   9537:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9538:         }else{ /* bad we change the value with the values of good ages */
                   9539:           for (i=1; i<=nlstate;i++){
                   9540:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   9541:           } /* i */
                   9542:         } /* end bad */
                   9543:        }else{
                   9544:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9545:           agemingood[cptcod]=age;
                   9546:         }else{ /* bad */
                   9547:           for (i=1; i<=nlstate;i++){
                   9548:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   9549:           } /* i */
                   9550:         } /* end bad */
                   9551:        }/* end else */
                   9552:        sum=0.;sumr=0.;
                   9553:        for (i=1; i<=nlstate;i++){
                   9554:         sum+=mobaverage[(int)age][i][cptcod];
                   9555:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  9556:        }
1.266     brouard  9557:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  9558:         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  9559:        } /* end bad */
                   9560:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9561:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  9562:         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  9563:        } /* end bad */
                   9564:      }/* age */
1.266     brouard  9565: 
1.222     brouard  9566:                
                   9567:      for (age=bage; age<=fage; age++){
1.235     brouard  9568:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  9569:        sumnewp[cptcod]=0.;
                   9570:        sumnewm[cptcod]=0.;
                   9571:        for (i=1; i<=nlstate;i++){
                   9572:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   9573:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9574:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   9575:        }
                   9576:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   9577:      }
                   9578:      /* printf("\n"); */
                   9579:      /* } */
1.266     brouard  9580: 
1.222     brouard  9581:      /* brutal averaging */
1.266     brouard  9582:      /* for (i=1; i<=nlstate;i++){ */
                   9583:      /*   for (age=1; age<=bage; age++){ */
                   9584:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   9585:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9586:      /*   }     */
                   9587:      /*   for (age=fage; age<=AGESUP; age++){ */
                   9588:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   9589:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9590:      /*   } */
                   9591:      /* } /\* end i status *\/ */
                   9592:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   9593:      /*   for (age=1; age<=AGESUP; age++){ */
                   9594:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   9595:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   9596:      /*   } */
                   9597:      /* } */
1.222     brouard  9598:    }/* end cptcod */
1.266     brouard  9599:    free_vector(agemaxgoodr,1, ncovcombmax);
                   9600:    free_vector(agemaxgood,1, ncovcombmax);
                   9601:    free_vector(agemingood,1, ncovcombmax);
                   9602:    free_vector(agemingoodr,1, ncovcombmax);
                   9603:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  9604:    free_vector(sumnewm,1, ncovcombmax);
                   9605:    free_vector(sumnewp,1, ncovcombmax);
                   9606:    return 0;
                   9607:  }/* End movingaverage */
1.218     brouard  9608:  
1.126     brouard  9609: 
1.296     brouard  9610:  
1.126     brouard  9611: /************** Forecasting ******************/
1.296     brouard  9612: /* 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)*/
                   9613: 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){
                   9614:   /* dateintemean, mean date of interviews
                   9615:      dateprojd, year, month, day of starting projection 
                   9616:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  9617:      agemin, agemax range of age
                   9618:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   9619:   */
1.296     brouard  9620:   /* double anprojd, mprojd, jprojd; */
                   9621:   /* double anprojf, mprojf, jprojf; */
1.267     brouard  9622:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  9623:   double agec; /* generic age */
1.296     brouard  9624:   double agelim, ppij, yp,yp1,yp2;
1.126     brouard  9625:   double *popeffectif,*popcount;
                   9626:   double ***p3mat;
1.218     brouard  9627:   /* double ***mobaverage; */
1.126     brouard  9628:   char fileresf[FILENAMELENGTH];
                   9629: 
                   9630:   agelim=AGESUP;
1.211     brouard  9631:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9632:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9633:      We still use firstpass and lastpass as another selection.
                   9634:   */
1.214     brouard  9635:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9636:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  9637:  
1.201     brouard  9638:   strcpy(fileresf,"F_"); 
                   9639:   strcat(fileresf,fileresu);
1.126     brouard  9640:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   9641:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   9642:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   9643:   }
1.235     brouard  9644:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   9645:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  9646: 
1.225     brouard  9647:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  9648: 
                   9649: 
                   9650:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9651:   if (stepm<=12) stepsize=1;
                   9652:   if(estepm < stepm){
                   9653:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9654:   }
1.270     brouard  9655:   else{
                   9656:     hstepm=estepm;   
                   9657:   }
                   9658:   if(estepm > stepm){ /* Yes every two year */
                   9659:     stepsize=2;
                   9660:   }
1.296     brouard  9661:   hstepm=hstepm/stepm;
1.126     brouard  9662: 
1.296     brouard  9663:   
                   9664:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9665:   /*                              fractional in yp1 *\/ */
                   9666:   /* aintmean=yp; */
                   9667:   /* yp2=modf((yp1*12),&yp); */
                   9668:   /* mintmean=yp; */
                   9669:   /* yp1=modf((yp2*30.5),&yp); */
                   9670:   /* jintmean=yp; */
                   9671:   /* if(jintmean==0) jintmean=1; */
                   9672:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  9673: 
1.296     brouard  9674: 
                   9675:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   9676:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   9677:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.227     brouard  9678:   i1=pow(2,cptcoveff);
1.126     brouard  9679:   if (cptcovn < 1){i1=1;}
                   9680:   
1.296     brouard  9681:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  9682:   
                   9683:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  9684:   
1.126     brouard  9685: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  9686:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.332     brouard  9687:     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  9688:     if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  9689:       continue;
1.227     brouard  9690:     if(invalidvarcomb[k]){
                   9691:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   9692:       continue;
                   9693:     }
                   9694:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   9695:     for(j=1;j<=cptcoveff;j++) {
1.332     brouard  9696:       /* fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); */
                   9697:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.227     brouard  9698:     }
1.235     brouard  9699:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  9700:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.235     brouard  9701:     }
1.227     brouard  9702:     fprintf(ficresf," yearproj age");
                   9703:     for(j=1; j<=nlstate+ndeath;j++){ 
                   9704:       for(i=1; i<=nlstate;i++)               
                   9705:        fprintf(ficresf," p%d%d",i,j);
                   9706:       fprintf(ficresf," wp.%d",j);
                   9707:     }
1.296     brouard  9708:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  9709:       fprintf(ficresf,"\n");
1.296     brouard  9710:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  9711:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   9712:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  9713:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   9714:        nhstepm = nhstepm/hstepm; 
                   9715:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9716:        oldm=oldms;savm=savms;
1.268     brouard  9717:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  9718:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  9719:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  9720:        for (h=0; h<=nhstepm; h++){
                   9721:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  9722:            break;
                   9723:          }
                   9724:        }
                   9725:        fprintf(ficresf,"\n");
                   9726:        for(j=1;j<=cptcoveff;j++) 
1.332     brouard  9727:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Tvaraff not correct *\/ */
                   9728:          fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /* TnsdVar[Tvaraff]  correct */
1.296     brouard  9729:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  9730:        
                   9731:        for(j=1; j<=nlstate+ndeath;j++) {
                   9732:          ppij=0.;
                   9733:          for(i=1; i<=nlstate;i++) {
1.278     brouard  9734:            if (mobilav>=1)
                   9735:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   9736:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   9737:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   9738:            }
1.268     brouard  9739:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   9740:          } /* end i */
                   9741:          fprintf(ficresf," %.3f", ppij);
                   9742:        }/* end j */
1.227     brouard  9743:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9744:       } /* end agec */
1.266     brouard  9745:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   9746:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  9747:     } /* end yearp */
                   9748:   } /* end  k */
1.219     brouard  9749:        
1.126     brouard  9750:   fclose(ficresf);
1.215     brouard  9751:   printf("End of Computing forecasting \n");
                   9752:   fprintf(ficlog,"End of Computing forecasting\n");
                   9753: 
1.126     brouard  9754: }
                   9755: 
1.269     brouard  9756: /************** Back Forecasting ******************/
1.296     brouard  9757:  /* 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){ */
                   9758:  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){
                   9759:   /* back1, year, month, day of starting backprojection
1.267     brouard  9760:      agemin, agemax range of age
                   9761:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  9762:      anback2 year of end of backprojection (same day and month as back1).
                   9763:      prevacurrent and prev are prevalences.
1.267     brouard  9764:   */
                   9765:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   9766:   double agec; /* generic age */
1.302     brouard  9767:   double agelim, ppij, ppi, yp,yp1,yp2; /* ,jintmean,mintmean,aintmean;*/
1.267     brouard  9768:   double *popeffectif,*popcount;
                   9769:   double ***p3mat;
                   9770:   /* double ***mobaverage; */
                   9771:   char fileresfb[FILENAMELENGTH];
                   9772:  
1.268     brouard  9773:   agelim=AGEINF;
1.267     brouard  9774:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9775:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9776:      We still use firstpass and lastpass as another selection.
                   9777:   */
                   9778:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9779:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   9780: 
                   9781:   /*Do we need to compute prevalence again?*/
                   9782: 
                   9783:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   9784:   
                   9785:   strcpy(fileresfb,"FB_");
                   9786:   strcat(fileresfb,fileresu);
                   9787:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   9788:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   9789:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   9790:   }
                   9791:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   9792:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   9793:   
                   9794:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   9795:   
                   9796:    
                   9797:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9798:   if (stepm<=12) stepsize=1;
                   9799:   if(estepm < stepm){
                   9800:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9801:   }
1.270     brouard  9802:   else{
                   9803:     hstepm=estepm;   
                   9804:   }
                   9805:   if(estepm >= stepm){ /* Yes every two year */
                   9806:     stepsize=2;
                   9807:   }
1.267     brouard  9808:   
                   9809:   hstepm=hstepm/stepm;
1.296     brouard  9810:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9811:   /*                              fractional in yp1 *\/ */
                   9812:   /* aintmean=yp; */
                   9813:   /* yp2=modf((yp1*12),&yp); */
                   9814:   /* mintmean=yp; */
                   9815:   /* yp1=modf((yp2*30.5),&yp); */
                   9816:   /* jintmean=yp; */
                   9817:   /* if(jintmean==0) jintmean=1; */
                   9818:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  9819:   
                   9820:   i1=pow(2,cptcoveff);
                   9821:   if (cptcovn < 1){i1=1;}
                   9822:   
1.296     brouard  9823:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   9824:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  9825:   
                   9826:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   9827:   
                   9828:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9829:   for(k=1; k<=i1;k++){
                   9830:     if(i1 != 1 && TKresult[nres]!= k)
                   9831:       continue;
                   9832:     if(invalidvarcomb[k]){
                   9833:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   9834:       continue;
                   9835:     }
1.268     brouard  9836:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.267     brouard  9837:     for(j=1;j<=cptcoveff;j++) {
1.332     brouard  9838:       fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.267     brouard  9839:     }
                   9840:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   9841:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9842:     }
                   9843:     fprintf(ficresfb," yearbproj age");
                   9844:     for(j=1; j<=nlstate+ndeath;j++){
                   9845:       for(i=1; i<=nlstate;i++)
1.268     brouard  9846:        fprintf(ficresfb," b%d%d",i,j);
                   9847:       fprintf(ficresfb," b.%d",j);
1.267     brouard  9848:     }
1.296     brouard  9849:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  9850:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   9851:       fprintf(ficresfb,"\n");
1.296     brouard  9852:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  9853:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  9854:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   9855:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  9856:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  9857:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  9858:        nhstepm = nhstepm/hstepm;
                   9859:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9860:        oldm=oldms;savm=savms;
1.268     brouard  9861:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  9862:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  9863:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  9864:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   9865:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   9866:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  9867:        for (h=0; h<=nhstepm; h++){
1.268     brouard  9868:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   9869:            break;
                   9870:          }
                   9871:        }
                   9872:        fprintf(ficresfb,"\n");
                   9873:        for(j=1;j<=cptcoveff;j++)
1.332     brouard  9874:          fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.296     brouard  9875:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  9876:        for(i=1; i<=nlstate+ndeath;i++) {
                   9877:          ppij=0.;ppi=0.;
                   9878:          for(j=1; j<=nlstate;j++) {
                   9879:            /* if (mobilav==1) */
1.269     brouard  9880:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   9881:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   9882:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   9883:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  9884:              /* else { */
                   9885:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   9886:              /* } */
1.268     brouard  9887:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   9888:          } /* end j */
                   9889:          if(ppi <0.99){
                   9890:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   9891:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   9892:          }
                   9893:          fprintf(ficresfb," %.3f", ppij);
                   9894:        }/* end j */
1.267     brouard  9895:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9896:       } /* end agec */
                   9897:     } /* end yearp */
                   9898:   } /* end k */
1.217     brouard  9899:   
1.267     brouard  9900:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  9901:   
1.267     brouard  9902:   fclose(ficresfb);
                   9903:   printf("End of Computing Back forecasting \n");
                   9904:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  9905:        
1.267     brouard  9906: }
1.217     brouard  9907: 
1.269     brouard  9908: /* Variance of prevalence limit: varprlim */
                   9909:  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  9910:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  9911:  
                   9912:    char fileresvpl[FILENAMELENGTH];  
                   9913:    FILE *ficresvpl;
                   9914:    double **oldm, **savm;
                   9915:    double **varpl; /* Variances of prevalence limits by age */   
                   9916:    int i1, k, nres, j ;
                   9917:    
                   9918:     strcpy(fileresvpl,"VPL_");
                   9919:     strcat(fileresvpl,fileresu);
                   9920:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  9921:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  9922:       exit(0);
                   9923:     }
1.288     brouard  9924:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   9925:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  9926:     
                   9927:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   9928:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   9929:     
                   9930:     i1=pow(2,cptcoveff);
                   9931:     if (cptcovn < 1){i1=1;}
                   9932: 
1.337     brouard  9933:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9934:        k=TKresult[nres];
1.338     brouard  9935:        if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  9936:      /* for(k=1; k<=i1;k++){ /\* We find the combination equivalent to result line values of dummies *\/ */
1.269     brouard  9937:       if(i1 != 1 && TKresult[nres]!= k)
                   9938:        continue;
                   9939:       fprintf(ficresvpl,"\n#****** ");
                   9940:       printf("\n#****** ");
                   9941:       fprintf(ficlog,"\n#****** ");
1.337     brouard  9942:       for(j=1;j<=cptcovs;j++) {
                   9943:        fprintf(ficresvpl,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   9944:        fprintf(ficlog,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   9945:        printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   9946:        /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   9947:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.269     brouard  9948:       }
1.337     brouard  9949:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   9950:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9951:       /*       fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9952:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9953:       /* }      */
1.269     brouard  9954:       fprintf(ficresvpl,"******\n");
                   9955:       printf("******\n");
                   9956:       fprintf(ficlog,"******\n");
                   9957:       
                   9958:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9959:       oldm=oldms;savm=savms;
                   9960:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   9961:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   9962:       /*}*/
                   9963:     }
                   9964:     
                   9965:     fclose(ficresvpl);
1.288     brouard  9966:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   9967:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  9968: 
                   9969:  }
                   9970: /* Variance of back prevalence: varbprlim */
                   9971:  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){
                   9972:       /*------- Variance of back (stable) prevalence------*/
                   9973: 
                   9974:    char fileresvbl[FILENAMELENGTH];  
                   9975:    FILE  *ficresvbl;
                   9976: 
                   9977:    double **oldm, **savm;
                   9978:    double **varbpl; /* Variances of back prevalence limits by age */   
                   9979:    int i1, k, nres, j ;
                   9980: 
                   9981:    strcpy(fileresvbl,"VBL_");
                   9982:    strcat(fileresvbl,fileresu);
                   9983:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   9984:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   9985:      exit(0);
                   9986:    }
                   9987:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   9988:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   9989:    
                   9990:    
                   9991:    i1=pow(2,cptcoveff);
                   9992:    if (cptcovn < 1){i1=1;}
                   9993:    
1.337     brouard  9994:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9995:      k=TKresult[nres];
1.338     brouard  9996:      if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  9997:     /* for(k=1; k<=i1;k++){ */
                   9998:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   9999:     /*          continue; */
1.269     brouard  10000:        fprintf(ficresvbl,"\n#****** ");
                   10001:        printf("\n#****** ");
                   10002:        fprintf(ficlog,"\n#****** ");
1.337     brouard  10003:        for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */
1.338     brouard  10004:         printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   10005:         fprintf(ficresvbl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   10006:         fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
1.337     brouard  10007:        /* for(j=1;j<=cptcoveff;j++) { */
                   10008:        /*       fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10009:        /*       fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10010:        /*       printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10011:        /* } */
                   10012:        /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   10013:        /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10014:        /*       fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10015:        /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
1.269     brouard  10016:        }
                   10017:        fprintf(ficresvbl,"******\n");
                   10018:        printf("******\n");
                   10019:        fprintf(ficlog,"******\n");
                   10020:        
                   10021:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   10022:        oldm=oldms;savm=savms;
                   10023:        
                   10024:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   10025:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   10026:        /*}*/
                   10027:      }
                   10028:    
                   10029:    fclose(ficresvbl);
                   10030:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   10031:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   10032: 
                   10033:  } /* End of varbprlim */
                   10034: 
1.126     brouard  10035: /************** Forecasting *****not tested NB*************/
1.227     brouard  10036: /* 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  10037:   
1.227     brouard  10038: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   10039: /*   int *popage; */
                   10040: /*   double calagedatem, agelim, kk1, kk2; */
                   10041: /*   double *popeffectif,*popcount; */
                   10042: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   10043: /*   /\* double ***mobaverage; *\/ */
                   10044: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  10045: 
1.227     brouard  10046: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10047: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10048: /*   agelim=AGESUP; */
                   10049: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  10050:   
1.227     brouard  10051: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  10052:   
                   10053:   
1.227     brouard  10054: /*   strcpy(filerespop,"POP_");  */
                   10055: /*   strcat(filerespop,fileresu); */
                   10056: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   10057: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   10058: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   10059: /*   } */
                   10060: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   10061: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  10062: 
1.227     brouard  10063: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  10064: 
1.227     brouard  10065: /*   /\* if (mobilav!=0) { *\/ */
                   10066: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   10067: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   10068: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   10069: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   10070: /*   /\*   } *\/ */
                   10071: /*   /\* } *\/ */
1.126     brouard  10072: 
1.227     brouard  10073: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   10074: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  10075:   
1.227     brouard  10076: /*   agelim=AGESUP; */
1.126     brouard  10077:   
1.227     brouard  10078: /*   hstepm=1; */
                   10079: /*   hstepm=hstepm/stepm;  */
1.218     brouard  10080:        
1.227     brouard  10081: /*   if (popforecast==1) { */
                   10082: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   10083: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   10084: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   10085: /*     }  */
                   10086: /*     popage=ivector(0,AGESUP); */
                   10087: /*     popeffectif=vector(0,AGESUP); */
                   10088: /*     popcount=vector(0,AGESUP); */
1.126     brouard  10089:     
1.227     brouard  10090: /*     i=1;    */
                   10091: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  10092:     
1.227     brouard  10093: /*     imx=i; */
                   10094: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   10095: /*   } */
1.218     brouard  10096:   
1.227     brouard  10097: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   10098: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   10099: /*       k=k+1; */
                   10100: /*       fprintf(ficrespop,"\n#******"); */
                   10101: /*       for(j=1;j<=cptcoveff;j++) { */
                   10102: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   10103: /*       } */
                   10104: /*       fprintf(ficrespop,"******\n"); */
                   10105: /*       fprintf(ficrespop,"# Age"); */
                   10106: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   10107: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  10108:       
1.227     brouard  10109: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   10110: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  10111:        
1.227     brouard  10112: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   10113: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   10114: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  10115:          
1.227     brouard  10116: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10117: /*       oldm=oldms;savm=savms; */
                   10118: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  10119:          
1.227     brouard  10120: /*       for (h=0; h<=nhstepm; h++){ */
                   10121: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   10122: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   10123: /*         }  */
                   10124: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   10125: /*           kk1=0.;kk2=0; */
                   10126: /*           for(i=1; i<=nlstate;i++) {               */
                   10127: /*             if (mobilav==1)  */
                   10128: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   10129: /*             else { */
                   10130: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   10131: /*             } */
                   10132: /*           } */
                   10133: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   10134: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   10135: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   10136: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   10137: /*           } */
                   10138: /*         } */
                   10139: /*         for(i=1; i<=nlstate;i++){ */
                   10140: /*           kk1=0.; */
                   10141: /*           for(j=1; j<=nlstate;j++){ */
                   10142: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   10143: /*           } */
                   10144: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   10145: /*         } */
1.218     brouard  10146:            
1.227     brouard  10147: /*         if (h==(int)(calagedatem+12*cpt)) */
                   10148: /*           for(j=1; j<=nlstate;j++)  */
                   10149: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   10150: /*       } */
                   10151: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10152: /*     } */
                   10153: /*       } */
1.218     brouard  10154:       
1.227     brouard  10155: /*       /\******\/ */
1.218     brouard  10156:       
1.227     brouard  10157: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   10158: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   10159: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   10160: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   10161: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  10162:          
1.227     brouard  10163: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10164: /*       oldm=oldms;savm=savms; */
                   10165: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   10166: /*       for (h=0; h<=nhstepm; h++){ */
                   10167: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   10168: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   10169: /*         }  */
                   10170: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   10171: /*           kk1=0.;kk2=0; */
                   10172: /*           for(i=1; i<=nlstate;i++) {               */
                   10173: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   10174: /*           } */
                   10175: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   10176: /*         } */
                   10177: /*       } */
                   10178: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10179: /*     } */
                   10180: /*       } */
                   10181: /*     }  */
                   10182: /*   } */
1.218     brouard  10183:   
1.227     brouard  10184: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  10185:   
1.227     brouard  10186: /*   if (popforecast==1) { */
                   10187: /*     free_ivector(popage,0,AGESUP); */
                   10188: /*     free_vector(popeffectif,0,AGESUP); */
                   10189: /*     free_vector(popcount,0,AGESUP); */
                   10190: /*   } */
                   10191: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10192: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10193: /*   fclose(ficrespop); */
                   10194: /* } /\* End of popforecast *\/ */
1.218     brouard  10195:  
1.126     brouard  10196: int fileappend(FILE *fichier, char *optionfich)
                   10197: {
                   10198:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   10199:     printf("Problem with file: %s\n", optionfich);
                   10200:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   10201:     return (0);
                   10202:   }
                   10203:   fflush(fichier);
                   10204:   return (1);
                   10205: }
                   10206: 
                   10207: 
                   10208: /**************** function prwizard **********************/
                   10209: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   10210: {
                   10211: 
                   10212:   /* Wizard to print covariance matrix template */
                   10213: 
1.164     brouard  10214:   char ca[32], cb[32];
                   10215:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  10216:   int numlinepar;
                   10217: 
                   10218:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10219:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10220:   for(i=1; i <=nlstate; i++){
                   10221:     jj=0;
                   10222:     for(j=1; j <=nlstate+ndeath; j++){
                   10223:       if(j==i) continue;
                   10224:       jj++;
                   10225:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   10226:       printf("%1d%1d",i,j);
                   10227:       fprintf(ficparo,"%1d%1d",i,j);
                   10228:       for(k=1; k<=ncovmodel;k++){
                   10229:        /*        printf(" %lf",param[i][j][k]); */
                   10230:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   10231:        printf(" 0.");
                   10232:        fprintf(ficparo," 0.");
                   10233:       }
                   10234:       printf("\n");
                   10235:       fprintf(ficparo,"\n");
                   10236:     }
                   10237:   }
                   10238:   printf("# Scales (for hessian or gradient estimation)\n");
                   10239:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   10240:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   10241:   for(i=1; i <=nlstate; i++){
                   10242:     jj=0;
                   10243:     for(j=1; j <=nlstate+ndeath; j++){
                   10244:       if(j==i) continue;
                   10245:       jj++;
                   10246:       fprintf(ficparo,"%1d%1d",i,j);
                   10247:       printf("%1d%1d",i,j);
                   10248:       fflush(stdout);
                   10249:       for(k=1; k<=ncovmodel;k++){
                   10250:        /*      printf(" %le",delti3[i][j][k]); */
                   10251:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   10252:        printf(" 0.");
                   10253:        fprintf(ficparo," 0.");
                   10254:       }
                   10255:       numlinepar++;
                   10256:       printf("\n");
                   10257:       fprintf(ficparo,"\n");
                   10258:     }
                   10259:   }
                   10260:   printf("# Covariance matrix\n");
                   10261: /* # 121 Var(a12)\n\ */
                   10262: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10263: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   10264: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   10265: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   10266: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   10267: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   10268: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   10269:   fflush(stdout);
                   10270:   fprintf(ficparo,"# Covariance matrix\n");
                   10271:   /* # 121 Var(a12)\n\ */
                   10272:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10273:   /* #   ...\n\ */
                   10274:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   10275:   
                   10276:   for(itimes=1;itimes<=2;itimes++){
                   10277:     jj=0;
                   10278:     for(i=1; i <=nlstate; i++){
                   10279:       for(j=1; j <=nlstate+ndeath; j++){
                   10280:        if(j==i) continue;
                   10281:        for(k=1; k<=ncovmodel;k++){
                   10282:          jj++;
                   10283:          ca[0]= k+'a'-1;ca[1]='\0';
                   10284:          if(itimes==1){
                   10285:            printf("#%1d%1d%d",i,j,k);
                   10286:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   10287:          }else{
                   10288:            printf("%1d%1d%d",i,j,k);
                   10289:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   10290:            /*  printf(" %.5le",matcov[i][j]); */
                   10291:          }
                   10292:          ll=0;
                   10293:          for(li=1;li <=nlstate; li++){
                   10294:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   10295:              if(lj==li) continue;
                   10296:              for(lk=1;lk<=ncovmodel;lk++){
                   10297:                ll++;
                   10298:                if(ll<=jj){
                   10299:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   10300:                  if(ll<jj){
                   10301:                    if(itimes==1){
                   10302:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10303:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10304:                    }else{
                   10305:                      printf(" 0.");
                   10306:                      fprintf(ficparo," 0.");
                   10307:                    }
                   10308:                  }else{
                   10309:                    if(itimes==1){
                   10310:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   10311:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   10312:                    }else{
                   10313:                      printf(" 0.");
                   10314:                      fprintf(ficparo," 0.");
                   10315:                    }
                   10316:                  }
                   10317:                }
                   10318:              } /* end lk */
                   10319:            } /* end lj */
                   10320:          } /* end li */
                   10321:          printf("\n");
                   10322:          fprintf(ficparo,"\n");
                   10323:          numlinepar++;
                   10324:        } /* end k*/
                   10325:       } /*end j */
                   10326:     } /* end i */
                   10327:   } /* end itimes */
                   10328: 
                   10329: } /* end of prwizard */
                   10330: /******************* Gompertz Likelihood ******************************/
                   10331: double gompertz(double x[])
                   10332: { 
1.302     brouard  10333:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
1.126     brouard  10334:   int i,n=0; /* n is the size of the sample */
                   10335: 
1.220     brouard  10336:   for (i=1;i<=imx ; i++) {
1.126     brouard  10337:     sump=sump+weight[i];
                   10338:     /*    sump=sump+1;*/
                   10339:     num=num+1;
                   10340:   }
1.302     brouard  10341:   L=0.0;
                   10342:   /* agegomp=AGEGOMP; */
1.126     brouard  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: 
1.302     brouard  10346:   for (i=1;i<=imx ; i++) {
                   10347:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   10348:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   10349:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   10350:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   10351:      * +
                   10352:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   10353:      */
                   10354:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   10355:        if (cens[i] == 1){
                   10356:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   10357:        } else if (cens[i] == 0){
1.126     brouard  10358:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
1.302     brouard  10359:          +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   10360:       } else
                   10361:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
1.126     brouard  10362:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
1.302     brouard  10363:        L=L+A*weight[i];
1.126     brouard  10364:        /*      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  10365:      }
                   10366:   }
1.126     brouard  10367: 
1.302     brouard  10368:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
1.126     brouard  10369:  
                   10370:   return -2*L*num/sump;
                   10371: }
                   10372: 
1.136     brouard  10373: #ifdef GSL
                   10374: /******************* Gompertz_f Likelihood ******************************/
                   10375: double gompertz_f(const gsl_vector *v, void *params)
                   10376: { 
1.302     brouard  10377:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
1.136     brouard  10378:   double *x= (double *) v->data;
                   10379:   int i,n=0; /* n is the size of the sample */
                   10380: 
                   10381:   for (i=0;i<=imx-1 ; i++) {
                   10382:     sump=sump+weight[i];
                   10383:     /*    sump=sump+1;*/
                   10384:     num=num+1;
                   10385:   }
                   10386:  
                   10387:  
                   10388:   /* for (i=0; i<=imx; i++) 
                   10389:      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]);*/
                   10390:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   10391:   for (i=1;i<=imx ; i++)
                   10392:     {
                   10393:       if (cens[i] == 1 && wav[i]>1)
                   10394:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   10395:       
                   10396:       if (cens[i] == 0 && wav[i]>1)
                   10397:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   10398:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   10399:       
                   10400:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   10401:       if (wav[i] > 1 ) { /* ??? */
                   10402:        LL=LL+A*weight[i];
                   10403:        /*      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]);*/
                   10404:       }
                   10405:     }
                   10406: 
                   10407:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   10408:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   10409:  
                   10410:   return -2*LL*num/sump;
                   10411: }
                   10412: #endif
                   10413: 
1.126     brouard  10414: /******************* Printing html file ***********/
1.201     brouard  10415: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  10416:                  int lastpass, int stepm, int weightopt, char model[],\
                   10417:                  int imx,  double p[],double **matcov,double agemortsup){
                   10418:   int i,k;
                   10419: 
                   10420:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   10421:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   10422:   for (i=1;i<=2;i++) 
                   10423:     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  10424:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  10425:   fprintf(fichtm,"</ul>");
                   10426: 
                   10427: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   10428: 
                   10429:  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>");
                   10430: 
                   10431:  for (k=agegomp;k<(agemortsup-2);k++) 
                   10432:    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]);
                   10433: 
                   10434:  
                   10435:   fflush(fichtm);
                   10436: }
                   10437: 
                   10438: /******************* Gnuplot file **************/
1.201     brouard  10439: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  10440: 
                   10441:   char dirfileres[132],optfileres[132];
1.164     brouard  10442: 
1.126     brouard  10443:   int ng;
                   10444: 
                   10445: 
                   10446:   /*#ifdef windows */
                   10447:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   10448:     /*#endif */
                   10449: 
                   10450: 
                   10451:   strcpy(dirfileres,optionfilefiname);
                   10452:   strcpy(optfileres,"vpl");
1.199     brouard  10453:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  10454:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  10455:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  10456:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  10457:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   10458: 
                   10459: } 
                   10460: 
1.136     brouard  10461: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   10462: {
1.126     brouard  10463: 
1.136     brouard  10464:   /*-------- data file ----------*/
                   10465:   FILE *fic;
                   10466:   char dummy[]="                         ";
1.240     brouard  10467:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  10468:   int lstra;
1.136     brouard  10469:   int linei, month, year,iout;
1.302     brouard  10470:   int noffset=0; /* This is the offset if BOM data file */
1.136     brouard  10471:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  10472:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  10473:   char *stratrunc;
1.223     brouard  10474: 
1.240     brouard  10475:   DummyV=ivector(1,NCOVMAX); /* 1 to 3 */
                   10476:   FixedV=ivector(1,NCOVMAX); /* 1 to 3 */
1.328     brouard  10477:   for(v=1;v<NCOVMAX;v++){
                   10478:     DummyV[v]=0;
                   10479:     FixedV[v]=0;
                   10480:   }
1.126     brouard  10481: 
1.240     brouard  10482:   for(v=1; v <=ncovcol;v++){
                   10483:     DummyV[v]=0;
                   10484:     FixedV[v]=0;
                   10485:   }
                   10486:   for(v=ncovcol+1; v <=ncovcol+nqv;v++){
                   10487:     DummyV[v]=1;
                   10488:     FixedV[v]=0;
                   10489:   }
                   10490:   for(v=ncovcol+nqv+1; v <=ncovcol+nqv+ntv;v++){
                   10491:     DummyV[v]=0;
                   10492:     FixedV[v]=1;
                   10493:   }
                   10494:   for(v=ncovcol+nqv+ntv+1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   10495:     DummyV[v]=1;
                   10496:     FixedV[v]=1;
                   10497:   }
                   10498:   for(v=1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   10499:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   10500:     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]);
                   10501:   }
1.339     brouard  10502:   
                   10503:   ncovcolt=ncovcol+nqv+ntv+nqtv; /* total of covariates in the data, not in the model equation */
                   10504:   
1.136     brouard  10505:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  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;
1.136     brouard  10508:   }
1.126     brouard  10509: 
1.302     brouard  10510:     /* Is it a BOM UTF-8 Windows file? */
                   10511:   /* First data line */
                   10512:   linei=0;
                   10513:   while(fgets(line, MAXLINE, fic)) {
                   10514:     noffset=0;
                   10515:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   10516:     {
                   10517:       noffset=noffset+3;
                   10518:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   10519:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   10520:       fflush(ficlog); return 1;
                   10521:     }
                   10522:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   10523:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   10524:     {
                   10525:       noffset=noffset+2;
1.304     brouard  10526:       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);
                   10527:       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  10528:       fflush(ficlog); return 1;
                   10529:     }
                   10530:     else if( line[0] == 0 && line[1] == 0)
                   10531:     {
                   10532:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   10533:        noffset=noffset+4;
1.304     brouard  10534:        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);
                   10535:        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  10536:        fflush(ficlog); return 1;
                   10537:       }
                   10538:     } else{
                   10539:       ;/*printf(" Not a BOM file\n");*/
                   10540:     }
                   10541:         /* If line starts with a # it is a comment */
                   10542:     if (line[noffset] == '#') {
                   10543:       linei=linei+1;
                   10544:       break;
                   10545:     }else{
                   10546:       break;
                   10547:     }
                   10548:   }
                   10549:   fclose(fic);
                   10550:   if((fic=fopen(datafile,"r"))==NULL)    {
                   10551:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10552:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   10553:   }
                   10554:   /* Not a Bom file */
                   10555:   
1.136     brouard  10556:   i=1;
                   10557:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   10558:     linei=linei+1;
                   10559:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   10560:       if(line[j] == '\t')
                   10561:        line[j] = ' ';
                   10562:     }
                   10563:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   10564:       ;
                   10565:     };
                   10566:     line[j+1]=0;  /* Trims blanks at end of line */
                   10567:     if(line[0]=='#'){
                   10568:       fprintf(ficlog,"Comment line\n%s\n",line);
                   10569:       printf("Comment line\n%s\n",line);
                   10570:       continue;
                   10571:     }
                   10572:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  10573:     strcpy(line, linetmp);
1.223     brouard  10574:     
                   10575:     /* Loops on waves */
                   10576:     for (j=maxwav;j>=1;j--){
                   10577:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  10578:        cutv(stra, strb, line, ' '); 
                   10579:        if(strb[0]=='.') { /* Missing value */
                   10580:          lval=-1;
                   10581:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
1.341     brouard  10582:          cotvar[j][ncovcol+nqv+ntv+iv][i]=-1; /* For performance reasons */
1.238     brouard  10583:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   10584:            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);
                   10585:            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);
                   10586:            return 1;
                   10587:          }
                   10588:        }else{
                   10589:          errno=0;
                   10590:          /* what_kind_of_number(strb); */
                   10591:          dval=strtod(strb,&endptr); 
                   10592:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   10593:          /* if(strb != endptr && *endptr == '\0') */
                   10594:          /*    dval=dlval; */
                   10595:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10596:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10597:            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);
                   10598:            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);
                   10599:            return 1;
                   10600:          }
                   10601:          cotqvar[j][iv][i]=dval; 
1.341     brouard  10602:          cotvar[j][ncovcol+nqv+ntv+iv][i]=dval; /* because cotvar starts now at first ntv */ 
1.238     brouard  10603:        }
                   10604:        strcpy(line,stra);
1.223     brouard  10605:       }/* end loop ntqv */
1.225     brouard  10606:       
1.223     brouard  10607:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  10608:        cutv(stra, strb, line, ' '); 
                   10609:        if(strb[0]=='.') { /* Missing value */
                   10610:          lval=-1;
                   10611:        }else{
                   10612:          errno=0;
                   10613:          lval=strtol(strb,&endptr,10); 
                   10614:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   10615:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10616:            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);
                   10617:            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);
                   10618:            return 1;
                   10619:          }
                   10620:        }
                   10621:        if(lval <-1 || lval >1){
                   10622:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10623:  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  10624:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10625:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10626:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10627:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10628:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10629:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10630:  Exiting.\n",lval,linei, i,line,iv,j);
1.238     brouard  10631:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10632:  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  10633:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10634:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10635:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10636:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10637:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10638:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10639:  Exiting.\n",lval,linei, i,line,iv,j);fflush(ficlog);
1.238     brouard  10640:          return 1;
                   10641:        }
1.341     brouard  10642:        cotvar[j][ncovcol+nqv+iv][i]=(double)(lval);
1.238     brouard  10643:        strcpy(line,stra);
1.223     brouard  10644:       }/* end loop ntv */
1.225     brouard  10645:       
1.223     brouard  10646:       /* Statuses  at wave */
1.137     brouard  10647:       cutv(stra, strb, line, ' '); 
1.223     brouard  10648:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  10649:        lval=-1;
1.136     brouard  10650:       }else{
1.238     brouard  10651:        errno=0;
                   10652:        lval=strtol(strb,&endptr,10); 
                   10653:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
1.347   ! brouard  10654:        if( strb[0]=='\0' || (*endptr != '\0' )){
        !          10655:          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);
        !          10656:          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);
        !          10657:          return 1;
        !          10658:        }else if( lval==0 || lval > nlstate+ndeath){
        !          10659:          printf("Error in data around '%s' at line number %d for individual %d, '%s'\n Should be a state at wave %d. A state should be 1 to %d and not %d.\n Fix your data file '%s'!  Exiting.\n", strb, linei,i,line,j,nlstate+ndeath, lval, datafile);fflush(stdout);
        !          10660:          fprintf(ficlog,"Error in data around '%s' at line number %d for individual %d, '%s'\n Should be a state at wave %d. A state should be 1 to %d and not %d.\n Fix your data file '%s'!  Exiting.\n", strb, linei,i,line,j,nlstate+ndeath, lval, datafile); fflush(ficlog);
1.238     brouard  10661:          return 1;
                   10662:        }
1.136     brouard  10663:       }
1.225     brouard  10664:       
1.136     brouard  10665:       s[j][i]=lval;
1.225     brouard  10666:       
1.223     brouard  10667:       /* Date of Interview */
1.136     brouard  10668:       strcpy(line,stra);
                   10669:       cutv(stra, strb,line,' ');
1.169     brouard  10670:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10671:       }
1.169     brouard  10672:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  10673:        month=99;
                   10674:        year=9999;
1.136     brouard  10675:       }else{
1.225     brouard  10676:        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);
                   10677:        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);
                   10678:        return 1;
1.136     brouard  10679:       }
                   10680:       anint[j][i]= (double) year; 
1.302     brouard  10681:       mint[j][i]= (double)month;
                   10682:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   10683:       /*       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]); */
                   10684:       /*       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]); */
                   10685:       /* } */
1.136     brouard  10686:       strcpy(line,stra);
1.223     brouard  10687:     } /* End loop on waves */
1.225     brouard  10688:     
1.223     brouard  10689:     /* Date of death */
1.136     brouard  10690:     cutv(stra, strb,line,' '); 
1.169     brouard  10691:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10692:     }
1.169     brouard  10693:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  10694:       month=99;
                   10695:       year=9999;
                   10696:     }else{
1.141     brouard  10697:       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  10698:       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);
                   10699:       return 1;
1.136     brouard  10700:     }
                   10701:     andc[i]=(double) year; 
                   10702:     moisdc[i]=(double) month; 
                   10703:     strcpy(line,stra);
                   10704:     
1.223     brouard  10705:     /* Date of birth */
1.136     brouard  10706:     cutv(stra, strb,line,' '); 
1.169     brouard  10707:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10708:     }
1.169     brouard  10709:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  10710:       month=99;
                   10711:       year=9999;
                   10712:     }else{
1.141     brouard  10713:       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);
                   10714:       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  10715:       return 1;
1.136     brouard  10716:     }
                   10717:     if (year==9999) {
1.141     brouard  10718:       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);
                   10719:       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  10720:       return 1;
                   10721:       
1.136     brouard  10722:     }
                   10723:     annais[i]=(double)(year);
1.302     brouard  10724:     moisnais[i]=(double)(month);
                   10725:     for (j=1;j<=maxwav;j++){
                   10726:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   10727:        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]);
                   10728:        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]);
                   10729:       }
                   10730:     }
                   10731: 
1.136     brouard  10732:     strcpy(line,stra);
1.225     brouard  10733:     
1.223     brouard  10734:     /* Sample weight */
1.136     brouard  10735:     cutv(stra, strb,line,' '); 
                   10736:     errno=0;
                   10737:     dval=strtod(strb,&endptr); 
                   10738:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  10739:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   10740:       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  10741:       fflush(ficlog);
                   10742:       return 1;
                   10743:     }
                   10744:     weight[i]=dval; 
                   10745:     strcpy(line,stra);
1.225     brouard  10746:     
1.223     brouard  10747:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   10748:       cutv(stra, strb, line, ' '); 
                   10749:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  10750:        lval=-1;
1.311     brouard  10751:        coqvar[iv][i]=NAN; 
                   10752:        covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  10753:       }else{
1.225     brouard  10754:        errno=0;
                   10755:        /* what_kind_of_number(strb); */
                   10756:        dval=strtod(strb,&endptr);
                   10757:        /* if(strb != endptr && *endptr == '\0') */
                   10758:        /*   dval=dlval; */
                   10759:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10760:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10761:          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);
                   10762:          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);
                   10763:          return 1;
                   10764:        }
                   10765:        coqvar[iv][i]=dval; 
1.226     brouard  10766:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  10767:       }
                   10768:       strcpy(line,stra);
                   10769:     }/* end loop nqv */
1.136     brouard  10770:     
1.223     brouard  10771:     /* Covariate values */
1.136     brouard  10772:     for (j=ncovcol;j>=1;j--){
                   10773:       cutv(stra, strb,line,' '); 
1.223     brouard  10774:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  10775:        lval=-1;
1.136     brouard  10776:       }else{
1.225     brouard  10777:        errno=0;
                   10778:        lval=strtol(strb,&endptr,10); 
                   10779:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10780:          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);
                   10781:          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);
                   10782:          return 1;
                   10783:        }
1.136     brouard  10784:       }
                   10785:       if(lval <-1 || lval >1){
1.225     brouard  10786:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  10787:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   10788:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  10789:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10790:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10791:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  10792:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  10793:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  10794:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  10795:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  10796:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   10797:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  10798:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10799:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10800:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  10801:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  10802:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  10803:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  10804:        return 1;
1.136     brouard  10805:       }
                   10806:       covar[j][i]=(double)(lval);
                   10807:       strcpy(line,stra);
                   10808:     }  
                   10809:     lstra=strlen(stra);
1.225     brouard  10810:     
1.136     brouard  10811:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   10812:       stratrunc = &(stra[lstra-9]);
                   10813:       num[i]=atol(stratrunc);
                   10814:     }
                   10815:     else
                   10816:       num[i]=atol(stra);
                   10817:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   10818:       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;}*/
                   10819:     
                   10820:     i=i+1;
                   10821:   } /* End loop reading  data */
1.225     brouard  10822:   
1.136     brouard  10823:   *imax=i-1; /* Number of individuals */
                   10824:   fclose(fic);
1.225     brouard  10825:   
1.136     brouard  10826:   return (0);
1.164     brouard  10827:   /* endread: */
1.225     brouard  10828:   printf("Exiting readdata: ");
                   10829:   fclose(fic);
                   10830:   return (1);
1.223     brouard  10831: }
1.126     brouard  10832: 
1.234     brouard  10833: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  10834:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  10835:   while (*p2 == ' ')
1.234     brouard  10836:     p2++; 
                   10837:   /* while ((*p1++ = *p2++) !=0) */
                   10838:   /*   ; */
                   10839:   /* do */
                   10840:   /*   while (*p2 == ' ') */
                   10841:   /*     p2++; */
                   10842:   /* while (*p1++ == *p2++); */
                   10843:   *stri=p2; 
1.145     brouard  10844: }
                   10845: 
1.330     brouard  10846: int decoderesult( char resultline[], int nres)
1.230     brouard  10847: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   10848: {
1.235     brouard  10849:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  10850:   char resultsav[MAXLINE];
1.330     brouard  10851:   /* int resultmodel[MAXLINE]; */
1.334     brouard  10852:   /* int modelresult[MAXLINE]; */
1.230     brouard  10853:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   10854: 
1.234     brouard  10855:   removefirstspace(&resultline);
1.332     brouard  10856:   printf("decoderesult:%s\n",resultline);
1.230     brouard  10857: 
1.332     brouard  10858:   strcpy(resultsav,resultline);
1.342     brouard  10859:   /* printf("Decoderesult resultsav=\"%s\" resultline=\"%s\"\n", resultsav, resultline); */
1.230     brouard  10860:   if (strlen(resultsav) >1){
1.334     brouard  10861:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' in this resultline */
1.230     brouard  10862:   }
1.253     brouard  10863:   if(j == 0){ /* Resultline but no = */
                   10864:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   10865:     return (0);
                   10866:   }
1.234     brouard  10867:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
1.334     brouard  10868:     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);
                   10869:     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  10870:     /* return 1;*/
1.234     brouard  10871:   }
1.334     brouard  10872:   for(k=1; k<=j;k++){ /* Loop on any covariate of the RESULT LINE */
1.234     brouard  10873:     if(nbocc(resultsav,'=') >1){
1.318     brouard  10874:       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  10875:       /* 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  10876:       cutl(strc,strd,strb,'=');  /* strb:"V4=1" strc="1" strd="V4" */
1.332     brouard  10877:       /* If a blank, then strc="V4=" and strd='\0' */
                   10878:       if(strc[0]=='\0'){
                   10879:       printf("Error in resultline, probably a blank after the \"%s\", \"result:%s\", stra=\"%s\" resultsav=\"%s\"\n",strb,resultline, stra, resultsav);
                   10880:        fprintf(ficlog,"Error in resultline, probably a blank after the \"V%s=\", resultline=%s\n",strb,resultline);
                   10881:        return 1;
                   10882:       }
1.234     brouard  10883:     }else
                   10884:       cutl(strc,strd,resultsav,'=');
1.318     brouard  10885:     Tvalsel[k]=atof(strc); /* 1 */ /* Tvalsel of k is the float value of the kth covariate appearing in this result line */
1.234     brouard  10886:     
1.230     brouard  10887:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
1.318     brouard  10888:     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  10889:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   10890:     /* cptcovsel++;     */
                   10891:     if (nbocc(stra,'=') >0)
                   10892:       strcpy(resultsav,stra); /* and analyzes it */
                   10893:   }
1.235     brouard  10894:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  10895:   /* 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  10896:   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  10897:     if(Typevar[k1]==0){ /* Single covariate in model */
                   10898:       /* 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.234     brouard  10899:       match=0;
1.318     brouard  10900:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10901:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  10902:          modelresult[nres][k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.318     brouard  10903:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
1.234     brouard  10904:          break;
                   10905:        }
                   10906:       }
                   10907:       if(match == 0){
1.338     brouard  10908:        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]);
                   10909:        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  10910:        return 1;
1.234     brouard  10911:       }
1.332     brouard  10912:     }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*/
                   10913:       /* We feed resultmodel[k1]=k2; */
                   10914:       match=0;
                   10915:       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 */
                   10916:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  10917:          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  10918:          resultmodel[nres][k1]=k2; /* Added here */
1.342     brouard  10919:          /* printf("Decoderesult first modelresult[k2=%d]=%d (k1) V%d*AGE\n",k2,k1,Tvar[k1]); */
1.332     brouard  10920:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10921:          break;
                   10922:        }
                   10923:       }
                   10924:       if(match == 0){
1.338     brouard  10925:        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]);
                   10926:        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  10927:       return 1;
                   10928:       }
                   10929:     }else if(Typevar[k1]==2){ /* Product No age We want to get the position in the resultline of the product in the model line*/
                   10930:       /* resultmodel[nres][of such a Vn * Vm product k1] is not unique, so can't exist, we feed Tvard[k1][1] and [2] */ 
                   10931:       match=0;
1.342     brouard  10932:       /* 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  10933:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10934:        if(Tvardk[k1][1]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   10935:          /* modelresult[k2]=k1; */
1.342     brouard  10936:          /* printf("Decoderesult first Product modelresult[k2=%d]=%d (k1) V%d * \n",k2,k1,Tvarsel[k2]); */
1.332     brouard  10937:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10938:        }
                   10939:       }
                   10940:       if(match == 0){
1.338     brouard  10941:        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);
                   10942:        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  10943:        return 1;
                   10944:       }
                   10945:       match=0;
                   10946:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10947:        if(Tvardk[k1][2]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   10948:          /* modelresult[k2]=k1;*/
1.342     brouard  10949:          /* printf("Decoderesult second Product modelresult[k2=%d]=%d (k1) * V%d \n ",k2,k1,Tvarsel[k2]); */
1.332     brouard  10950:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10951:          break;
                   10952:        }
                   10953:       }
                   10954:       if(match == 0){
1.338     brouard  10955:        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);
                   10956:        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  10957:        return 1;
                   10958:       }
                   10959:     }/* End of testing */
1.333     brouard  10960:   }/* End loop cptcovt */
1.235     brouard  10961:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  10962:   /* Feeds resultmodel[nres][k1]=k2 for single covariate (k1) in the model equation */
1.334     brouard  10963:   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)
                   10964:                           * Loop on resultline variables: result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  10965:     match=0;
1.318     brouard  10966:     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  10967:       if(Typevar[k1]==0){ /* Single only */
1.237     brouard  10968:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4   */
1.330     brouard  10969:          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  10970:          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  10971:          ++match;
                   10972:        }
                   10973:       }
                   10974:     }
                   10975:     if(match == 0){
1.338     brouard  10976:       printf("Error in result line: variable V%d is missing in model; result: %s, model=1+age+%s\n",Tvarsel[k2], resultline, model);
                   10977:       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  10978:       return 1;
1.234     brouard  10979:     }else if(match > 1){
1.338     brouard  10980:       printf("Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
                   10981:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
1.310     brouard  10982:       return 1;
1.234     brouard  10983:     }
                   10984:   }
1.334     brouard  10985:   /* cptcovres=j /\* Number of variables in the resultline is equal to cptcovs and thus useless *\/     */
1.234     brouard  10986:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  10987:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.330     brouard  10988:   /* nres=1st result line: V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   10989:   /* 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*/
                   10990:   /* nres=2nd result line: V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.235     brouard  10991:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   10992:   /*    1 0 0 0 */
                   10993:   /*    2 1 0 0 */
                   10994:   /*    3 0 1 0 */ 
1.330     brouard  10995:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 (nres=2)*/
1.235     brouard  10996:   /*    5 0 0 1 */
1.330     brouard  10997:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 (nres=1)*/
1.235     brouard  10998:   /*    7 0 1 1 */
                   10999:   /*    8 1 1 1 */
1.237     brouard  11000:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   11001:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   11002:   /* V5*age V5 known which value for nres?  */
                   11003:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.334     brouard  11004:   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.
                   11005:                                                   * loop on position k1 in the MODEL LINE */
1.331     brouard  11006:     /* k counting number of combination of single dummies in the equation model */
                   11007:     /* k4 counting single dummies in the equation model */
                   11008:     /* k4q counting single quantitatives in the equation model */
1.344     brouard  11009:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Dummy and Single, fixed or timevarying, k1 is sorting according to MODEL, but k3 to resultline */
1.334     brouard  11010:        /* 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  11011:       /* 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  11012:       /* Value in the (current nres) resultline of the variable at the k1th position in the model equation resultmodel[nres][k1]= k3 */
1.332     brouard  11013:       /* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline                        */
                   11014:       /*      k3 is the position in the nres result line of the k1th variable of the model equation                                  */
                   11015:       /* Tvarsel[k3]: Name of the variable at the k3th position in the result line.                                                  */
                   11016:       /* Tvalsel[k3]: Value of the variable at the k3th position in the result line.                                                 */
                   11017:       /* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline                   */
1.334     brouard  11018:       /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline                     */
1.332     brouard  11019:       /* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line                                        */
1.330     brouard  11020:       /* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line                                                      */
1.332     brouard  11021:       k3= resultmodel[nres][k1]; /* From position k1 in model get position k3 in result line */
                   11022:       /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   11023:       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  11024:       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  11025:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][Name]=Value; stores the value into the name of the variable. */
1.332     brouard  11026:       /* Tinvresult[nres][4]=1 */
1.334     brouard  11027:       /* Tresult[nres][k4+1]=Tvalsel[k3];/\* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) *\/ */
                   11028:       Tresult[nres][k3]=Tvalsel[k3];/* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) */
                   11029:       /* Tvresult[nres][k4+1]=(int)Tvarsel[k3];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   11030:       Tvresult[nres][k3]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
1.237     brouard  11031:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.334     brouard  11032:       precov[nres][k1]=Tvalsel[k3]; /* Value from resultline of the variable at the k1 position in the model */
1.342     brouard  11033:       /* 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  11034:       k4++;;
1.331     brouard  11035:     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Quantitative and single */
1.330     brouard  11036:       /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 */
1.332     brouard  11037:       /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline                                 */
1.330     brouard  11038:       /* Tqinvresult[nres][Name of a quantitative variable]= value of the variable in the result line                                                      */
1.332     brouard  11039:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 5 =k3q */
                   11040:       k2q=(int)Tvarsel[k3q]; /*  Name of variable at k3q th position in the resultline */
                   11041:       /* Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  11042:       /* Tqresult[nres][k4q+1]=Tvalsel[k3q]; /\* Tqresult[nres][1]=25.1 *\/ */
                   11043:       /* Tvresult[nres][k4q+1]=(int)Tvarsel[k3q];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   11044:       /* Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /\* Tvqresult[nres][1]=5 *\/ */
                   11045:       Tqresult[nres][k3q]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   11046:       Tvresult[nres][k3q]=(int)Tvarsel[k3q];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   11047:       Tvqresult[nres][k3q]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
1.237     brouard  11048:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.330     brouard  11049:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.332     brouard  11050:       precov[nres][k1]=Tvalsel[k3q];
1.342     brouard  11051:       /* 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  11052:       k4q++;;
1.331     brouard  11053:     }else if( Dummy[k1]==2 ){ /* For dummy with age product */
                   11054:       /* Tvar[k1]; */ /* Age variable */
1.332     brouard  11055:       /* Wrong we want the value of variable name Tvar[k1] */
                   11056:       
                   11057:       k3= resultmodel[nres][k1]; /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
1.331     brouard  11058:       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  11059:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][4]=1 */
1.332     brouard  11060:       precov[nres][k1]=Tvalsel[k3];
1.342     brouard  11061:       /* 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  11062:     }else if( Dummy[k1]==3 ){ /* For quant with age product */
1.332     brouard  11063:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 25.1=k3q */
1.331     brouard  11064:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  11065:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* TinvDoQresult[nres][5]=25.1 */
1.332     brouard  11066:       precov[nres][k1]=Tvalsel[k3q];
1.342     brouard  11067:       /* 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  11068:     }else if(Typevar[k1]==2 ){ /* For product quant or dummy (not with age) */
1.332     brouard  11069:       precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
1.342     brouard  11070:       /* 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  11071:     }else{
1.332     brouard  11072:       printf("Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
                   11073:       fprintf(ficlog,"Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
1.235     brouard  11074:     }
                   11075:   }
1.234     brouard  11076:   
1.334     brouard  11077:   TKresult[nres]=++k; /* Number of combinations of dummies for the nresult and the model =Tvalsel[k3]*pow(2,k4) + 1*/
1.230     brouard  11078:   return (0);
                   11079: }
1.235     brouard  11080: 
1.230     brouard  11081: int decodemodel( char model[], int lastobs)
                   11082:  /**< This routine decodes the model and returns:
1.224     brouard  11083:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   11084:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   11085:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   11086:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   11087:        * - cptcovage number of covariates with age*products =2
                   11088:        * - cptcovs number of simple covariates
1.339     brouard  11089:        * ncovcolt=ncovcol+nqv+ntv+nqtv total of covariates in the data, not in the model equation
1.224     brouard  11090:        * - 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  11091:        *     which is a new column after the 9 (ncovcol+nqv+ntv+nqtv) variables. 
1.319     brouard  11092:        * - if k is a product Vn*Vm, covar[k][i] is filled with correct values for each individual
1.224     brouard  11093:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   11094:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   11095:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   11096:        */
1.319     brouard  11097: /* 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  11098: {
1.238     brouard  11099:   int i, j, k, ks, v;
1.227     brouard  11100:   int  j1, k1, k2, k3, k4;
1.136     brouard  11101:   char modelsav[80];
1.145     brouard  11102:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  11103:   char *strpt;
1.136     brouard  11104: 
1.145     brouard  11105:   /*removespace(model);*/
1.136     brouard  11106:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  11107:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  11108:     if (strstr(model,"AGE") !=0){
1.192     brouard  11109:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   11110:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  11111:       return 1;
                   11112:     }
1.141     brouard  11113:     if (strstr(model,"v") !=0){
1.338     brouard  11114:       printf("Error. 'v' must be in upper case 'V' model=1+age+%s ",model);
                   11115:       fprintf(ficlog,"Error. 'v' must be in upper case model=1+age+%s ",model);fflush(ficlog);
1.141     brouard  11116:       return 1;
                   11117:     }
1.187     brouard  11118:     strcpy(modelsav,model); 
                   11119:     if ((strpt=strstr(model,"age*age")) !=0){
1.338     brouard  11120:       printf(" strpt=%s, model=1+age+%s\n",strpt, model);
1.187     brouard  11121:       if(strpt != model){
1.338     brouard  11122:        printf("Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  11123:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  11124:  corresponding column of parameters.\n",model);
1.338     brouard  11125:        fprintf(ficlog,"Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  11126:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  11127:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  11128:        return 1;
1.225     brouard  11129:       }
1.187     brouard  11130:       nagesqr=1;
                   11131:       if (strstr(model,"+age*age") !=0)
1.234     brouard  11132:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  11133:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  11134:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  11135:       else 
1.234     brouard  11136:        substrchaine(modelsav, model, "age*age");
1.187     brouard  11137:     }else
                   11138:       nagesqr=0;
                   11139:     if (strlen(modelsav) >1){
                   11140:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   11141:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224     brouard  11142:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  11143:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  11144:                     * cst, age and age*age 
                   11145:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   11146:       /* including age products which are counted in cptcovage.
                   11147:        * but the covariates which are products must be treated 
                   11148:        * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  11149:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   11150:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.225     brouard  11151:       
                   11152:       
1.187     brouard  11153:       /*   Design
                   11154:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   11155:        *  <          ncovcol=8                >
                   11156:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   11157:        *   k=  1    2      3       4     5       6      7        8
                   11158:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
1.345     brouard  11159:        *  covar[k,i], are for fixed covariates, value of kth covariate if not including age for individual i:
1.224     brouard  11160:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   11161:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  11162:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   11163:        *  Tage[++cptcovage]=k
1.345     brouard  11164:        *       if products, new covar are created after ncovcol + nqv (quanti fixed) with k1
1.187     brouard  11165:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   11166:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   11167:        *  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
                   11168:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   11169:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   11170:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
1.345     brouard  11171:        *  <          ncovcol=8  8 fixed covariate. Additional starts at 9 (V5*V6) and 10(V7*V8)              >
1.187     brouard  11172:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   11173:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
1.345     brouard  11174:        *     Tvard[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   11175:        * p Tvar[1]@12={2,   1,     3,      3,   9,     10,     8,       8}
1.187     brouard  11176:        * p Tprod[1]@2={                         6, 5}
                   11177:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   11178:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   11179:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1.319     brouard  11180:        *How to reorganize? Tvars(orted)
1.187     brouard  11181:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   11182:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   11183:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   11184:        * Struct []
                   11185:        */
1.225     brouard  11186:       
1.187     brouard  11187:       /* This loop fills the array Tvar from the string 'model'.*/
                   11188:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   11189:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   11190:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   11191:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   11192:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   11193:       /*       k=1 Tvar[1]=2 (from V2) */
                   11194:       /*       k=5 Tvar[5] */
                   11195:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  11196:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  11197:       /*       } */
1.198     brouard  11198:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  11199:       /*
                   11200:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  11201:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   11202:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   11203:       }
1.187     brouard  11204:       cptcovage=0;
1.319     brouard  11205:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model line */
                   11206:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' cutl from left to right
                   11207:                                         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" */
                   11208:        if (nbocc(modelsav,'+')==0)
                   11209:          strcpy(strb,modelsav); /* and analyzes it */
1.234     brouard  11210:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   11211:        /*scanf("%d",i);*/
1.319     brouard  11212:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V5*age+ V4+V3*age strb=V3*age */
                   11213:          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  11214:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   11215:            /* covar is not filled and then is empty */
                   11216:            cptcovprod--;
                   11217:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
1.319     brouard  11218:            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  11219:            Typevar[k]=1;  /* 1 for age product */
1.319     brouard  11220:            cptcovage++; /* Counts the number of covariates which include age as a product */
                   11221:            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  11222:            /*printf("stre=%s ", stre);*/
                   11223:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   11224:            cptcovprod--;
                   11225:            cutl(stre,strb,strc,'V');
                   11226:            Tvar[k]=atoi(stre);
                   11227:            Typevar[k]=1;  /* 1 for age product */
                   11228:            cptcovage++;
                   11229:            Tage[cptcovage]=k;
                   11230:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   11231:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   11232:            cptcovn++;
                   11233:            cptcovprodnoage++;k1++;
                   11234:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
1.339     brouard  11235:            Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* ncovcolt+k1; For model-covariate k tells which data-covariate to use but
1.234     brouard  11236:                                                because this model-covariate is a construction we invent a new column
                   11237:                                                which is after existing variables ncovcol+nqv+ntv+nqtv + k1
1.335     brouard  11238:                                                If already ncovcol=4 and model= V2 + V1 + V1*V4 + age*V3 + V3*V2
1.319     brouard  11239:                                                thus after V4 we invent V5 and V6 because age*V3 will be computed in 4
1.339     brouard  11240:                                                Tvar[3=V1*V4]=4+1=5 Tvar[5=V3*V2]=4 + 2= 6, Tvar[4=age*V3]=3 etc */
1.335     brouard  11241:            /* Please remark that the new variables are model dependent */
                   11242:            /* If we have 4 variable but the model uses only 3, like in
                   11243:             * model= V1 + age*V1 + V2 + V3 + age*V2 + age*V3 + V1*V2 + V1*V3
                   11244:             *  k=     1     2       3   4     5        6        7       8
                   11245:             * Tvar[k]=1     1       2   3     2        3       (5       6) (and not 4 5 because of V4 missing)
                   11246:             * Tage[kk]    [1]= 2           [2]=5      [3]=6                  kk=1 to cptcovage=3
                   11247:             * Tvar[Tage[kk]][1]=2          [2]=2      [3]=3
                   11248:             */
1.339     brouard  11249:            Typevar[k]=2;  /* 2 for product */
1.234     brouard  11250:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   11251:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
1.319     brouard  11252:            Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 */
1.234     brouard  11253:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
1.330     brouard  11254:            Tvardk[k][1] =atoi(strc); /* m 1 for V1*/
1.234     brouard  11255:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
1.330     brouard  11256:            Tvardk[k][2] =atoi(stre); /* n 4 for V4*/
1.234     brouard  11257:            k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   11258:            /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   11259:            /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
1.225     brouard  11260:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
1.234     brouard  11261:            /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
1.339     brouard  11262:            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 */
                   11263:              for (i=1; i<=lastobs;i++){/* For fixed product */
1.234     brouard  11264:              /* Computes the new covariate which is a product of
                   11265:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
1.339     brouard  11266:              covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   11267:              }
                   11268:            } /*End of FixedV */
1.234     brouard  11269:          } /* End age is not in the model */
                   11270:        } /* End if model includes a product */
1.319     brouard  11271:        else { /* not a product */
1.234     brouard  11272:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   11273:          /*  scanf("%d",i);*/
                   11274:          cutl(strd,strc,strb,'V');
                   11275:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   11276:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   11277:          Tvar[k]=atoi(strd);
                   11278:          Typevar[k]=0;  /* 0 for simple covariates */
                   11279:        }
                   11280:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  11281:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  11282:                                  scanf("%d",i);*/
1.187     brouard  11283:       } /* end of loop + on total covariates */
                   11284:     } /* end if strlen(modelsave == 0) age*age might exist */
                   11285:   } /* end if strlen(model == 0) */
1.136     brouard  11286:   
                   11287:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   11288:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  11289:   
1.136     brouard  11290:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  11291:      printf("cptcovprod=%d ", cptcovprod);
                   11292:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   11293:      scanf("%d ",i);*/
                   11294: 
                   11295: 
1.230     brouard  11296: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   11297:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  11298: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   11299:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   11300:    k =           1    2   3     4       5       6      7      8        9
                   11301:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
1.319     brouard  11302:    Typevar[k]=   0    0   0     2       1       0      2      1        0
1.227     brouard  11303:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   11304:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   11305:          Tmodelind[combination of covar]=k;
1.225     brouard  11306: */  
                   11307: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  11308:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  11309:   /* 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  11310:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.318     brouard  11311:   printf("Model=1+age+%s\n\
1.227     brouard  11312: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   11313: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   11314: 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  11315:   fprintf(ficlog,"Model=1+age+%s\n\
1.227     brouard  11316: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   11317: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   11318: 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  11319:   for(k=-1;k<=NCOVMAX; k++){ Fixed[k]=0; Dummy[k]=0;}
                   11320:   for(k=1;k<=NCOVMAX; k++){TvarFind[k]=0; TvarVind[k]=0;}
1.343     brouard  11321:   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  11322:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  11323:       Fixed[k]= 0;
                   11324:       Dummy[k]= 0;
1.225     brouard  11325:       ncoveff++;
1.232     brouard  11326:       ncovf++;
1.234     brouard  11327:       nsd++;
                   11328:       modell[k].maintype= FTYPE;
                   11329:       TvarsD[nsd]=Tvar[k];
                   11330:       TvarsDind[nsd]=k;
1.330     brouard  11331:       TnsdVar[Tvar[k]]=nsd;
1.234     brouard  11332:       TvarF[ncovf]=Tvar[k];
                   11333:       TvarFind[ncovf]=k;
                   11334:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   11335:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.339     brouard  11336:     /* }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /\* Product of fixed dummy (<=ncovcol) covariates For a fixed product k is higher than ncovcol *\/ */
                   11337:     }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  11338:       Fixed[k]= 0;
                   11339:       Dummy[k]= 0;
                   11340:       ncoveff++;
                   11341:       ncovf++;
                   11342:       modell[k].maintype= FTYPE;
                   11343:       TvarF[ncovf]=Tvar[k];
1.330     brouard  11344:       /* TnsdVar[Tvar[k]]=nsd; */ /* To be done */
1.234     brouard  11345:       TvarFind[ncovf]=k;
1.230     brouard  11346:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  11347:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.240     brouard  11348:     }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  11349:       Fixed[k]= 0;
                   11350:       Dummy[k]= 1;
1.230     brouard  11351:       nqfveff++;
1.234     brouard  11352:       modell[k].maintype= FTYPE;
                   11353:       modell[k].subtype= FQ;
                   11354:       nsq++;
1.334     brouard  11355:       TvarsQ[nsq]=Tvar[k]; /* Gives the variable name (extended to products) of first nsq simple quantitative covariates (fixed or time vary see below */
                   11356:       TvarsQind[nsq]=k;    /* Gives the position in the model equation of the first nsq simple quantitative covariates (fixed or time vary) */
1.232     brouard  11357:       ncovf++;
1.234     brouard  11358:       TvarF[ncovf]=Tvar[k];
                   11359:       TvarFind[ncovf]=k;
1.231     brouard  11360:       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  11361:       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  11362:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.339     brouard  11363:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11364:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11365:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11366:       ncovvt++;
                   11367:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11368:       TvarVVind[ncovvt]=k;    /*  TvarVVind[1]=2 (second position in the model equation  */
                   11369: 
1.227     brouard  11370:       Fixed[k]= 1;
                   11371:       Dummy[k]= 0;
1.225     brouard  11372:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  11373:       modell[k].maintype= VTYPE;
                   11374:       modell[k].subtype= VD;
                   11375:       nsd++;
                   11376:       TvarsD[nsd]=Tvar[k];
                   11377:       TvarsDind[nsd]=k;
1.330     brouard  11378:       TnsdVar[Tvar[k]]=nsd; /* To be verified */
1.234     brouard  11379:       ncovv++; /* Only simple time varying variables */
                   11380:       TvarV[ncovv]=Tvar[k];
1.242     brouard  11381:       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  11382:       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 */
                   11383:       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  11384:       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);
                   11385:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  11386:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.339     brouard  11387:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11388:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11389:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11390:       ncovvt++;
                   11391:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11392:       TvarVVind[ncovvt]=k;  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11393:       
1.234     brouard  11394:       Fixed[k]= 1;
                   11395:       Dummy[k]= 1;
                   11396:       nqtveff++;
                   11397:       modell[k].maintype= VTYPE;
                   11398:       modell[k].subtype= VQ;
                   11399:       ncovv++; /* Only simple time varying variables */
                   11400:       nsq++;
1.334     brouard  11401:       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) */
                   11402:       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  11403:       TvarV[ncovv]=Tvar[k];
1.242     brouard  11404:       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  11405:       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 */
                   11406:       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  11407:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   11408:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
1.342     brouard  11409:       /* 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); */
                   11410:       /* printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv); */
1.227     brouard  11411:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  11412:       ncova++;
                   11413:       TvarA[ncova]=Tvar[k];
                   11414:       TvarAind[ncova]=k;
1.231     brouard  11415:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  11416:        Fixed[k]= 2;
                   11417:        Dummy[k]= 2;
                   11418:        modell[k].maintype= ATYPE;
                   11419:        modell[k].subtype= APFD;
                   11420:        /* ncoveff++; */
1.227     brouard  11421:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  11422:        Fixed[k]= 2;
                   11423:        Dummy[k]= 3;
                   11424:        modell[k].maintype= ATYPE;
                   11425:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   11426:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  11427:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  11428:        Fixed[k]= 3;
                   11429:        Dummy[k]= 2;
                   11430:        modell[k].maintype= ATYPE;
                   11431:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   11432:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  11433:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  11434:        Fixed[k]= 3;
                   11435:        Dummy[k]= 3;
                   11436:        modell[k].maintype= ATYPE;
                   11437:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   11438:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  11439:       }
1.339     brouard  11440:     }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  */
                   11441:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11442:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11443:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11444:       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 */
                   11445:       ncovvt++;
                   11446:       TvarVV[ncovvt]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
                   11447:       TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   11448:       ncovvt++;
                   11449:       TvarVV[ncovvt]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
                   11450:       TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   11451: 
                   11452: 
                   11453:       if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   11454:        if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
1.240     brouard  11455:          Fixed[k]= 1;
                   11456:          Dummy[k]= 0;
                   11457:          modell[k].maintype= FTYPE;
                   11458:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
                   11459:          ncovf++; /* Fixed variables without age */
                   11460:          TvarF[ncovf]=Tvar[k];
                   11461:          TvarFind[ncovf]=k;
1.339     brouard  11462:        }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
                   11463:          Fixed[k]= 0;  /* Fixed product */
1.240     brouard  11464:          Dummy[k]= 1;
                   11465:          modell[k].maintype= FTYPE;
                   11466:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
                   11467:          ncovf++; /* Varying variables without age */
                   11468:          TvarF[ncovf]=Tvar[k];
                   11469:          TvarFind[ncovf]=k;
1.339     brouard  11470:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
1.240     brouard  11471:          Fixed[k]= 1;
                   11472:          Dummy[k]= 0;
                   11473:          modell[k].maintype= VTYPE;
                   11474:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
                   11475:          ncovv++; /* Varying variables without age */
1.339     brouard  11476:          TvarV[ncovv]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
                   11477:          TvarVind[ncovv]=k;/* TvarVind[1]=5 */ 
                   11478:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
1.240     brouard  11479:          Fixed[k]= 1;
                   11480:          Dummy[k]= 1;
                   11481:          modell[k].maintype= VTYPE;
                   11482:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
                   11483:          ncovv++; /* Varying variables without age */
                   11484:          TvarV[ncovv]=Tvar[k];
                   11485:          TvarVind[ncovv]=k;
                   11486:        }
1.339     brouard  11487:       }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   11488:        if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
                   11489:          Fixed[k]= 0;  /*  Fixed product */
1.240     brouard  11490:          Dummy[k]= 1;
                   11491:          modell[k].maintype= FTYPE;
                   11492:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
                   11493:          ncovf++; /* Fixed variables without age */
                   11494:          TvarF[ncovf]=Tvar[k];
                   11495:          TvarFind[ncovf]=k;
1.339     brouard  11496:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
1.240     brouard  11497:          Fixed[k]= 1;
                   11498:          Dummy[k]= 1;
                   11499:          modell[k].maintype= VTYPE;
                   11500:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
                   11501:          ncovv++; /* Varying variables without age */
                   11502:          TvarV[ncovv]=Tvar[k];
                   11503:          TvarVind[ncovv]=k;
1.339     brouard  11504:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
1.240     brouard  11505:          Fixed[k]= 1;
                   11506:          Dummy[k]= 1;
                   11507:          modell[k].maintype= VTYPE;
                   11508:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
                   11509:          ncovv++; /* Varying variables without age */
                   11510:          TvarV[ncovv]=Tvar[k];
                   11511:          TvarVind[ncovv]=k;
                   11512:          ncovv++; /* Varying variables without age */
                   11513:          TvarV[ncovv]=Tvar[k];
                   11514:          TvarVind[ncovv]=k;
                   11515:        }
1.339     brouard  11516:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
1.240     brouard  11517:        if(Tvard[k1][2] <=ncovcol){
                   11518:          Fixed[k]= 1;
                   11519:          Dummy[k]= 1;
                   11520:          modell[k].maintype= VTYPE;
                   11521:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
                   11522:          ncovv++; /* Varying variables without age */
                   11523:          TvarV[ncovv]=Tvar[k];
                   11524:          TvarVind[ncovv]=k;
                   11525:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   11526:          Fixed[k]= 1;
                   11527:          Dummy[k]= 1;
                   11528:          modell[k].maintype= VTYPE;
                   11529:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
                   11530:          ncovv++; /* Varying variables without age */
                   11531:          TvarV[ncovv]=Tvar[k];
                   11532:          TvarVind[ncovv]=k;
                   11533:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   11534:          Fixed[k]= 1;
                   11535:          Dummy[k]= 0;
                   11536:          modell[k].maintype= VTYPE;
                   11537:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
                   11538:          ncovv++; /* Varying variables without age */
                   11539:          TvarV[ncovv]=Tvar[k];
                   11540:          TvarVind[ncovv]=k;
                   11541:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   11542:          Fixed[k]= 1;
                   11543:          Dummy[k]= 1;
                   11544:          modell[k].maintype= VTYPE;
                   11545:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
                   11546:          ncovv++; /* Varying variables without age */
                   11547:          TvarV[ncovv]=Tvar[k];
                   11548:          TvarVind[ncovv]=k;
                   11549:        }
1.339     brouard  11550:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
1.240     brouard  11551:        if(Tvard[k1][2] <=ncovcol){
                   11552:          Fixed[k]= 1;
                   11553:          Dummy[k]= 1;
                   11554:          modell[k].maintype= VTYPE;
                   11555:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
                   11556:          ncovv++; /* Varying variables without age */
                   11557:          TvarV[ncovv]=Tvar[k];
                   11558:          TvarVind[ncovv]=k;
                   11559:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   11560:          Fixed[k]= 1;
                   11561:          Dummy[k]= 1;
                   11562:          modell[k].maintype= VTYPE;
                   11563:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
                   11564:          ncovv++; /* Varying variables without age */
                   11565:          TvarV[ncovv]=Tvar[k];
                   11566:          TvarVind[ncovv]=k;
                   11567:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   11568:          Fixed[k]= 1;
                   11569:          Dummy[k]= 1;
                   11570:          modell[k].maintype= VTYPE;
                   11571:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
                   11572:          ncovv++; /* Varying variables without age */
                   11573:          TvarV[ncovv]=Tvar[k];
                   11574:          TvarVind[ncovv]=k;
                   11575:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   11576:          Fixed[k]= 1;
                   11577:          Dummy[k]= 1;
                   11578:          modell[k].maintype= VTYPE;
                   11579:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
                   11580:          ncovv++; /* Varying variables without age */
                   11581:          TvarV[ncovv]=Tvar[k];
                   11582:          TvarVind[ncovv]=k;
                   11583:        }
1.227     brouard  11584:       }else{
1.240     brouard  11585:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   11586:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   11587:       } /*end k1*/
1.225     brouard  11588:     }else{
1.226     brouard  11589:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   11590:       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  11591:     }
1.342     brouard  11592:     /* 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]); */
                   11593:     /* printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype); */
1.227     brouard  11594:     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]);
                   11595:   }
                   11596:   /* Searching for doublons in the model */
                   11597:   for(k1=1; k1<= cptcovt;k1++){
                   11598:     for(k2=1; k2 <k1;k2++){
1.285     brouard  11599:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   11600:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  11601:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   11602:          if(Tvar[k1]==Tvar[k2]){
1.338     brouard  11603:            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]);
                   11604:            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  11605:            return(1);
                   11606:          }
                   11607:        }else if (Typevar[k1] ==2){
                   11608:          k3=Tposprod[k1];
                   11609:          k4=Tposprod[k2];
                   11610:          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  11611:            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]]);
                   11612:            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  11613:            return(1);
                   11614:          }
                   11615:        }
1.227     brouard  11616:       }
                   11617:     }
1.225     brouard  11618:   }
                   11619:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   11620:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  11621:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   11622:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.137     brouard  11623:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  11624:   /*endread:*/
1.225     brouard  11625:   printf("Exiting decodemodel: ");
                   11626:   return (1);
1.136     brouard  11627: }
                   11628: 
1.169     brouard  11629: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  11630: {/* Check ages at death */
1.136     brouard  11631:   int i, m;
1.218     brouard  11632:   int firstone=0;
                   11633:   
1.136     brouard  11634:   for (i=1; i<=imx; i++) {
                   11635:     for(m=2; (m<= maxwav); m++) {
                   11636:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   11637:        anint[m][i]=9999;
1.216     brouard  11638:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   11639:          s[m][i]=-1;
1.136     brouard  11640:       }
                   11641:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  11642:        *nberr = *nberr + 1;
1.218     brouard  11643:        if(firstone == 0){
                   11644:          firstone=1;
1.260     brouard  11645:        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  11646:        }
1.262     brouard  11647:        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  11648:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  11649:       }
                   11650:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  11651:        (*nberr)++;
1.259     brouard  11652:        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  11653:        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  11654:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  11655:       }
                   11656:     }
                   11657:   }
                   11658: 
                   11659:   for (i=1; i<=imx; i++)  {
                   11660:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   11661:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  11662:       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  11663:        if (s[m][i] >= nlstate+1) {
1.169     brouard  11664:          if(agedc[i]>0){
                   11665:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  11666:              agev[m][i]=agedc[i];
1.214     brouard  11667:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  11668:            }else {
1.136     brouard  11669:              if ((int)andc[i]!=9999){
                   11670:                nbwarn++;
                   11671:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   11672:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   11673:                agev[m][i]=-1;
                   11674:              }
                   11675:            }
1.169     brouard  11676:          } /* agedc > 0 */
1.214     brouard  11677:        } /* end if */
1.136     brouard  11678:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   11679:                                 years but with the precision of a month */
                   11680:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   11681:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   11682:            agev[m][i]=1;
                   11683:          else if(agev[m][i] < *agemin){ 
                   11684:            *agemin=agev[m][i];
                   11685:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   11686:          }
                   11687:          else if(agev[m][i] >*agemax){
                   11688:            *agemax=agev[m][i];
1.156     brouard  11689:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  11690:          }
                   11691:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   11692:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  11693:        } /* en if 9*/
1.136     brouard  11694:        else { /* =9 */
1.214     brouard  11695:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  11696:          agev[m][i]=1;
                   11697:          s[m][i]=-1;
                   11698:        }
                   11699:       }
1.214     brouard  11700:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  11701:        agev[m][i]=1;
1.214     brouard  11702:       else{
                   11703:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   11704:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   11705:        agev[m][i]=0;
                   11706:       }
                   11707:     } /* End for lastpass */
                   11708:   }
1.136     brouard  11709:     
                   11710:   for (i=1; i<=imx; i++)  {
                   11711:     for(m=firstpass; (m<=lastpass); m++){
                   11712:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  11713:        (*nberr)++;
1.136     brouard  11714:        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);     
                   11715:        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);     
                   11716:        return 1;
                   11717:       }
                   11718:     }
                   11719:   }
                   11720: 
                   11721:   /*for (i=1; i<=imx; i++){
                   11722:   for (m=firstpass; (m<lastpass); m++){
                   11723:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   11724: }
                   11725: 
                   11726: }*/
                   11727: 
                   11728: 
1.139     brouard  11729:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   11730:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  11731: 
                   11732:   return (0);
1.164     brouard  11733:  /* endread:*/
1.136     brouard  11734:     printf("Exiting calandcheckages: ");
                   11735:     return (1);
                   11736: }
                   11737: 
1.172     brouard  11738: #if defined(_MSC_VER)
                   11739: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   11740: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   11741: //#include "stdafx.h"
                   11742: //#include <stdio.h>
                   11743: //#include <tchar.h>
                   11744: //#include <windows.h>
                   11745: //#include <iostream>
                   11746: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   11747: 
                   11748: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   11749: 
                   11750: BOOL IsWow64()
                   11751: {
                   11752:        BOOL bIsWow64 = FALSE;
                   11753: 
                   11754:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   11755:        //  (HANDLE, PBOOL);
                   11756: 
                   11757:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   11758: 
                   11759:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   11760:        const char funcName[] = "IsWow64Process";
                   11761:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   11762:                GetProcAddress(module, funcName);
                   11763: 
                   11764:        if (NULL != fnIsWow64Process)
                   11765:        {
                   11766:                if (!fnIsWow64Process(GetCurrentProcess(),
                   11767:                        &bIsWow64))
                   11768:                        //throw std::exception("Unknown error");
                   11769:                        printf("Unknown error\n");
                   11770:        }
                   11771:        return bIsWow64 != FALSE;
                   11772: }
                   11773: #endif
1.177     brouard  11774: 
1.191     brouard  11775: void syscompilerinfo(int logged)
1.292     brouard  11776: {
                   11777: #include <stdint.h>
                   11778: 
                   11779:   /* #include "syscompilerinfo.h"*/
1.185     brouard  11780:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   11781:    /* /GS /W3 /Gy
                   11782:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   11783:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   11784:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  11785:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   11786:    */ 
                   11787:    /* 64 bits */
1.185     brouard  11788:    /*
                   11789:      /GS /W3 /Gy
                   11790:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   11791:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   11792:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   11793:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   11794:    /* Optimization are useless and O3 is slower than O2 */
                   11795:    /*
                   11796:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   11797:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   11798:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   11799:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   11800:    */
1.186     brouard  11801:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  11802:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   11803:       /PDB:"visual studio
                   11804:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   11805:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   11806:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   11807:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   11808:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   11809:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   11810:       uiAccess='false'"
                   11811:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   11812:       /NOLOGO /TLBID:1
                   11813:    */
1.292     brouard  11814: 
                   11815: 
1.177     brouard  11816: #if defined __INTEL_COMPILER
1.178     brouard  11817: #if defined(__GNUC__)
                   11818:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   11819: #endif
1.177     brouard  11820: #elif defined(__GNUC__) 
1.179     brouard  11821: #ifndef  __APPLE__
1.174     brouard  11822: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  11823: #endif
1.177     brouard  11824:    struct utsname sysInfo;
1.178     brouard  11825:    int cross = CROSS;
                   11826:    if (cross){
                   11827:           printf("Cross-");
1.191     brouard  11828:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  11829:    }
1.174     brouard  11830: #endif
                   11831: 
1.191     brouard  11832:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  11833: #if defined(__clang__)
1.191     brouard  11834:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  11835: #endif
                   11836: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  11837:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  11838: #endif
                   11839: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  11840:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  11841: #endif
                   11842: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  11843:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  11844: #endif
                   11845: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  11846:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  11847: #endif
                   11848: #if defined(_MSC_VER)
1.191     brouard  11849:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  11850: #endif
                   11851: #if defined(__PGI)
1.191     brouard  11852:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  11853: #endif
                   11854: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  11855:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  11856: #endif
1.191     brouard  11857:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  11858:    
1.167     brouard  11859: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   11860: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   11861:     // Windows (x64 and x86)
1.191     brouard  11862:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  11863: #elif __unix__ // all unices, not all compilers
                   11864:     // Unix
1.191     brouard  11865:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  11866: #elif __linux__
                   11867:     // linux
1.191     brouard  11868:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  11869: #elif __APPLE__
1.174     brouard  11870:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  11871:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  11872: #endif
                   11873: 
                   11874: /*  __MINGW32__          */
                   11875: /*  __CYGWIN__  */
                   11876: /* __MINGW64__  */
                   11877: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   11878: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   11879: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   11880: /* _WIN64  // Defined for applications for Win64. */
                   11881: /* _M_X64 // Defined for compilations that target x64 processors. */
                   11882: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  11883: 
1.167     brouard  11884: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  11885:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  11886: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  11887:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  11888: #else
1.191     brouard  11889:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  11890: #endif
                   11891: 
1.169     brouard  11892: #if defined(__GNUC__)
                   11893: # if defined(__GNUC_PATCHLEVEL__)
                   11894: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   11895:                             + __GNUC_MINOR__ * 100 \
                   11896:                             + __GNUC_PATCHLEVEL__)
                   11897: # else
                   11898: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   11899:                             + __GNUC_MINOR__ * 100)
                   11900: # endif
1.174     brouard  11901:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  11902:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  11903: 
                   11904:    if (uname(&sysInfo) != -1) {
                   11905:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  11906:         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  11907:    }
                   11908:    else
                   11909:       perror("uname() error");
1.179     brouard  11910:    //#ifndef __INTEL_COMPILER 
                   11911: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  11912:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  11913:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  11914: #endif
1.169     brouard  11915: #endif
1.172     brouard  11916: 
1.286     brouard  11917:    //   void main ()
1.172     brouard  11918:    //   {
1.169     brouard  11919: #if defined(_MSC_VER)
1.174     brouard  11920:    if (IsWow64()){
1.191     brouard  11921:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   11922:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  11923:    }
                   11924:    else{
1.191     brouard  11925:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   11926:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  11927:    }
1.172     brouard  11928:    //     printf("\nPress Enter to continue...");
                   11929:    //     getchar();
                   11930:    //   }
                   11931: 
1.169     brouard  11932: #endif
                   11933:    
1.167     brouard  11934: 
1.219     brouard  11935: }
1.136     brouard  11936: 
1.219     brouard  11937: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  11938:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.332     brouard  11939:   /* Computes the prevalence limit for each combination of the dummy covariates */
1.235     brouard  11940:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  11941:   /* double ftolpl = 1.e-10; */
1.180     brouard  11942:   double age, agebase, agelim;
1.203     brouard  11943:   double tot;
1.180     brouard  11944: 
1.202     brouard  11945:   strcpy(filerespl,"PL_");
                   11946:   strcat(filerespl,fileresu);
                   11947:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  11948:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   11949:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  11950:   }
1.288     brouard  11951:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   11952:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  11953:   pstamp(ficrespl);
1.288     brouard  11954:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  11955:   fprintf(ficrespl,"#Age ");
                   11956:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   11957:   fprintf(ficrespl,"\n");
1.180     brouard  11958:   
1.219     brouard  11959:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  11960: 
1.219     brouard  11961:   agebase=ageminpar;
                   11962:   agelim=agemaxpar;
1.180     brouard  11963: 
1.227     brouard  11964:   /* i1=pow(2,ncoveff); */
1.234     brouard  11965:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  11966:   if (cptcovn < 1){i1=1;}
1.180     brouard  11967: 
1.337     brouard  11968:   /* for(k=1; k<=i1;k++){ /\* For each combination k of dummy covariates in the model *\/ */
1.238     brouard  11969:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  11970:       k=TKresult[nres];
1.338     brouard  11971:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  11972:       /* if(i1 != 1 && TKresult[nres]!= k) /\* We found the combination k corresponding to the resultline value of dummies *\/ */
                   11973:       /*       continue; */
1.235     brouard  11974: 
1.238     brouard  11975:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11976:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   11977:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   11978:       /* k=k+1; */
                   11979:       /* to clean */
1.332     brouard  11980:       /*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*/
1.238     brouard  11981:       fprintf(ficrespl,"#******");
                   11982:       printf("#******");
                   11983:       fprintf(ficlog,"#******");
1.337     brouard  11984:       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  11985:        /* fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Here problem for varying dummy*\/ */
1.337     brouard  11986:        /* printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11987:        /* fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11988:        fprintf(ficrespl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11989:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11990:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11991:       }
                   11992:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   11993:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11994:       /*       fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11995:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11996:       /* } */
1.238     brouard  11997:       fprintf(ficrespl,"******\n");
                   11998:       printf("******\n");
                   11999:       fprintf(ficlog,"******\n");
                   12000:       if(invalidvarcomb[k]){
                   12001:        printf("\nCombination (%d) ignored because no case \n",k); 
                   12002:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   12003:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   12004:        continue;
                   12005:       }
1.219     brouard  12006: 
1.238     brouard  12007:       fprintf(ficrespl,"#Age ");
1.337     brouard  12008:       /* for(j=1;j<=cptcoveff;j++) { */
                   12009:       /*       fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12010:       /* } */
                   12011:       for(j=1;j<=cptcovs;j++) { /* New the quanti variable is added */
                   12012:        fprintf(ficrespl,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12013:       }
                   12014:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   12015:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  12016:     
1.238     brouard  12017:       for (age=agebase; age<=agelim; age++){
                   12018:        /* for (age=agebase; age<=agebase; age++){ */
1.337     brouard  12019:        /**< Computes the prevalence limit in each live state at age x and for covariate combination (k and) nres */
                   12020:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres); /* Nicely done */
1.238     brouard  12021:        fprintf(ficrespl,"%.0f ",age );
1.337     brouard  12022:        /* for(j=1;j<=cptcoveff;j++) */
                   12023:        /*   fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12024:        for(j=1;j<=cptcovs;j++)
                   12025:          fprintf(ficrespl,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12026:        tot=0.;
                   12027:        for(i=1; i<=nlstate;i++){
                   12028:          tot +=  prlim[i][i];
                   12029:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   12030:        }
                   12031:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   12032:       } /* Age */
                   12033:       /* was end of cptcod */
1.337     brouard  12034:     } /* nres */
                   12035:   /* } /\* for each combination *\/ */
1.219     brouard  12036:   return 0;
1.180     brouard  12037: }
                   12038: 
1.218     brouard  12039: 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  12040:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  12041:        
                   12042:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   12043:    * at any age between ageminpar and agemaxpar
                   12044:         */
1.235     brouard  12045:   int i, j, k, i1, nres=0 ;
1.217     brouard  12046:   /* double ftolpl = 1.e-10; */
                   12047:   double age, agebase, agelim;
                   12048:   double tot;
1.218     brouard  12049:   /* double ***mobaverage; */
                   12050:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  12051: 
                   12052:   strcpy(fileresplb,"PLB_");
                   12053:   strcat(fileresplb,fileresu);
                   12054:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  12055:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   12056:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  12057:   }
1.288     brouard  12058:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   12059:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  12060:   pstamp(ficresplb);
1.288     brouard  12061:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  12062:   fprintf(ficresplb,"#Age ");
                   12063:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   12064:   fprintf(ficresplb,"\n");
                   12065:   
1.218     brouard  12066:   
                   12067:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   12068:   
                   12069:   agebase=ageminpar;
                   12070:   agelim=agemaxpar;
                   12071:   
                   12072:   
1.227     brouard  12073:   i1=pow(2,cptcoveff);
1.218     brouard  12074:   if (cptcovn < 1){i1=1;}
1.227     brouard  12075:   
1.238     brouard  12076:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.338     brouard  12077:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   12078:       k=TKresult[nres];
                   12079:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   12080:      /* if(i1 != 1 && TKresult[nres]!= k) */
                   12081:      /*        continue; */
                   12082:      /* /\*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*\/ */
1.238     brouard  12083:       fprintf(ficresplb,"#******");
                   12084:       printf("#******");
                   12085:       fprintf(ficlog,"#******");
1.338     brouard  12086:       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) */
                   12087:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12088:        fprintf(ficresplb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12089:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12090:       }
1.338     brouard  12091:       /* for(j=1;j<=cptcoveff ;j++) {/\* all covariates *\/ */
                   12092:       /*       fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12093:       /*       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12094:       /*       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12095:       /* } */
                   12096:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   12097:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12098:       /*       fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12099:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12100:       /* } */
1.238     brouard  12101:       fprintf(ficresplb,"******\n");
                   12102:       printf("******\n");
                   12103:       fprintf(ficlog,"******\n");
                   12104:       if(invalidvarcomb[k]){
                   12105:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   12106:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   12107:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   12108:        continue;
                   12109:       }
1.218     brouard  12110:     
1.238     brouard  12111:       fprintf(ficresplb,"#Age ");
1.338     brouard  12112:       for(j=1;j<=cptcovs;j++) {
                   12113:        fprintf(ficresplb,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12114:       }
                   12115:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   12116:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  12117:     
                   12118:     
1.238     brouard  12119:       for (age=agebase; age<=agelim; age++){
                   12120:        /* for (age=agebase; age<=agebase; age++){ */
                   12121:        if(mobilavproj > 0){
                   12122:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   12123:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  12124:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  12125:        }else if (mobilavproj == 0){
                   12126:          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);
                   12127:          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);
                   12128:          exit(1);
                   12129:        }else{
                   12130:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  12131:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  12132:          /* printf("TOTOT\n"); */
                   12133:           /* exit(1); */
1.238     brouard  12134:        }
                   12135:        fprintf(ficresplb,"%.0f ",age );
1.338     brouard  12136:        for(j=1;j<=cptcovs;j++)
                   12137:          fprintf(ficresplb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12138:        tot=0.;
                   12139:        for(i=1; i<=nlstate;i++){
                   12140:          tot +=  bprlim[i][i];
                   12141:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   12142:        }
                   12143:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   12144:       } /* Age */
                   12145:       /* was end of cptcod */
1.255     brouard  12146:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.338     brouard  12147:     /* } /\* end of any combination *\/ */
1.238     brouard  12148:   } /* end of nres */  
1.218     brouard  12149:   /* hBijx(p, bage, fage); */
                   12150:   /* fclose(ficrespijb); */
                   12151:   
                   12152:   return 0;
1.217     brouard  12153: }
1.218     brouard  12154:  
1.180     brouard  12155: int hPijx(double *p, int bage, int fage){
                   12156:     /*------------- h Pij x at various ages ------------*/
1.336     brouard  12157:   /* to be optimized with precov */
1.180     brouard  12158:   int stepsize;
                   12159:   int agelim;
                   12160:   int hstepm;
                   12161:   int nhstepm;
1.235     brouard  12162:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  12163: 
                   12164:   double agedeb;
                   12165:   double ***p3mat;
                   12166: 
1.337     brouard  12167:   strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
                   12168:   if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   12169:     printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   12170:     fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   12171:   }
                   12172:   printf("Computing pij: result on file '%s' \n", filerespij);
                   12173:   fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   12174:   
                   12175:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   12176:   /*if (stepm<=24) stepsize=2;*/
                   12177:   
                   12178:   agelim=AGESUP;
                   12179:   hstepm=stepsize*YEARM; /* Every year of age */
                   12180:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   12181:   
                   12182:   /* hstepm=1;   aff par mois*/
                   12183:   pstamp(ficrespij);
                   12184:   fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   12185:   i1= pow(2,cptcoveff);
                   12186:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12187:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   12188:   /*   k=k+1;  */
                   12189:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   12190:     k=TKresult[nres];
1.338     brouard  12191:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12192:     /* for(k=1; k<=i1;k++){ */
                   12193:     /* if(i1 != 1 && TKresult[nres]!= k) */
                   12194:     /*         continue; */
                   12195:     fprintf(ficrespij,"\n#****** ");
                   12196:     for(j=1;j<=cptcovs;j++){
                   12197:       fprintf(ficrespij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12198:       /* fprintf(ficrespij,"@wV%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12199:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   12200:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12201:       /*       fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12202:     }
                   12203:     fprintf(ficrespij,"******\n");
                   12204:     
                   12205:     for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   12206:       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   12207:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   12208:       
                   12209:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   12210:       
                   12211:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12212:       oldm=oldms;savm=savms;
                   12213:       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
                   12214:       fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   12215:       for(i=1; i<=nlstate;i++)
                   12216:        for(j=1; j<=nlstate+ndeath;j++)
                   12217:          fprintf(ficrespij," %1d-%1d",i,j);
                   12218:       fprintf(ficrespij,"\n");
                   12219:       for (h=0; h<=nhstepm; h++){
                   12220:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   12221:        fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.183     brouard  12222:        for(i=1; i<=nlstate;i++)
                   12223:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  12224:            fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.183     brouard  12225:        fprintf(ficrespij,"\n");
                   12226:       }
1.337     brouard  12227:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12228:       fprintf(ficrespij,"\n");
1.180     brouard  12229:     }
1.337     brouard  12230:   }
                   12231:   /*}*/
                   12232:   return 0;
1.180     brouard  12233: }
1.218     brouard  12234:  
                   12235:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  12236:     /*------------- h Bij x at various ages ------------*/
1.336     brouard  12237:     /* To be optimized with precov */
1.217     brouard  12238:   int stepsize;
1.218     brouard  12239:   /* int agelim; */
                   12240:        int ageminl;
1.217     brouard  12241:   int hstepm;
                   12242:   int nhstepm;
1.238     brouard  12243:   int h, i, i1, j, k, nres;
1.218     brouard  12244:        
1.217     brouard  12245:   double agedeb;
                   12246:   double ***p3mat;
1.218     brouard  12247:        
                   12248:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   12249:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   12250:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   12251:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   12252:   }
                   12253:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   12254:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   12255:   
                   12256:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   12257:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  12258:   
1.218     brouard  12259:   /* agelim=AGESUP; */
1.289     brouard  12260:   ageminl=AGEINF; /* was 30 */
1.218     brouard  12261:   hstepm=stepsize*YEARM; /* Every year of age */
                   12262:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   12263:   
                   12264:   /* hstepm=1;   aff par mois*/
                   12265:   pstamp(ficrespijb);
1.255     brouard  12266:   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  12267:   i1= pow(2,cptcoveff);
1.218     brouard  12268:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12269:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   12270:   /*   k=k+1;  */
1.238     brouard  12271:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  12272:     k=TKresult[nres];
1.338     brouard  12273:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12274:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   12275:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   12276:     /*         continue; */
                   12277:     fprintf(ficrespijb,"\n#****** ");
                   12278:     for(j=1;j<=cptcovs;j++){
1.338     brouard  12279:       fprintf(ficrespijb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.337     brouard  12280:       /* for(j=1;j<=cptcoveff;j++) */
                   12281:       /*       fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12282:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   12283:       /*       fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12284:     }
                   12285:     fprintf(ficrespijb,"******\n");
                   12286:     if(invalidvarcomb[k]){  /* Is it necessary here? */
                   12287:       fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   12288:       continue;
                   12289:     }
                   12290:     
                   12291:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   12292:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   12293:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   12294:       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 */
                   12295:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
                   12296:       
                   12297:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   12298:       
                   12299:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   12300:       /* and memory limitations if stepm is small */
                   12301:       
                   12302:       /* oldm=oldms;savm=savms; */
                   12303:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   12304:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);/* Bug valgrind */
                   12305:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
                   12306:       fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
                   12307:       for(i=1; i<=nlstate;i++)
                   12308:        for(j=1; j<=nlstate+ndeath;j++)
                   12309:          fprintf(ficrespijb," %1d-%1d",i,j);
                   12310:       fprintf(ficrespijb,"\n");
                   12311:       for (h=0; h<=nhstepm; h++){
                   12312:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   12313:        fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   12314:        /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
1.217     brouard  12315:        for(i=1; i<=nlstate;i++)
                   12316:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  12317:            fprintf(ficrespijb," %.5f", p3mat[i][j][h]);/* Bug valgrind */
1.217     brouard  12318:        fprintf(ficrespijb,"\n");
1.337     brouard  12319:       }
                   12320:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12321:       fprintf(ficrespijb,"\n");
                   12322:     } /* end age deb */
                   12323:     /* } /\* end combination *\/ */
1.238     brouard  12324:   } /* end nres */
1.218     brouard  12325:   return 0;
                   12326:  } /*  hBijx */
1.217     brouard  12327: 
1.180     brouard  12328: 
1.136     brouard  12329: /***********************************************/
                   12330: /**************** Main Program *****************/
                   12331: /***********************************************/
                   12332: 
                   12333: int main(int argc, char *argv[])
                   12334: {
                   12335: #ifdef GSL
                   12336:   const gsl_multimin_fminimizer_type *T;
                   12337:   size_t iteri = 0, it;
                   12338:   int rval = GSL_CONTINUE;
                   12339:   int status = GSL_SUCCESS;
                   12340:   double ssval;
                   12341: #endif
                   12342:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  12343:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   12344:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  12345:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  12346:   int jj, ll, li, lj, lk;
1.136     brouard  12347:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  12348:   int num_filled;
1.136     brouard  12349:   int itimes;
                   12350:   int NDIM=2;
                   12351:   int vpopbased=0;
1.235     brouard  12352:   int nres=0;
1.258     brouard  12353:   int endishere=0;
1.277     brouard  12354:   int noffset=0;
1.274     brouard  12355:   int ncurrv=0; /* Temporary variable */
                   12356:   
1.164     brouard  12357:   char ca[32], cb[32];
1.136     brouard  12358:   /*  FILE *fichtm; *//* Html File */
                   12359:   /* FILE *ficgp;*/ /*Gnuplot File */
                   12360:   struct stat info;
1.191     brouard  12361:   double agedeb=0.;
1.194     brouard  12362: 
                   12363:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  12364:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  12365: 
1.165     brouard  12366:   double fret;
1.191     brouard  12367:   double dum=0.; /* Dummy variable */
1.136     brouard  12368:   double ***p3mat;
1.218     brouard  12369:   /* double ***mobaverage; */
1.319     brouard  12370:   double wald;
1.164     brouard  12371: 
                   12372:   char line[MAXLINE];
1.197     brouard  12373:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   12374: 
1.234     brouard  12375:   char  modeltemp[MAXLINE];
1.332     brouard  12376:   char resultline[MAXLINE], resultlineori[MAXLINE];
1.230     brouard  12377:   
1.136     brouard  12378:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  12379:   char *tok, *val; /* pathtot */
1.334     brouard  12380:   /* int firstobs=1, lastobs=10; /\* nobs = lastobs-firstobs declared globally ;*\/ */
1.195     brouard  12381:   int c,  h , cpt, c2;
1.191     brouard  12382:   int jl=0;
                   12383:   int i1, j1, jk, stepsize=0;
1.194     brouard  12384:   int count=0;
                   12385: 
1.164     brouard  12386:   int *tab; 
1.136     brouard  12387:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  12388:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   12389:   /* double anprojf, mprojf, jprojf; */
                   12390:   /* double jintmean,mintmean,aintmean;   */
                   12391:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   12392:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   12393:   double yrfproj= 10.0; /* Number of years of forward projections */
                   12394:   double yrbproj= 10.0; /* Number of years of backward projections */
                   12395:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  12396:   int mobilav=0,popforecast=0;
1.191     brouard  12397:   int hstepm=0, nhstepm=0;
1.136     brouard  12398:   int agemortsup;
                   12399:   float  sumlpop=0.;
                   12400:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   12401:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   12402: 
1.191     brouard  12403:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  12404:   double ftolpl=FTOL;
                   12405:   double **prlim;
1.217     brouard  12406:   double **bprlim;
1.317     brouard  12407:   double ***param; /* Matrix of parameters, param[i][j][k] param=ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel) 
                   12408:                     state of origin, state of destination including death, for each covariate: constante, age, and V1 V2 etc. */
1.251     brouard  12409:   double ***paramstart; /* Matrix of starting parameter values */
                   12410:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  12411:   double **matcov; /* Matrix of covariance */
1.203     brouard  12412:   double **hess; /* Hessian matrix */
1.136     brouard  12413:   double ***delti3; /* Scale */
                   12414:   double *delti; /* Scale */
                   12415:   double ***eij, ***vareij;
                   12416:   double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  12417: 
1.136     brouard  12418:   double *epj, vepp;
1.164     brouard  12419: 
1.273     brouard  12420:   double dateprev1, dateprev2;
1.296     brouard  12421:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   12422:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   12423: 
1.217     brouard  12424: 
1.136     brouard  12425:   double **ximort;
1.145     brouard  12426:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  12427:   int *dcwave;
                   12428: 
1.164     brouard  12429:   char z[1]="c";
1.136     brouard  12430: 
                   12431:   /*char  *strt;*/
                   12432:   char strtend[80];
1.126     brouard  12433: 
1.164     brouard  12434: 
1.126     brouard  12435: /*   setlocale (LC_ALL, ""); */
                   12436: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   12437: /*   textdomain (PACKAGE); */
                   12438: /*   setlocale (LC_CTYPE, ""); */
                   12439: /*   setlocale (LC_MESSAGES, ""); */
                   12440: 
                   12441:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  12442:   rstart_time = time(NULL);  
                   12443:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   12444:   start_time = *localtime(&rstart_time);
1.126     brouard  12445:   curr_time=start_time;
1.157     brouard  12446:   /*tml = *localtime(&start_time.tm_sec);*/
                   12447:   /* strcpy(strstart,asctime(&tml)); */
                   12448:   strcpy(strstart,asctime(&start_time));
1.126     brouard  12449: 
                   12450: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  12451: /*  tp.tm_sec = tp.tm_sec +86400; */
                   12452: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  12453: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   12454: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   12455: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  12456: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  12457: /*   strt=asctime(&tmg); */
                   12458: /*   printf("Time(after) =%s",strstart);  */
                   12459: /*  (void) time (&time_value);
                   12460: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   12461: *  tm = *localtime(&time_value);
                   12462: *  strstart=asctime(&tm);
                   12463: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   12464: */
                   12465: 
                   12466:   nberr=0; /* Number of errors and warnings */
                   12467:   nbwarn=0;
1.184     brouard  12468: #ifdef WIN32
                   12469:   _getcwd(pathcd, size);
                   12470: #else
1.126     brouard  12471:   getcwd(pathcd, size);
1.184     brouard  12472: #endif
1.191     brouard  12473:   syscompilerinfo(0);
1.196     brouard  12474:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  12475:   if(argc <=1){
                   12476:     printf("\nEnter the parameter file name: ");
1.205     brouard  12477:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   12478:       printf("ERROR Empty parameter file name\n");
                   12479:       goto end;
                   12480:     }
1.126     brouard  12481:     i=strlen(pathr);
                   12482:     if(pathr[i-1]=='\n')
                   12483:       pathr[i-1]='\0';
1.156     brouard  12484:     i=strlen(pathr);
1.205     brouard  12485:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  12486:       pathr[i-1]='\0';
1.205     brouard  12487:     }
                   12488:     i=strlen(pathr);
                   12489:     if( i==0 ){
                   12490:       printf("ERROR Empty parameter file name\n");
                   12491:       goto end;
                   12492:     }
                   12493:     for (tok = pathr; tok != NULL; ){
1.126     brouard  12494:       printf("Pathr |%s|\n",pathr);
                   12495:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   12496:       printf("val= |%s| pathr=%s\n",val,pathr);
                   12497:       strcpy (pathtot, val);
                   12498:       if(pathr[0] == '\0') break; /* Dirty */
                   12499:     }
                   12500:   }
1.281     brouard  12501:   else if (argc<=2){
                   12502:     strcpy(pathtot,argv[1]);
                   12503:   }
1.126     brouard  12504:   else{
                   12505:     strcpy(pathtot,argv[1]);
1.281     brouard  12506:     strcpy(z,argv[2]);
                   12507:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  12508:   }
                   12509:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   12510:   /*cygwin_split_path(pathtot,path,optionfile);
                   12511:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   12512:   /* cutv(path,optionfile,pathtot,'\\');*/
                   12513: 
                   12514:   /* Split argv[0], imach program to get pathimach */
                   12515:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   12516:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   12517:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   12518:  /*   strcpy(pathimach,argv[0]); */
                   12519:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   12520:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   12521:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  12522: #ifdef WIN32
                   12523:   _chdir(path); /* Can be a relative path */
                   12524:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   12525: #else
1.126     brouard  12526:   chdir(path); /* Can be a relative path */
1.184     brouard  12527:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   12528: #endif
                   12529:   printf("Current directory %s!\n",pathcd);
1.126     brouard  12530:   strcpy(command,"mkdir ");
                   12531:   strcat(command,optionfilefiname);
                   12532:   if((outcmd=system(command)) != 0){
1.169     brouard  12533:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  12534:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   12535:     /* fclose(ficlog); */
                   12536: /*     exit(1); */
                   12537:   }
                   12538: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   12539: /*     perror("mkdir"); */
                   12540: /*   } */
                   12541: 
                   12542:   /*-------- arguments in the command line --------*/
                   12543: 
1.186     brouard  12544:   /* Main Log file */
1.126     brouard  12545:   strcat(filelog, optionfilefiname);
                   12546:   strcat(filelog,".log");    /* */
                   12547:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   12548:     printf("Problem with logfile %s\n",filelog);
                   12549:     goto end;
                   12550:   }
                   12551:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  12552:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  12553:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   12554:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   12555:  path=%s \n\
                   12556:  optionfile=%s\n\
                   12557:  optionfilext=%s\n\
1.156     brouard  12558:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  12559: 
1.197     brouard  12560:   syscompilerinfo(1);
1.167     brouard  12561: 
1.126     brouard  12562:   printf("Local time (at start):%s",strstart);
                   12563:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   12564:   fflush(ficlog);
                   12565: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  12566: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  12567: 
                   12568:   /* */
                   12569:   strcpy(fileres,"r");
                   12570:   strcat(fileres, optionfilefiname);
1.201     brouard  12571:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  12572:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  12573:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  12574: 
1.186     brouard  12575:   /* Main ---------arguments file --------*/
1.126     brouard  12576: 
                   12577:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  12578:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   12579:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  12580:     fflush(ficlog);
1.149     brouard  12581:     /* goto end; */
                   12582:     exit(70); 
1.126     brouard  12583:   }
                   12584: 
                   12585:   strcpy(filereso,"o");
1.201     brouard  12586:   strcat(filereso,fileresu);
1.126     brouard  12587:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   12588:     printf("Problem with Output resultfile: %s\n", filereso);
                   12589:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   12590:     fflush(ficlog);
                   12591:     goto end;
                   12592:   }
1.278     brouard  12593:       /*-------- Rewriting parameter file ----------*/
                   12594:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   12595:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   12596:   strcat(rfileres,".");    /* */
                   12597:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   12598:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   12599:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   12600:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   12601:     fflush(ficlog);
                   12602:     goto end;
                   12603:   }
                   12604:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  12605: 
1.278     brouard  12606:                                      
1.126     brouard  12607:   /* Reads comments: lines beginning with '#' */
                   12608:   numlinepar=0;
1.277     brouard  12609:   /* Is it a BOM UTF-8 Windows file? */
                   12610:   /* First parameter line */
1.197     brouard  12611:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  12612:     noffset=0;
                   12613:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   12614:     {
                   12615:       noffset=noffset+3;
                   12616:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   12617:     }
1.302     brouard  12618: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   12619:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
1.277     brouard  12620:     {
                   12621:       noffset=noffset+2;
                   12622:       printf("# File is an UTF16BE BOM file\n");
                   12623:     }
                   12624:     else if( line[0] == 0 && line[1] == 0)
                   12625:     {
                   12626:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   12627:        noffset=noffset+4;
                   12628:        printf("# File is an UTF16BE BOM file\n");
                   12629:       }
                   12630:     } else{
                   12631:       ;/*printf(" Not a BOM file\n");*/
                   12632:     }
                   12633:   
1.197     brouard  12634:     /* If line starts with a # it is a comment */
1.277     brouard  12635:     if (line[noffset] == '#') {
1.197     brouard  12636:       numlinepar++;
                   12637:       fputs(line,stdout);
                   12638:       fputs(line,ficparo);
1.278     brouard  12639:       fputs(line,ficres);
1.197     brouard  12640:       fputs(line,ficlog);
                   12641:       continue;
                   12642:     }else
                   12643:       break;
                   12644:   }
                   12645:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   12646:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   12647:     if (num_filled != 5) {
                   12648:       printf("Should be 5 parameters\n");
1.283     brouard  12649:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  12650:     }
1.126     brouard  12651:     numlinepar++;
1.197     brouard  12652:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  12653:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   12654:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   12655:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  12656:   }
                   12657:   /* Second parameter line */
                   12658:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  12659:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   12660:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  12661:     if (line[0] == '#') {
                   12662:       numlinepar++;
1.283     brouard  12663:       printf("%s",line);
                   12664:       fprintf(ficres,"%s",line);
                   12665:       fprintf(ficparo,"%s",line);
                   12666:       fprintf(ficlog,"%s",line);
1.197     brouard  12667:       continue;
                   12668:     }else
                   12669:       break;
                   12670:   }
1.223     brouard  12671:   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", \
                   12672:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   12673:     if (num_filled != 11) {
                   12674:       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  12675:       printf("but line=%s\n",line);
1.283     brouard  12676:       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");
                   12677:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  12678:     }
1.286     brouard  12679:     if( lastpass > maxwav){
                   12680:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   12681:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   12682:       fflush(ficlog);
                   12683:       goto end;
                   12684:     }
                   12685:       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  12686:     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  12687:     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  12688:     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  12689:   }
1.203     brouard  12690:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  12691:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  12692:   /* Third parameter line */
                   12693:   while(fgets(line, MAXLINE, ficpar)) {
                   12694:     /* If line starts with a # it is a comment */
                   12695:     if (line[0] == '#') {
                   12696:       numlinepar++;
1.283     brouard  12697:       printf("%s",line);
                   12698:       fprintf(ficres,"%s",line);
                   12699:       fprintf(ficparo,"%s",line);
                   12700:       fprintf(ficlog,"%s",line);
1.197     brouard  12701:       continue;
                   12702:     }else
                   12703:       break;
                   12704:   }
1.201     brouard  12705:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
1.279     brouard  12706:     if (num_filled != 1){
1.302     brouard  12707:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   12708:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
1.197     brouard  12709:       model[0]='\0';
                   12710:       goto end;
                   12711:     }
                   12712:     else{
                   12713:       if (model[0]=='+'){
                   12714:        for(i=1; i<=strlen(model);i++)
                   12715:          modeltemp[i-1]=model[i];
1.201     brouard  12716:        strcpy(model,modeltemp); 
1.197     brouard  12717:       }
                   12718:     }
1.338     brouard  12719:     /* printf(" model=1+age%s modeltemp= %s, model=1+age+%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  12720:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  12721:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   12722:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   12723:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  12724:   }
                   12725:   /* 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); */
                   12726:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   12727:   /* 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  12728:   /* 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); */
                   12729:   /* 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  12730:   fflush(ficlog);
1.190     brouard  12731:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   12732:   if(model[0]=='#'){
1.279     brouard  12733:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   12734:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   12735:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  12736:     if(mle != -1){
1.279     brouard  12737:       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  12738:       exit(1);
                   12739:     }
                   12740:   }
1.126     brouard  12741:   while((c=getc(ficpar))=='#' && c!= EOF){
                   12742:     ungetc(c,ficpar);
                   12743:     fgets(line, MAXLINE, ficpar);
                   12744:     numlinepar++;
1.195     brouard  12745:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   12746:       z[0]=line[1];
1.342     brouard  12747:     }else if(line[1]=='d'){ /* For debugging individual values of covariates in ficresilk */
1.343     brouard  12748:       debugILK=1;printf("DebugILK\n");
1.195     brouard  12749:     }
                   12750:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  12751:     fputs(line, stdout);
                   12752:     //puts(line);
1.126     brouard  12753:     fputs(line,ficparo);
                   12754:     fputs(line,ficlog);
                   12755:   }
                   12756:   ungetc(c,ficpar);
                   12757: 
                   12758:    
1.290     brouard  12759:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   12760:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   12761:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
1.341     brouard  12762:   /* if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /\**< Time varying covariate (dummy and quantitative)*\/ */
                   12763:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);  /**< Might be better */
1.136     brouard  12764:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   12765:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   12766:      v1+v2*age+v2*v3 makes cptcovn = 3
                   12767:   */
                   12768:   if (strlen(model)>1) 
1.187     brouard  12769:     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  12770:   else
1.187     brouard  12771:     ncovmodel=2; /* Constant and age */
1.133     brouard  12772:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   12773:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  12774:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   12775:     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);
                   12776:     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);
                   12777:     fflush(stdout);
                   12778:     fclose (ficlog);
                   12779:     goto end;
                   12780:   }
1.126     brouard  12781:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   12782:   delti=delti3[1][1];
                   12783:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   12784:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  12785: /* We could also provide initial parameters values giving by simple logistic regression 
                   12786:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   12787:       /* for(i=1;i<nlstate;i++){ */
                   12788:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   12789:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   12790:       /* } */
1.126     brouard  12791:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  12792:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   12793:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  12794:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   12795:     fclose (ficparo);
                   12796:     fclose (ficlog);
                   12797:     goto end;
                   12798:     exit(0);
1.220     brouard  12799:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  12800:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  12801:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   12802:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  12803:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   12804:     matcov=matrix(1,npar,1,npar);
1.203     brouard  12805:     hess=matrix(1,npar,1,npar);
1.220     brouard  12806:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  12807:     /* Read guessed parameters */
1.126     brouard  12808:     /* Reads comments: lines beginning with '#' */
                   12809:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12810:       ungetc(c,ficpar);
                   12811:       fgets(line, MAXLINE, ficpar);
                   12812:       numlinepar++;
1.141     brouard  12813:       fputs(line,stdout);
1.126     brouard  12814:       fputs(line,ficparo);
                   12815:       fputs(line,ficlog);
                   12816:     }
                   12817:     ungetc(c,ficpar);
                   12818:     
                   12819:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  12820:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  12821:     for(i=1; i <=nlstate; i++){
1.234     brouard  12822:       j=0;
1.126     brouard  12823:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  12824:        if(jj==i) continue;
                   12825:        j++;
1.292     brouard  12826:        while((c=getc(ficpar))=='#' && c!= EOF){
                   12827:          ungetc(c,ficpar);
                   12828:          fgets(line, MAXLINE, ficpar);
                   12829:          numlinepar++;
                   12830:          fputs(line,stdout);
                   12831:          fputs(line,ficparo);
                   12832:          fputs(line,ficlog);
                   12833:        }
                   12834:        ungetc(c,ficpar);
1.234     brouard  12835:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   12836:        if ((i1 != i) || (j1 != jj)){
                   12837:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  12838: It might be a problem of design; if ncovcol and the model are correct\n \
                   12839: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  12840:          exit(1);
                   12841:        }
                   12842:        fprintf(ficparo,"%1d%1d",i1,j1);
                   12843:        if(mle==1)
                   12844:          printf("%1d%1d",i,jj);
                   12845:        fprintf(ficlog,"%1d%1d",i,jj);
                   12846:        for(k=1; k<=ncovmodel;k++){
                   12847:          fscanf(ficpar," %lf",&param[i][j][k]);
                   12848:          if(mle==1){
                   12849:            printf(" %lf",param[i][j][k]);
                   12850:            fprintf(ficlog," %lf",param[i][j][k]);
                   12851:          }
                   12852:          else
                   12853:            fprintf(ficlog," %lf",param[i][j][k]);
                   12854:          fprintf(ficparo," %lf",param[i][j][k]);
                   12855:        }
                   12856:        fscanf(ficpar,"\n");
                   12857:        numlinepar++;
                   12858:        if(mle==1)
                   12859:          printf("\n");
                   12860:        fprintf(ficlog,"\n");
                   12861:        fprintf(ficparo,"\n");
1.126     brouard  12862:       }
                   12863:     }  
                   12864:     fflush(ficlog);
1.234     brouard  12865:     
1.251     brouard  12866:     /* Reads parameters values */
1.126     brouard  12867:     p=param[1][1];
1.251     brouard  12868:     pstart=paramstart[1][1];
1.126     brouard  12869:     
                   12870:     /* Reads comments: lines beginning with '#' */
                   12871:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12872:       ungetc(c,ficpar);
                   12873:       fgets(line, MAXLINE, ficpar);
                   12874:       numlinepar++;
1.141     brouard  12875:       fputs(line,stdout);
1.126     brouard  12876:       fputs(line,ficparo);
                   12877:       fputs(line,ficlog);
                   12878:     }
                   12879:     ungetc(c,ficpar);
                   12880: 
                   12881:     for(i=1; i <=nlstate; i++){
                   12882:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  12883:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   12884:        if ( (i1-i) * (j1-j) != 0){
                   12885:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   12886:          exit(1);
                   12887:        }
                   12888:        printf("%1d%1d",i,j);
                   12889:        fprintf(ficparo,"%1d%1d",i1,j1);
                   12890:        fprintf(ficlog,"%1d%1d",i1,j1);
                   12891:        for(k=1; k<=ncovmodel;k++){
                   12892:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   12893:          printf(" %le",delti3[i][j][k]);
                   12894:          fprintf(ficparo," %le",delti3[i][j][k]);
                   12895:          fprintf(ficlog," %le",delti3[i][j][k]);
                   12896:        }
                   12897:        fscanf(ficpar,"\n");
                   12898:        numlinepar++;
                   12899:        printf("\n");
                   12900:        fprintf(ficparo,"\n");
                   12901:        fprintf(ficlog,"\n");
1.126     brouard  12902:       }
                   12903:     }
                   12904:     fflush(ficlog);
1.234     brouard  12905:     
1.145     brouard  12906:     /* Reads covariance matrix */
1.126     brouard  12907:     delti=delti3[1][1];
1.220     brouard  12908:                
                   12909:                
1.126     brouard  12910:     /* 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  12911:                
1.126     brouard  12912:     /* Reads comments: lines beginning with '#' */
                   12913:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12914:       ungetc(c,ficpar);
                   12915:       fgets(line, MAXLINE, ficpar);
                   12916:       numlinepar++;
1.141     brouard  12917:       fputs(line,stdout);
1.126     brouard  12918:       fputs(line,ficparo);
                   12919:       fputs(line,ficlog);
                   12920:     }
                   12921:     ungetc(c,ficpar);
1.220     brouard  12922:                
1.126     brouard  12923:     matcov=matrix(1,npar,1,npar);
1.203     brouard  12924:     hess=matrix(1,npar,1,npar);
1.131     brouard  12925:     for(i=1; i <=npar; i++)
                   12926:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  12927:                
1.194     brouard  12928:     /* Scans npar lines */
1.126     brouard  12929:     for(i=1; i <=npar; i++){
1.226     brouard  12930:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  12931:       if(count != 3){
1.226     brouard  12932:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  12933: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   12934: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  12935:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  12936: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   12937: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  12938:        exit(1);
1.220     brouard  12939:       }else{
1.226     brouard  12940:        if(mle==1)
                   12941:          printf("%1d%1d%d",i1,j1,jk);
                   12942:       }
                   12943:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   12944:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  12945:       for(j=1; j <=i; j++){
1.226     brouard  12946:        fscanf(ficpar," %le",&matcov[i][j]);
                   12947:        if(mle==1){
                   12948:          printf(" %.5le",matcov[i][j]);
                   12949:        }
                   12950:        fprintf(ficlog," %.5le",matcov[i][j]);
                   12951:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  12952:       }
                   12953:       fscanf(ficpar,"\n");
                   12954:       numlinepar++;
                   12955:       if(mle==1)
1.220     brouard  12956:                                printf("\n");
1.126     brouard  12957:       fprintf(ficlog,"\n");
                   12958:       fprintf(ficparo,"\n");
                   12959:     }
1.194     brouard  12960:     /* End of read covariance matrix npar lines */
1.126     brouard  12961:     for(i=1; i <=npar; i++)
                   12962:       for(j=i+1;j<=npar;j++)
1.226     brouard  12963:        matcov[i][j]=matcov[j][i];
1.126     brouard  12964:     
                   12965:     if(mle==1)
                   12966:       printf("\n");
                   12967:     fprintf(ficlog,"\n");
                   12968:     
                   12969:     fflush(ficlog);
                   12970:     
                   12971:   }    /* End of mle != -3 */
1.218     brouard  12972:   
1.186     brouard  12973:   /*  Main data
                   12974:    */
1.290     brouard  12975:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   12976:   /* num=lvector(1,n); */
                   12977:   /* moisnais=vector(1,n); */
                   12978:   /* annais=vector(1,n); */
                   12979:   /* moisdc=vector(1,n); */
                   12980:   /* andc=vector(1,n); */
                   12981:   /* weight=vector(1,n); */
                   12982:   /* agedc=vector(1,n); */
                   12983:   /* cod=ivector(1,n); */
                   12984:   /* for(i=1;i<=n;i++){ */
                   12985:   num=lvector(firstobs,lastobs);
                   12986:   moisnais=vector(firstobs,lastobs);
                   12987:   annais=vector(firstobs,lastobs);
                   12988:   moisdc=vector(firstobs,lastobs);
                   12989:   andc=vector(firstobs,lastobs);
                   12990:   weight=vector(firstobs,lastobs);
                   12991:   agedc=vector(firstobs,lastobs);
                   12992:   cod=ivector(firstobs,lastobs);
                   12993:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  12994:     num[i]=0;
                   12995:     moisnais[i]=0;
                   12996:     annais[i]=0;
                   12997:     moisdc[i]=0;
                   12998:     andc[i]=0;
                   12999:     agedc[i]=0;
                   13000:     cod[i]=0;
                   13001:     weight[i]=1.0; /* Equal weights, 1 by default */
                   13002:   }
1.290     brouard  13003:   mint=matrix(1,maxwav,firstobs,lastobs);
                   13004:   anint=matrix(1,maxwav,firstobs,lastobs);
1.325     brouard  13005:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */
1.336     brouard  13006:   /* printf("BUG ncovmodel=%d NCOVMAX=%d 2**ncovmodel=%f BUG\n",ncovmodel,NCOVMAX,pow(2,ncovmodel)); */
1.126     brouard  13007:   tab=ivector(1,NCOVMAX);
1.144     brouard  13008:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  13009:   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  13010: 
1.136     brouard  13011:   /* Reads data from file datafile */
                   13012:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   13013:     goto end;
                   13014: 
                   13015:   /* Calculation of the number of parameters from char model */
1.234     brouard  13016:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  13017:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   13018:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   13019:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   13020:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  13021:   */
                   13022:   
                   13023:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   13024:   TvarsDind=ivector(1,NCOVMAX); /*  */
1.330     brouard  13025:   TnsdVar=ivector(1,NCOVMAX); /*  */
1.335     brouard  13026:     /* for(i=1; i<=NCOVMAX;i++) TnsdVar[i]=3; */
1.234     brouard  13027:   TvarsD=ivector(1,NCOVMAX); /*  */
                   13028:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   13029:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  13030:   TvarF=ivector(1,NCOVMAX); /*  */
                   13031:   TvarFind=ivector(1,NCOVMAX); /*  */
                   13032:   TvarV=ivector(1,NCOVMAX); /*  */
                   13033:   TvarVind=ivector(1,NCOVMAX); /*  */
                   13034:   TvarA=ivector(1,NCOVMAX); /*  */
                   13035:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  13036:   TvarFD=ivector(1,NCOVMAX); /*  */
                   13037:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   13038:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   13039:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   13040:   TvarVD=ivector(1,NCOVMAX); /*  */
                   13041:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   13042:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   13043:   TvarVQind=ivector(1,NCOVMAX); /*  */
1.339     brouard  13044:   TvarVV=ivector(1,NCOVMAX); /*  */
                   13045:   TvarVVind=ivector(1,NCOVMAX); /*  */
1.231     brouard  13046: 
1.230     brouard  13047:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  13048:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  13049:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   13050:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   13051:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.137     brouard  13052:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   13053:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   13054:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   13055:   */
                   13056:   /* For model-covariate k tells which data-covariate to use but
                   13057:     because this model-covariate is a construction we invent a new column
                   13058:     ncovcol + k1
                   13059:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   13060:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  13061:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   13062:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  13063:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   13064:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  13065:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  13066:   */
1.145     brouard  13067:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   13068:   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  13069:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   13070:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.330     brouard  13071:   Tvardk=imatrix(1,NCOVMAX,1,2);
1.145     brouard  13072:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  13073:                         4 covariates (3 plus signs)
                   13074:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
1.328     brouard  13075:                           */  
                   13076:   for(i=1;i<NCOVMAX;i++)
                   13077:     Tage[i]=0;
1.230     brouard  13078:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  13079:                                * individual dummy, fixed or varying:
                   13080:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   13081:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  13082:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   13083:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   13084:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   13085:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   13086:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  13087:                                * individual quantitative, fixed or varying:
                   13088:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   13089:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   13090:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.186     brouard  13091: /* Main decodemodel */
                   13092: 
1.187     brouard  13093: 
1.223     brouard  13094:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  13095:     goto end;
                   13096: 
1.137     brouard  13097:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   13098:     nbwarn++;
                   13099:     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); 
                   13100:     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); 
                   13101:   }
1.136     brouard  13102:     /*  if(mle==1){*/
1.137     brouard  13103:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   13104:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  13105:   }
                   13106: 
                   13107:     /*-calculation of age at interview from date of interview and age at death -*/
                   13108:   agev=matrix(1,maxwav,1,imx);
                   13109: 
                   13110:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   13111:     goto end;
                   13112: 
1.126     brouard  13113: 
1.136     brouard  13114:   agegomp=(int)agemin;
1.290     brouard  13115:   free_vector(moisnais,firstobs,lastobs);
                   13116:   free_vector(annais,firstobs,lastobs);
1.126     brouard  13117:   /* free_matrix(mint,1,maxwav,1,n);
                   13118:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  13119:   /* free_vector(moisdc,1,n); */
                   13120:   /* free_vector(andc,1,n); */
1.145     brouard  13121:   /* */
                   13122:   
1.126     brouard  13123:   wav=ivector(1,imx);
1.214     brouard  13124:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13125:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13126:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13127:   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.*/
                   13128:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   13129:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  13130:    
                   13131:   /* Concatenates waves */
1.214     brouard  13132:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   13133:      Death is a valid wave (if date is known).
                   13134:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   13135:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   13136:      and mw[mi+1][i]. dh depends on stepm.
                   13137:   */
                   13138: 
1.126     brouard  13139:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  13140:   /* Concatenates waves */
1.145     brouard  13141:  
1.290     brouard  13142:   free_vector(moisdc,firstobs,lastobs);
                   13143:   free_vector(andc,firstobs,lastobs);
1.215     brouard  13144: 
1.126     brouard  13145:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   13146:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   13147:   ncodemax[1]=1;
1.145     brouard  13148:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  13149:   cptcoveff=0;
1.220     brouard  13150:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
1.335     brouard  13151:     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  13152:   }
                   13153:   
                   13154:   ncovcombmax=pow(2,cptcoveff);
1.338     brouard  13155:   invalidvarcomb=ivector(0, ncovcombmax); 
                   13156:   for(i=0;i<ncovcombmax;i++)
1.227     brouard  13157:     invalidvarcomb[i]=0;
                   13158:   
1.211     brouard  13159:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  13160:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  13161:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  13162:   
1.200     brouard  13163:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  13164:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  13165:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  13166:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   13167:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   13168:    * (currently 0 or 1) in the data.
                   13169:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   13170:    * corresponding modality (h,j).
                   13171:    */
                   13172: 
1.145     brouard  13173:   h=0;
                   13174:   /*if (cptcovn > 0) */
1.126     brouard  13175:   m=pow(2,cptcoveff);
                   13176:  
1.144     brouard  13177:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  13178:           * For k=4 covariates, h goes from 1 to m=2**k
                   13179:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   13180:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.329     brouard  13181:           *     h\k   1     2     3     4   *  h-1\k-1  4  3  2  1          
                   13182:           *______________________________   *______________________
                   13183:           *     1 i=1 1 i=1 1 i=1 1 i=1 1   *     0     0  0  0  0 
                   13184:           *     2     2     1     1     1   *     1     0  0  0  1 
                   13185:           *     3 i=2 1     2     1     1   *     2     0  0  1  0 
                   13186:           *     4     2     2     1     1   *     3     0  0  1  1 
                   13187:           *     5 i=3 1 i=2 1     2     1   *     4     0  1  0  0 
                   13188:           *     6     2     1     2     1   *     5     0  1  0  1 
                   13189:           *     7 i=4 1     2     2     1   *     6     0  1  1  0 
                   13190:           *     8     2     2     2     1   *     7     0  1  1  1 
                   13191:           *     9 i=5 1 i=3 1 i=2 1     2   *     8     1  0  0  0 
                   13192:           *    10     2     1     1     2   *     9     1  0  0  1 
                   13193:           *    11 i=6 1     2     1     2   *    10     1  0  1  0 
                   13194:           *    12     2     2     1     2   *    11     1  0  1  1 
                   13195:           *    13 i=7 1 i=4 1     2     2   *    12     1  1  0  0  
                   13196:           *    14     2     1     2     2   *    13     1  1  0  1 
                   13197:           *    15 i=8 1     2     2     2   *    14     1  1  1  0 
                   13198:           *    16     2     2     2     2   *    15     1  1  1  1          
                   13199:           */                                     
1.212     brouard  13200:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  13201:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   13202:      * and the value of each covariate?
                   13203:      * V1=1, V2=1, V3=2, V4=1 ?
                   13204:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   13205:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   13206:      * In order to get the real value in the data, we use nbcode
                   13207:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   13208:      * We are keeping this crazy system in order to be able (in the future?) 
                   13209:      * to have more than 2 values (0 or 1) for a covariate.
                   13210:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   13211:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   13212:      *              bbbbbbbb
                   13213:      *              76543210     
                   13214:      *   h-1        00000101 (6-1=5)
1.219     brouard  13215:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  13216:      *           &
                   13217:      *     1        00000001 (1)
1.219     brouard  13218:      *              00000000        = 1 & ((h-1) >> (k-1))
                   13219:      *          +1= 00000001 =1 
1.211     brouard  13220:      *
                   13221:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   13222:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   13223:      *    >>k'            11
                   13224:      *          &   00000001
                   13225:      *            = 00000001
                   13226:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   13227:      * Reverse h=6 and m=16?
                   13228:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   13229:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   13230:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   13231:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   13232:      * V3=decodtabm(14,3,2**4)=2
                   13233:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   13234:      *(h-1) >> (j-1)    0011 =13 >> 2
                   13235:      *          &1 000000001
                   13236:      *           = 000000001
                   13237:      *         +1= 000000010 =2
                   13238:      *                  2211
                   13239:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   13240:      *                  V3=2
1.220     brouard  13241:                 * codtabm and decodtabm are identical
1.211     brouard  13242:      */
                   13243: 
1.145     brouard  13244: 
                   13245:  free_ivector(Ndum,-1,NCOVMAX);
                   13246: 
                   13247: 
1.126     brouard  13248:     
1.186     brouard  13249:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  13250:   strcpy(optionfilegnuplot,optionfilefiname);
                   13251:   if(mle==-3)
1.201     brouard  13252:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  13253:   strcat(optionfilegnuplot,".gp");
                   13254: 
                   13255:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   13256:     printf("Problem with file %s",optionfilegnuplot);
                   13257:   }
                   13258:   else{
1.204     brouard  13259:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  13260:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  13261:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   13262:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  13263:   }
                   13264:   /*  fclose(ficgp);*/
1.186     brouard  13265: 
                   13266: 
                   13267:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  13268: 
                   13269:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   13270:   if(mle==-3)
1.201     brouard  13271:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  13272:   strcat(optionfilehtm,".htm");
                   13273:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  13274:     printf("Problem with %s \n",optionfilehtm);
                   13275:     exit(0);
1.126     brouard  13276:   }
                   13277: 
                   13278:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   13279:   strcat(optionfilehtmcov,"-cov.htm");
                   13280:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   13281:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   13282:   }
                   13283:   else{
                   13284:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   13285: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  13286: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  13287:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   13288:   }
                   13289: 
1.335     brouard  13290:   fprintf(fichtm,"<html><head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n\
                   13291: <title>IMaCh %s</title></head>\n\
                   13292:  <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n\
                   13293: <font size=\"3\">Sponsored by Copyright (C)  2002-2015 <a href=http://www.ined.fr>INED</a>\
                   13294: -EUROREVES-Institut de longévité-2013-2022-Japan Society for the Promotion of Sciences 日本学術振興会 \
                   13295: (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - \
                   13296: <a href=https://software.intel.com/en-us>Intel Software 2015-2018</a></font><br> \n", optionfilehtm);
                   13297:   
                   13298:   fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  13299: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  13300: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.337     brouard  13301: 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  13302: \n\
                   13303: <hr  size=\"2\" color=\"#EC5E5E\">\
                   13304:  <ul><li><h4>Parameter files</h4>\n\
                   13305:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   13306:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   13307:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   13308:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   13309:  - Date and time at start: %s</ul>\n",\
1.335     brouard  13310:          version,fullversion,optionfilehtm,optionfilehtm,title,datafile,datafile,firstpass,lastpass,stepm, weightopt, model, \
1.126     brouard  13311:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   13312:          fileres,fileres,\
                   13313:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   13314:   fflush(fichtm);
                   13315: 
                   13316:   strcpy(pathr,path);
                   13317:   strcat(pathr,optionfilefiname);
1.184     brouard  13318: #ifdef WIN32
                   13319:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   13320: #else
1.126     brouard  13321:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  13322: #endif
                   13323:          
1.126     brouard  13324:   
1.220     brouard  13325:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   13326:                 and for any valid combination of covariates
1.126     brouard  13327:      and prints on file fileres'p'. */
1.251     brouard  13328:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  13329:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  13330: 
                   13331:   fprintf(fichtm,"\n");
1.286     brouard  13332:   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  13333:          ftol, stepm);
                   13334:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   13335:   ncurrv=1;
                   13336:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   13337:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   13338:   ncurrv=i;
                   13339:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  13340:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  13341:   ncurrv=i;
                   13342:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  13343:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  13344:   ncurrv=i;
                   13345:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   13346:   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", \
                   13347:           nlstate, ndeath, maxwav, mle, weightopt);
                   13348: 
                   13349:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   13350: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   13351: 
                   13352:   
1.317     brouard  13353:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Number of (used) observations=%d <br>\n\
1.126     brouard  13354: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   13355: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  13356:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  13357:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  13358:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   13359:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   13360:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   13361:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  13362: 
1.126     brouard  13363:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   13364:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   13365:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   13366: 
                   13367:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  13368:   /* For mortality only */
1.126     brouard  13369:   if (mle==-3){
1.136     brouard  13370:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  13371:     for(i=1;i<=NDIM;i++)
                   13372:       for(j=1;j<=NDIM;j++)
                   13373:        ximort[i][j]=0.;
1.186     brouard  13374:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  13375:     cens=ivector(firstobs,lastobs);
                   13376:     ageexmed=vector(firstobs,lastobs);
                   13377:     agecens=vector(firstobs,lastobs);
                   13378:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  13379:                
1.126     brouard  13380:     for (i=1; i<=imx; i++){
                   13381:       dcwave[i]=-1;
                   13382:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  13383:        if (s[m][i]>nlstate) {
                   13384:          dcwave[i]=m;
                   13385:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   13386:          break;
                   13387:        }
1.126     brouard  13388:     }
1.226     brouard  13389:     
1.126     brouard  13390:     for (i=1; i<=imx; i++) {
                   13391:       if (wav[i]>0){
1.226     brouard  13392:        ageexmed[i]=agev[mw[1][i]][i];
                   13393:        j=wav[i];
                   13394:        agecens[i]=1.; 
                   13395:        
                   13396:        if (ageexmed[i]> 1 && wav[i] > 0){
                   13397:          agecens[i]=agev[mw[j][i]][i];
                   13398:          cens[i]= 1;
                   13399:        }else if (ageexmed[i]< 1) 
                   13400:          cens[i]= -1;
                   13401:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   13402:          cens[i]=0 ;
1.126     brouard  13403:       }
                   13404:       else cens[i]=-1;
                   13405:     }
                   13406:     
                   13407:     for (i=1;i<=NDIM;i++) {
                   13408:       for (j=1;j<=NDIM;j++)
1.226     brouard  13409:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  13410:     }
                   13411:     
1.302     brouard  13412:     p[1]=0.0268; p[NDIM]=0.083;
                   13413:     /* printf("%lf %lf", p[1], p[2]); */
1.126     brouard  13414:     
                   13415:     
1.136     brouard  13416: #ifdef GSL
                   13417:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  13418: #else
1.126     brouard  13419:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  13420: #endif
1.201     brouard  13421:     strcpy(filerespow,"POW-MORT_"); 
                   13422:     strcat(filerespow,fileresu);
1.126     brouard  13423:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   13424:       printf("Problem with resultfile: %s\n", filerespow);
                   13425:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   13426:     }
1.136     brouard  13427: #ifdef GSL
                   13428:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  13429: #else
1.126     brouard  13430:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  13431: #endif
1.126     brouard  13432:     /*  for (i=1;i<=nlstate;i++)
                   13433:        for(j=1;j<=nlstate+ndeath;j++)
                   13434:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   13435:     */
                   13436:     fprintf(ficrespow,"\n");
1.136     brouard  13437: #ifdef GSL
                   13438:     /* gsl starts here */ 
                   13439:     T = gsl_multimin_fminimizer_nmsimplex;
                   13440:     gsl_multimin_fminimizer *sfm = NULL;
                   13441:     gsl_vector *ss, *x;
                   13442:     gsl_multimin_function minex_func;
                   13443: 
                   13444:     /* Initial vertex size vector */
                   13445:     ss = gsl_vector_alloc (NDIM);
                   13446:     
                   13447:     if (ss == NULL){
                   13448:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   13449:     }
                   13450:     /* Set all step sizes to 1 */
                   13451:     gsl_vector_set_all (ss, 0.001);
                   13452: 
                   13453:     /* Starting point */
1.126     brouard  13454:     
1.136     brouard  13455:     x = gsl_vector_alloc (NDIM);
                   13456:     
                   13457:     if (x == NULL){
                   13458:       gsl_vector_free(ss);
                   13459:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   13460:     }
                   13461:   
                   13462:     /* Initialize method and iterate */
                   13463:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  13464:     /*     gsl_vector_set(x, 0, 0.0268); */
                   13465:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  13466:     gsl_vector_set(x, 0, p[1]);
                   13467:     gsl_vector_set(x, 1, p[2]);
                   13468: 
                   13469:     minex_func.f = &gompertz_f;
                   13470:     minex_func.n = NDIM;
                   13471:     minex_func.params = (void *)&p; /* ??? */
                   13472:     
                   13473:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   13474:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   13475:     
                   13476:     printf("Iterations beginning .....\n\n");
                   13477:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   13478: 
                   13479:     iteri=0;
                   13480:     while (rval == GSL_CONTINUE){
                   13481:       iteri++;
                   13482:       status = gsl_multimin_fminimizer_iterate(sfm);
                   13483:       
                   13484:       if (status) printf("error: %s\n", gsl_strerror (status));
                   13485:       fflush(0);
                   13486:       
                   13487:       if (status) 
                   13488:         break;
                   13489:       
                   13490:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   13491:       ssval = gsl_multimin_fminimizer_size (sfm);
                   13492:       
                   13493:       if (rval == GSL_SUCCESS)
                   13494:         printf ("converged to a local maximum at\n");
                   13495:       
                   13496:       printf("%5d ", iteri);
                   13497:       for (it = 0; it < NDIM; it++){
                   13498:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   13499:       }
                   13500:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   13501:     }
                   13502:     
                   13503:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   13504:     
                   13505:     gsl_vector_free(x); /* initial values */
                   13506:     gsl_vector_free(ss); /* inital step size */
                   13507:     for (it=0; it<NDIM; it++){
                   13508:       p[it+1]=gsl_vector_get(sfm->x,it);
                   13509:       fprintf(ficrespow," %.12lf", p[it]);
                   13510:     }
                   13511:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   13512: #endif
                   13513: #ifdef POWELL
                   13514:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   13515: #endif  
1.126     brouard  13516:     fclose(ficrespow);
                   13517:     
1.203     brouard  13518:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  13519: 
                   13520:     for(i=1; i <=NDIM; i++)
                   13521:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  13522:                                matcov[i][j]=matcov[j][i];
1.126     brouard  13523:     
                   13524:     printf("\nCovariance matrix\n ");
1.203     brouard  13525:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  13526:     for(i=1; i <=NDIM; i++) {
                   13527:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  13528:                                printf("%f ",matcov[i][j]);
                   13529:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  13530:       }
1.203     brouard  13531:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  13532:     }
                   13533:     
                   13534:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  13535:     for (i=1;i<=NDIM;i++) {
1.126     brouard  13536:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  13537:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   13538:     }
1.302     brouard  13539:     lsurv=vector(agegomp,AGESUP);
                   13540:     lpop=vector(agegomp,AGESUP);
                   13541:     tpop=vector(agegomp,AGESUP);
1.126     brouard  13542:     lsurv[agegomp]=100000;
                   13543:     
                   13544:     for (k=agegomp;k<=AGESUP;k++) {
                   13545:       agemortsup=k;
                   13546:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   13547:     }
                   13548:     
                   13549:     for (k=agegomp;k<agemortsup;k++)
                   13550:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   13551:     
                   13552:     for (k=agegomp;k<agemortsup;k++){
                   13553:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   13554:       sumlpop=sumlpop+lpop[k];
                   13555:     }
                   13556:     
                   13557:     tpop[agegomp]=sumlpop;
                   13558:     for (k=agegomp;k<(agemortsup-3);k++){
                   13559:       /*  tpop[k+1]=2;*/
                   13560:       tpop[k+1]=tpop[k]-lpop[k];
                   13561:     }
                   13562:     
                   13563:     
                   13564:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   13565:     for (k=agegomp;k<(agemortsup-2);k++) 
                   13566:       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]);
                   13567:     
                   13568:     
                   13569:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  13570:                ageminpar=50;
                   13571:                agemaxpar=100;
1.194     brouard  13572:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   13573:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   13574: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13575: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   13576:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   13577: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13578: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  13579:     }else{
                   13580:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   13581:                        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  13582:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  13583:                }
1.201     brouard  13584:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  13585:                     stepm, weightopt,\
                   13586:                     model,imx,p,matcov,agemortsup);
                   13587:     
1.302     brouard  13588:     free_vector(lsurv,agegomp,AGESUP);
                   13589:     free_vector(lpop,agegomp,AGESUP);
                   13590:     free_vector(tpop,agegomp,AGESUP);
1.220     brouard  13591:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  13592:     free_ivector(dcwave,firstobs,lastobs);
                   13593:     free_vector(agecens,firstobs,lastobs);
                   13594:     free_vector(ageexmed,firstobs,lastobs);
                   13595:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  13596: #ifdef GSL
1.136     brouard  13597: #endif
1.186     brouard  13598:   } /* Endof if mle==-3 mortality only */
1.205     brouard  13599:   /* Standard  */
                   13600:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   13601:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   13602:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  13603:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  13604:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   13605:     for (k=1; k<=npar;k++)
                   13606:       printf(" %d %8.5f",k,p[k]);
                   13607:     printf("\n");
1.205     brouard  13608:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   13609:       /* mlikeli uses func not funcone */
1.247     brouard  13610:       /* for(i=1;i<nlstate;i++){ */
                   13611:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   13612:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   13613:       /* } */
1.205     brouard  13614:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   13615:     }
                   13616:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   13617:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   13618:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   13619:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   13620:     }
                   13621:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  13622:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   13623:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
1.335     brouard  13624:           /* exit(0); */
1.126     brouard  13625:     for (k=1; k<=npar;k++)
                   13626:       printf(" %d %8.5f",k,p[k]);
                   13627:     printf("\n");
                   13628:     
                   13629:     /*--------- results files --------------*/
1.283     brouard  13630:     /* 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  13631:     
                   13632:     
                   13633:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  13634:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); /* Printing model equation */
1.126     brouard  13635:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  13636: 
                   13637:     printf("#model=  1      +     age ");
                   13638:     fprintf(ficres,"#model=  1      +     age ");
                   13639:     fprintf(ficlog,"#model=  1      +     age ");
                   13640:     fprintf(fichtm,"\n<ul><li> model=1+age+%s\n \
                   13641: </ul>", model);
                   13642: 
                   13643:     fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">\n");
                   13644:     fprintf(fichtm, "<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   13645:     if(nagesqr==1){
                   13646:       printf("  + age*age  ");
                   13647:       fprintf(ficres,"  + age*age  ");
                   13648:       fprintf(ficlog,"  + age*age  ");
                   13649:       fprintf(fichtm, "<th>+ age*age</th>");
                   13650:     }
                   13651:     for(j=1;j <=ncovmodel-2;j++){
                   13652:       if(Typevar[j]==0) {
                   13653:        printf("  +      V%d  ",Tvar[j]);
                   13654:        fprintf(ficres,"  +      V%d  ",Tvar[j]);
                   13655:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   13656:        fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   13657:       }else if(Typevar[j]==1) {
                   13658:        printf("  +    V%d*age ",Tvar[j]);
                   13659:        fprintf(ficres,"  +    V%d*age ",Tvar[j]);
                   13660:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   13661:        fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   13662:       }else if(Typevar[j]==2) {
                   13663:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13664:        fprintf(ficres,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13665:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13666:        fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13667:       }
                   13668:     }
                   13669:     printf("\n");
                   13670:     fprintf(ficres,"\n");
                   13671:     fprintf(ficlog,"\n");
                   13672:     fprintf(fichtm, "</tr>");
                   13673:     fprintf(fichtm, "\n");
                   13674:     
                   13675:     
1.126     brouard  13676:     for(i=1,jk=1; i <=nlstate; i++){
                   13677:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  13678:        if (k != i) {
1.319     brouard  13679:          fprintf(fichtm, "<tr>");
1.225     brouard  13680:          printf("%d%d ",i,k);
                   13681:          fprintf(ficlog,"%d%d ",i,k);
                   13682:          fprintf(ficres,"%1d%1d ",i,k);
1.319     brouard  13683:          fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  13684:          for(j=1; j <=ncovmodel; j++){
                   13685:            printf("%12.7f ",p[jk]);
                   13686:            fprintf(ficlog,"%12.7f ",p[jk]);
                   13687:            fprintf(ficres,"%12.7f ",p[jk]);
1.319     brouard  13688:            fprintf(fichtm, "<td>%12.7f</td>",p[jk]);
1.225     brouard  13689:            jk++; 
                   13690:          }
                   13691:          printf("\n");
                   13692:          fprintf(ficlog,"\n");
                   13693:          fprintf(ficres,"\n");
1.319     brouard  13694:          fprintf(fichtm, "</tr>\n");
1.225     brouard  13695:        }
1.126     brouard  13696:       }
                   13697:     }
1.319     brouard  13698:     /* fprintf(fichtm,"</tr>\n"); */
                   13699:     fprintf(fichtm,"</table>\n");
                   13700:     fprintf(fichtm, "\n");
                   13701: 
1.203     brouard  13702:     if(mle != 0){
                   13703:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  13704:       ftolhess=ftol; /* Usually correct */
1.203     brouard  13705:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   13706:       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");
                   13707:       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  13708:       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  13709:       fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">");
                   13710:       fprintf(fichtm, "\n<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   13711:       if(nagesqr==1){
                   13712:        printf("  + age*age  ");
                   13713:        fprintf(ficres,"  + age*age  ");
                   13714:        fprintf(ficlog,"  + age*age  ");
                   13715:        fprintf(fichtm, "<th>+ age*age</th>");
                   13716:       }
                   13717:       for(j=1;j <=ncovmodel-2;j++){
                   13718:        if(Typevar[j]==0) {
                   13719:          printf("  +      V%d  ",Tvar[j]);
                   13720:          fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   13721:        }else if(Typevar[j]==1) {
                   13722:          printf("  +    V%d*age ",Tvar[j]);
                   13723:          fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   13724:        }else if(Typevar[j]==2) {
                   13725:          fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13726:        }
                   13727:       }
                   13728:       fprintf(fichtm, "</tr>\n");
                   13729:  
1.203     brouard  13730:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  13731:        for(k=1; k <=(nlstate+ndeath); k++){
                   13732:          if (k != i) {
1.319     brouard  13733:            fprintf(fichtm, "<tr valign=top>");
1.225     brouard  13734:            printf("%d%d ",i,k);
                   13735:            fprintf(ficlog,"%d%d ",i,k);
1.319     brouard  13736:            fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  13737:            for(j=1; j <=ncovmodel; j++){
1.319     brouard  13738:              wald=p[jk]/sqrt(matcov[jk][jk]);
1.324     brouard  13739:              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]));
                   13740:              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  13741:              if(fabs(wald) > 1.96){
1.321     brouard  13742:                fprintf(fichtm, "<td><b>%12.7f</b></br> (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
1.319     brouard  13743:              }else{
                   13744:                fprintf(fichtm, "<td>%12.7f (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
                   13745:              }
1.324     brouard  13746:              fprintf(fichtm,"W=%8.3f</br>",wald);
1.319     brouard  13747:              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  13748:              jk++; 
                   13749:            }
                   13750:            printf("\n");
                   13751:            fprintf(ficlog,"\n");
1.319     brouard  13752:            fprintf(fichtm, "</tr>\n");
1.225     brouard  13753:          }
                   13754:        }
1.193     brouard  13755:       }
1.203     brouard  13756:     } /* end of hesscov and Wald tests */
1.319     brouard  13757:     fprintf(fichtm,"</table>\n");
1.225     brouard  13758:     
1.203     brouard  13759:     /*  */
1.126     brouard  13760:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   13761:     printf("# Scales (for hessian or gradient estimation)\n");
                   13762:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   13763:     for(i=1,jk=1; i <=nlstate; i++){
                   13764:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  13765:        if (j!=i) {
                   13766:          fprintf(ficres,"%1d%1d",i,j);
                   13767:          printf("%1d%1d",i,j);
                   13768:          fprintf(ficlog,"%1d%1d",i,j);
                   13769:          for(k=1; k<=ncovmodel;k++){
                   13770:            printf(" %.5e",delti[jk]);
                   13771:            fprintf(ficlog," %.5e",delti[jk]);
                   13772:            fprintf(ficres," %.5e",delti[jk]);
                   13773:            jk++;
                   13774:          }
                   13775:          printf("\n");
                   13776:          fprintf(ficlog,"\n");
                   13777:          fprintf(ficres,"\n");
                   13778:        }
1.126     brouard  13779:       }
                   13780:     }
                   13781:     
                   13782:     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  13783:     if(mle >= 1) /* To big for the screen */
1.126     brouard  13784:       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");
                   13785:     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");
                   13786:     /* # 121 Var(a12)\n\ */
                   13787:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   13788:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   13789:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   13790:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   13791:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   13792:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   13793:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   13794:     
                   13795:     
                   13796:     /* Just to have a covariance matrix which will be more understandable
                   13797:        even is we still don't want to manage dictionary of variables
                   13798:     */
                   13799:     for(itimes=1;itimes<=2;itimes++){
                   13800:       jj=0;
                   13801:       for(i=1; i <=nlstate; i++){
1.225     brouard  13802:        for(j=1; j <=nlstate+ndeath; j++){
                   13803:          if(j==i) continue;
                   13804:          for(k=1; k<=ncovmodel;k++){
                   13805:            jj++;
                   13806:            ca[0]= k+'a'-1;ca[1]='\0';
                   13807:            if(itimes==1){
                   13808:              if(mle>=1)
                   13809:                printf("#%1d%1d%d",i,j,k);
                   13810:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   13811:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   13812:            }else{
                   13813:              if(mle>=1)
                   13814:                printf("%1d%1d%d",i,j,k);
                   13815:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   13816:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   13817:            }
                   13818:            ll=0;
                   13819:            for(li=1;li <=nlstate; li++){
                   13820:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   13821:                if(lj==li) continue;
                   13822:                for(lk=1;lk<=ncovmodel;lk++){
                   13823:                  ll++;
                   13824:                  if(ll<=jj){
                   13825:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   13826:                    if(ll<jj){
                   13827:                      if(itimes==1){
                   13828:                        if(mle>=1)
                   13829:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13830:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13831:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13832:                      }else{
                   13833:                        if(mle>=1)
                   13834:                          printf(" %.5e",matcov[jj][ll]); 
                   13835:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   13836:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   13837:                      }
                   13838:                    }else{
                   13839:                      if(itimes==1){
                   13840:                        if(mle>=1)
                   13841:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   13842:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   13843:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   13844:                      }else{
                   13845:                        if(mle>=1)
                   13846:                          printf(" %.7e",matcov[jj][ll]); 
                   13847:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   13848:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   13849:                      }
                   13850:                    }
                   13851:                  }
                   13852:                } /* end lk */
                   13853:              } /* end lj */
                   13854:            } /* end li */
                   13855:            if(mle>=1)
                   13856:              printf("\n");
                   13857:            fprintf(ficlog,"\n");
                   13858:            fprintf(ficres,"\n");
                   13859:            numlinepar++;
                   13860:          } /* end k*/
                   13861:        } /*end j */
1.126     brouard  13862:       } /* end i */
                   13863:     } /* end itimes */
                   13864:     
                   13865:     fflush(ficlog);
                   13866:     fflush(ficres);
1.225     brouard  13867:     while(fgets(line, MAXLINE, ficpar)) {
                   13868:       /* If line starts with a # it is a comment */
                   13869:       if (line[0] == '#') {
                   13870:        numlinepar++;
                   13871:        fputs(line,stdout);
                   13872:        fputs(line,ficparo);
                   13873:        fputs(line,ficlog);
1.299     brouard  13874:        fputs(line,ficres);
1.225     brouard  13875:        continue;
                   13876:       }else
                   13877:        break;
                   13878:     }
                   13879:     
1.209     brouard  13880:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   13881:     /*   ungetc(c,ficpar); */
                   13882:     /*   fgets(line, MAXLINE, ficpar); */
                   13883:     /*   fputs(line,stdout); */
                   13884:     /*   fputs(line,ficparo); */
                   13885:     /* } */
                   13886:     /* ungetc(c,ficpar); */
1.126     brouard  13887:     
                   13888:     estepm=0;
1.209     brouard  13889:     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  13890:       
                   13891:       if (num_filled != 6) {
                   13892:        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);
                   13893:        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);
                   13894:        goto end;
                   13895:       }
                   13896:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   13897:     }
                   13898:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   13899:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   13900:     
1.209     brouard  13901:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  13902:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   13903:     if (fage <= 2) {
                   13904:       bage = ageminpar;
                   13905:       fage = agemaxpar;
                   13906:     }
                   13907:     
                   13908:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  13909:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   13910:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  13911:                
1.186     brouard  13912:     /* Other stuffs, more or less useful */    
1.254     brouard  13913:     while(fgets(line, MAXLINE, ficpar)) {
                   13914:       /* If line starts with a # it is a comment */
                   13915:       if (line[0] == '#') {
                   13916:        numlinepar++;
                   13917:        fputs(line,stdout);
                   13918:        fputs(line,ficparo);
                   13919:        fputs(line,ficlog);
1.299     brouard  13920:        fputs(line,ficres);
1.254     brouard  13921:        continue;
                   13922:       }else
                   13923:        break;
                   13924:     }
                   13925: 
                   13926:     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){
                   13927:       
                   13928:       if (num_filled != 7) {
                   13929:        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);
                   13930:        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);
                   13931:        goto end;
                   13932:       }
                   13933:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   13934:       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);
                   13935:       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);
                   13936:       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  13937:     }
1.254     brouard  13938: 
                   13939:     while(fgets(line, MAXLINE, ficpar)) {
                   13940:       /* If line starts with a # it is a comment */
                   13941:       if (line[0] == '#') {
                   13942:        numlinepar++;
                   13943:        fputs(line,stdout);
                   13944:        fputs(line,ficparo);
                   13945:        fputs(line,ficlog);
1.299     brouard  13946:        fputs(line,ficres);
1.254     brouard  13947:        continue;
                   13948:       }else
                   13949:        break;
1.126     brouard  13950:     }
                   13951:     
                   13952:     
                   13953:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   13954:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   13955:     
1.254     brouard  13956:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   13957:       if (num_filled != 1) {
                   13958:        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);
                   13959:        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);
                   13960:        goto end;
                   13961:       }
                   13962:       printf("pop_based=%d\n",popbased);
                   13963:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   13964:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   13965:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   13966:     }
                   13967:      
1.258     brouard  13968:     /* Results */
1.332     brouard  13969:     /* Value of covariate in each resultine will be compututed (if product) and sorted according to model rank */
                   13970:     /* It is precov[] because we need the varying age in order to compute the real cov[] of the model equation */  
                   13971:     precov=matrix(1,MAXRESULTLINESPONE,1,NCOVMAX+1);
1.307     brouard  13972:     endishere=0;
1.258     brouard  13973:     nresult=0;
1.308     brouard  13974:     parameterline=0;
1.258     brouard  13975:     do{
                   13976:       if(!fgets(line, MAXLINE, ficpar)){
                   13977:        endishere=1;
1.308     brouard  13978:        parameterline=15;
1.258     brouard  13979:       }else if (line[0] == '#') {
                   13980:        /* If line starts with a # it is a comment */
1.254     brouard  13981:        numlinepar++;
                   13982:        fputs(line,stdout);
                   13983:        fputs(line,ficparo);
                   13984:        fputs(line,ficlog);
1.299     brouard  13985:        fputs(line,ficres);
1.254     brouard  13986:        continue;
1.258     brouard  13987:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   13988:        parameterline=11;
1.296     brouard  13989:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  13990:        parameterline=12;
1.307     brouard  13991:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
1.258     brouard  13992:        parameterline=13;
1.307     brouard  13993:       }
1.258     brouard  13994:       else{
                   13995:        parameterline=14;
1.254     brouard  13996:       }
1.308     brouard  13997:       switch (parameterline){ /* =0 only if only comments */
1.258     brouard  13998:       case 11:
1.296     brouard  13999:        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)){
                   14000:                  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  14001:          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);
                   14002:          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);
                   14003:          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);
                   14004:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  14005:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   14006:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  14007:           prvforecast = 1;
                   14008:        } 
                   14009:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.313     brouard  14010:          printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   14011:          fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   14012:          fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  14013:           prvforecast = 2;
                   14014:        }
                   14015:        else {
                   14016:          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);
                   14017:          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);
                   14018:          goto end;
1.258     brouard  14019:        }
1.254     brouard  14020:        break;
1.258     brouard  14021:       case 12:
1.296     brouard  14022:        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)){
                   14023:           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);
                   14024:          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);
                   14025:          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);
                   14026:          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);
                   14027:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  14028:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   14029:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  14030:           prvbackcast = 1;
                   14031:        } 
                   14032:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.313     brouard  14033:          printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   14034:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   14035:          fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  14036:           prvbackcast = 2;
                   14037:        }
                   14038:        else {
                   14039:          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);
                   14040:          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);
                   14041:          goto end;
1.258     brouard  14042:        }
1.230     brouard  14043:        break;
1.258     brouard  14044:       case 13:
1.332     brouard  14045:        num_filled=sscanf(line,"result:%[^\n]\n",resultlineori);
1.307     brouard  14046:        nresult++; /* Sum of resultlines */
1.342     brouard  14047:        /* printf("Result %d: result:%s\n",nresult, resultlineori); */
1.332     brouard  14048:        /* removefirstspace(&resultlineori); */
                   14049:        
                   14050:        if(strstr(resultlineori,"v") !=0){
                   14051:          printf("Error. 'v' must be in upper case 'V' result: %s ",resultlineori);
                   14052:          fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultlineori);fflush(ficlog);
                   14053:          return 1;
                   14054:        }
                   14055:        trimbb(resultline, resultlineori); /* Suppressing double blank in the resultline */
1.342     brouard  14056:        /* printf("Decoderesult resultline=\"%s\" resultlineori=\"%s\"\n", resultline, resultlineori); */
1.318     brouard  14057:        if(nresult > MAXRESULTLINESPONE-1){
                   14058:          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);
                   14059:          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  14060:          goto end;
                   14061:        }
1.332     brouard  14062:        
1.310     brouard  14063:        if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.314     brouard  14064:          fprintf(ficparo,"result: %s\n",resultline);
                   14065:          fprintf(ficres,"result: %s\n",resultline);
                   14066:          fprintf(ficlog,"result: %s\n",resultline);
1.310     brouard  14067:        } else
                   14068:          goto end;
1.307     brouard  14069:        break;
                   14070:       case 14:
                   14071:        printf("Error: Unknown command '%s'\n",line);
                   14072:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
1.314     brouard  14073:        if(line[0] == ' ' || line[0] == '\n'){
                   14074:          printf("It should not be an empty line '%s'\n",line);
                   14075:          fprintf(ficlog,"It should not be an empty line '%s'\n",line);
                   14076:        }         
1.307     brouard  14077:        if(ncovmodel >=2 && nresult==0 ){
                   14078:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   14079:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  14080:        }
1.307     brouard  14081:        /* goto end; */
                   14082:        break;
1.308     brouard  14083:       case 15:
                   14084:        printf("End of resultlines.\n");
                   14085:        fprintf(ficlog,"End of resultlines.\n");
                   14086:        break;
                   14087:       default: /* parameterline =0 */
1.307     brouard  14088:        nresult=1;
                   14089:        decoderesult(".",nresult ); /* No covariate */
1.258     brouard  14090:       } /* End switch parameterline */
                   14091:     }while(endishere==0); /* End do */
1.126     brouard  14092:     
1.230     brouard  14093:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  14094:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  14095:     
                   14096:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  14097:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  14098:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  14099: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14100: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  14101:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  14102: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14103: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  14104:     }else{
1.270     brouard  14105:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  14106:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   14107:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   14108:       if(prvforecast==1){
                   14109:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   14110:         jprojd=jproj1;
                   14111:         mprojd=mproj1;
                   14112:         anprojd=anproj1;
                   14113:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   14114:         jprojf=jproj2;
                   14115:         mprojf=mproj2;
                   14116:         anprojf=anproj2;
                   14117:       } else if(prvforecast == 2){
                   14118:         dateprojd=dateintmean;
                   14119:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   14120:         dateprojf=dateintmean+yrfproj;
                   14121:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   14122:       }
                   14123:       if(prvbackcast==1){
                   14124:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   14125:         jbackd=jback1;
                   14126:         mbackd=mback1;
                   14127:         anbackd=anback1;
                   14128:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   14129:         jbackf=jback2;
                   14130:         mbackf=mback2;
                   14131:         anbackf=anback2;
                   14132:       } else if(prvbackcast == 2){
                   14133:         datebackd=dateintmean;
                   14134:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   14135:         datebackf=dateintmean-yrbproj;
                   14136:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   14137:       }
                   14138:       
                   14139:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);
1.220     brouard  14140:     }
                   14141:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  14142:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   14143:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  14144:                
1.225     brouard  14145:     /*------------ free_vector  -------------*/
                   14146:     /*  chdir(path); */
1.220     brouard  14147:                
1.215     brouard  14148:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   14149:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   14150:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   14151:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  14152:     free_lvector(num,firstobs,lastobs);
                   14153:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  14154:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   14155:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   14156:     fclose(ficparo);
                   14157:     fclose(ficres);
1.220     brouard  14158:                
                   14159:                
1.186     brouard  14160:     /* Other results (useful)*/
1.220     brouard  14161:                
                   14162:                
1.126     brouard  14163:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  14164:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   14165:     prlim=matrix(1,nlstate,1,nlstate);
1.332     brouard  14166:     /* Computes the prevalence limit for each combination k of the dummy covariates by calling prevalim(k) */
1.209     brouard  14167:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  14168:     fclose(ficrespl);
                   14169: 
                   14170:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  14171:     /*#include "hpijx.h"*/
1.332     brouard  14172:     /** 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?*/
                   14173:     /* calls hpxij with combination k */
1.180     brouard  14174:     hPijx(p, bage, fage);
1.145     brouard  14175:     fclose(ficrespij);
1.227     brouard  14176:     
1.220     brouard  14177:     /* ncovcombmax=  pow(2,cptcoveff); */
1.332     brouard  14178:     /*-------------- Variance of one-step probabilities for a combination ij or for nres ?---*/
1.145     brouard  14179:     k=1;
1.126     brouard  14180:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  14181:     
1.269     brouard  14182:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   14183:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   14184:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  14185:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  14186:        for(k=1;k<=ncovcombmax;k++)
                   14187:          probs[i][j][k]=0.;
1.269     brouard  14188:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   14189:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  14190:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  14191:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   14192:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  14193:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  14194:          for(k=1;k<=ncovcombmax;k++)
                   14195:            mobaverages[i][j][k]=0.;
1.219     brouard  14196:       mobaverage=mobaverages;
                   14197:       if (mobilav!=0) {
1.235     brouard  14198:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  14199:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  14200:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   14201:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   14202:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   14203:        }
1.269     brouard  14204:       } else if (mobilavproj !=0) {
1.235     brouard  14205:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  14206:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  14207:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   14208:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   14209:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   14210:        }
1.269     brouard  14211:       }else{
                   14212:        printf("Internal error moving average\n");
                   14213:        fflush(stdout);
                   14214:        exit(1);
1.219     brouard  14215:       }
                   14216:     }/* end if moving average */
1.227     brouard  14217:     
1.126     brouard  14218:     /*---------- Forecasting ------------------*/
1.296     brouard  14219:     if(prevfcast==1){ 
                   14220:       /*   /\*    if(stepm ==1){*\/ */
                   14221:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   14222:       /*This done previously after freqsummary.*/
                   14223:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   14224:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   14225:       
                   14226:       /* } else if (prvforecast==2){ */
                   14227:       /*   /\*    if(stepm ==1){*\/ */
                   14228:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   14229:       /* } */
                   14230:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   14231:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  14232:     }
1.269     brouard  14233: 
1.296     brouard  14234:     /* Prevbcasting */
                   14235:     if(prevbcast==1){
1.219     brouard  14236:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   14237:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   14238:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   14239: 
                   14240:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   14241: 
                   14242:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  14243: 
1.219     brouard  14244:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   14245:       fclose(ficresplb);
                   14246: 
1.222     brouard  14247:       hBijx(p, bage, fage, mobaverage);
                   14248:       fclose(ficrespijb);
1.219     brouard  14249: 
1.296     brouard  14250:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   14251:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   14252:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   14253:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   14254:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   14255:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   14256: 
                   14257:       
1.269     brouard  14258:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  14259: 
                   14260:       
1.269     brouard  14261:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  14262:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   14263:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   14264:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  14265:     }    /* end  Prevbcasting */
1.268     brouard  14266:  
1.186     brouard  14267:  
                   14268:     /* ------ Other prevalence ratios------------ */
1.126     brouard  14269: 
1.215     brouard  14270:     free_ivector(wav,1,imx);
                   14271:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   14272:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   14273:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  14274:                
                   14275:                
1.127     brouard  14276:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  14277:                
1.201     brouard  14278:     strcpy(filerese,"E_");
                   14279:     strcat(filerese,fileresu);
1.126     brouard  14280:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   14281:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   14282:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   14283:     }
1.208     brouard  14284:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   14285:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  14286: 
                   14287:     pstamp(ficreseij);
1.219     brouard  14288:                
1.235     brouard  14289:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   14290:     if (cptcovn < 1){i1=1;}
                   14291:     
                   14292:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   14293:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  14294:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  14295:        continue;
1.219     brouard  14296:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  14297:       printf("\n#****** ");
1.225     brouard  14298:       for(j=1;j<=cptcoveff;j++) {
1.332     brouard  14299:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   14300:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.235     brouard  14301:       }
                   14302:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.337     brouard  14303:        printf(" V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]); /* TvarsQ[j] gives the name of the jth quantitative (fixed or time v) */
                   14304:        fprintf(ficreseij,"V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]);
1.219     brouard  14305:       }
                   14306:       fprintf(ficreseij,"******\n");
1.235     brouard  14307:       printf("******\n");
1.219     brouard  14308:       
                   14309:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   14310:       oldm=oldms;savm=savms;
1.330     brouard  14311:       /* 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  14312:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  14313:       
1.219     brouard  14314:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  14315:     }
                   14316:     fclose(ficreseij);
1.208     brouard  14317:     printf("done evsij\n");fflush(stdout);
                   14318:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  14319: 
1.218     brouard  14320:                
1.227     brouard  14321:     /*---------- State-specific expectancies and variances ------------*/
1.336     brouard  14322:     /* Should be moved in a function */                
1.201     brouard  14323:     strcpy(filerest,"T_");
                   14324:     strcat(filerest,fileresu);
1.127     brouard  14325:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   14326:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   14327:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   14328:     }
1.208     brouard  14329:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   14330:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  14331:     strcpy(fileresstde,"STDE_");
                   14332:     strcat(fileresstde,fileresu);
1.126     brouard  14333:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  14334:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   14335:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  14336:     }
1.227     brouard  14337:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   14338:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  14339: 
1.201     brouard  14340:     strcpy(filerescve,"CVE_");
                   14341:     strcat(filerescve,fileresu);
1.126     brouard  14342:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  14343:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   14344:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  14345:     }
1.227     brouard  14346:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   14347:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  14348: 
1.201     brouard  14349:     strcpy(fileresv,"V_");
                   14350:     strcat(fileresv,fileresu);
1.126     brouard  14351:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   14352:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   14353:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   14354:     }
1.227     brouard  14355:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   14356:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  14357: 
1.235     brouard  14358:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   14359:     if (cptcovn < 1){i1=1;}
                   14360:     
1.334     brouard  14361:     for(nres=1; nres <= nresult; nres++) /* For each resultline, find the combination and output results according to the values of dummies and then quanti.  */
                   14362:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying. For each nres and each value at position k
                   14363:                          * we know Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline
                   14364:                          * Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline 
                   14365:                          * and Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
                   14366:       /* */
                   14367:       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  14368:        continue;
1.321     brouard  14369:       printf("\n# model %s \n#****** Result for:", model);
                   14370:       fprintf(ficrest,"\n# model %s \n#****** Result for:", model);
                   14371:       fprintf(ficlog,"\n# model %s \n#****** Result for:", model);
1.334     brouard  14372:       /* It might not be a good idea to mix dummies and quantitative */
                   14373:       /* 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 *\/ */
                   14374:       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 */
                   14375:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* Output by variables in the resultline *\/ */
                   14376:        /* Tvaraff[j] is the name of the dummy variable in position j in the equation model:
                   14377:         * Tvaraff[1]@9={4, 3, 0, 0, 0, 0, 0, 0, 0}, in model=V5+V4+V3+V4*V3+V5*age
                   14378:         * (V5 is quanti) V4 and V3 are dummies
                   14379:         * TnsdVar[4] is the position 1 and TnsdVar[3]=2 in codtabm(k,l)(V4  V3)=V4  V3
                   14380:         *                                                              l=1 l=2
                   14381:         *                                                           k=1  1   1   0   0
                   14382:         *                                                           k=2  2   1   1   0
                   14383:         *                                                           k=3 [1] [2]  0   1
                   14384:         *                                                           k=4  2   2   1   1
                   14385:         * If nres=1 result: V3=1 V4=0 then k=3 and outputs
                   14386:         * If nres=2 result: V4=1 V3=0 then k=2 and outputs
                   14387:         * nres=1 =>k=3 j=1 V4= nbcode[4][codtabm(3,1)=1)=0; j=2  V3= nbcode[3][codtabm(3,2)=2]=1
                   14388:         * nres=2 =>k=2 j=1 V4= nbcode[4][codtabm(2,1)=2)=1; j=2  V3= nbcode[3][codtabm(2,2)=1]=0
                   14389:         */
                   14390:        /* Tvresult[nres][j] Name of the variable at position j in this resultline */
                   14391:        /* Tresult[nres][j] Value of this variable at position j could be a float if quantitative  */
                   14392: /* We give up with the combinations!! */
1.342     brouard  14393:        /* if(debugILK) */
                   14394:        /*   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  14395: 
                   14396:        if(Dummy[modelresult[nres][j]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to j in resultline  */
1.344     brouard  14397:          /* 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  *\/ */ /* TinvDoQresult[nres][Name of the variable] */
                   14398:          printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); /* Output of each value for the combination TKresult[nres], ordered by the covariate values in the resultline  */
                   14399:          fprintf(ficlog,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
                   14400:          fprintf(ficrest,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
1.334     brouard  14401:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   14402:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   14403:          }else{
                   14404:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   14405:          }
                   14406:          /* fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14407:          /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14408:        }else if(Dummy[modelresult[nres][j]]==1){ /* Quanti variable */
                   14409:          /* For each selected (single) quantitative value */
1.337     brouard  14410:          printf(" V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   14411:          fprintf(ficlog," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   14412:          fprintf(ficrest," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
1.334     brouard  14413:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   14414:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   14415:          }else{
                   14416:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   14417:          }
                   14418:        }else{
                   14419:          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 */
                   14420:          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 */
                   14421:          exit(1);
                   14422:        }
1.335     brouard  14423:       } /* End loop for each variable in the resultline */
1.334     brouard  14424:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   14425:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /\* Wrong j is not in the equation model *\/ */
                   14426:       /*       fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14427:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14428:       /* }      */
1.208     brouard  14429:       fprintf(ficrest,"******\n");
1.227     brouard  14430:       fprintf(ficlog,"******\n");
                   14431:       printf("******\n");
1.208     brouard  14432:       
                   14433:       fprintf(ficresstdeij,"\n#****** ");
                   14434:       fprintf(ficrescveij,"\n#****** ");
1.337     brouard  14435:       /* It could have been: for(j=1;j<=cptcoveff;j++) {printf("V=%d=%lg",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);} */
                   14436:       /* But it won't be sorted and depends on how the resultline is ordered */
1.225     brouard  14437:       for(j=1;j<=cptcoveff;j++) {
1.334     brouard  14438:        fprintf(ficresstdeij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   14439:        /* fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14440:        /* fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14441:       }
                   14442:       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  14443:        fprintf(ficresstdeij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
                   14444:        fprintf(ficrescveij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
1.235     brouard  14445:       }        
1.208     brouard  14446:       fprintf(ficresstdeij,"******\n");
                   14447:       fprintf(ficrescveij,"******\n");
                   14448:       
                   14449:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  14450:       /* pstamp(ficresvij); */
1.225     brouard  14451:       for(j=1;j<=cptcoveff;j++) 
1.335     brouard  14452:        fprintf(ficresvij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   14453:        /* fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[TnsdVar[Tvaraff[j]]])]); */
1.235     brouard  14454:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  14455:        /* fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]); /\* To solve *\/ */
1.337     brouard  14456:        fprintf(ficresvij," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /* Solved */
1.235     brouard  14457:       }        
1.208     brouard  14458:       fprintf(ficresvij,"******\n");
                   14459:       
                   14460:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   14461:       oldm=oldms;savm=savms;
1.235     brouard  14462:       printf(" cvevsij ");
                   14463:       fprintf(ficlog, " cvevsij ");
                   14464:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  14465:       printf(" end cvevsij \n ");
                   14466:       fprintf(ficlog, " end cvevsij \n ");
                   14467:       
                   14468:       /*
                   14469:        */
                   14470:       /* goto endfree; */
                   14471:       
                   14472:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   14473:       pstamp(ficrest);
                   14474:       
1.269     brouard  14475:       epj=vector(1,nlstate+1);
1.208     brouard  14476:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  14477:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   14478:        cptcod= 0; /* To be deleted */
                   14479:        printf("varevsij vpopbased=%d \n",vpopbased);
                   14480:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  14481:        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  14482:        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 ");
                   14483:        if(vpopbased==1)
                   14484:          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);
                   14485:        else
1.288     brouard  14486:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
1.335     brouard  14487:        fprintf(ficrest,"# Age popbased mobilav e.. (std) "); /* Adding covariate values? */
1.227     brouard  14488:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   14489:        fprintf(ficrest,"\n");
                   14490:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  14491:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   14492:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  14493:        for(age=bage; age <=fage ;age++){
1.235     brouard  14494:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  14495:          if (vpopbased==1) {
                   14496:            if(mobilav ==0){
                   14497:              for(i=1; i<=nlstate;i++)
                   14498:                prlim[i][i]=probs[(int)age][i][k];
                   14499:            }else{ /* mobilav */ 
                   14500:              for(i=1; i<=nlstate;i++)
                   14501:                prlim[i][i]=mobaverage[(int)age][i][k];
                   14502:            }
                   14503:          }
1.219     brouard  14504:          
1.227     brouard  14505:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   14506:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   14507:          /* printf(" age %4.0f ",age); */
                   14508:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   14509:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   14510:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   14511:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   14512:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   14513:            }
                   14514:            epj[nlstate+1] +=epj[j];
                   14515:          }
                   14516:          /* printf(" age %4.0f \n",age); */
1.219     brouard  14517:          
1.227     brouard  14518:          for(i=1, vepp=0.;i <=nlstate;i++)
                   14519:            for(j=1;j <=nlstate;j++)
                   14520:              vepp += vareij[i][j][(int)age];
                   14521:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   14522:          for(j=1;j <=nlstate;j++){
                   14523:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   14524:          }
                   14525:          fprintf(ficrest,"\n");
                   14526:        }
1.208     brouard  14527:       } /* End vpopbased */
1.269     brouard  14528:       free_vector(epj,1,nlstate+1);
1.208     brouard  14529:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   14530:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  14531:       printf("done selection\n");fflush(stdout);
                   14532:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  14533:       
1.335     brouard  14534:     } /* End k selection or end covariate selection for nres */
1.227     brouard  14535: 
                   14536:     printf("done State-specific expectancies\n");fflush(stdout);
                   14537:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   14538: 
1.335     brouard  14539:     /* variance-covariance of forward period prevalence */
1.269     brouard  14540:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  14541: 
1.227     brouard  14542:     
1.290     brouard  14543:     free_vector(weight,firstobs,lastobs);
1.330     brouard  14544:     free_imatrix(Tvardk,1,NCOVMAX,1,2);
1.227     brouard  14545:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  14546:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   14547:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   14548:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   14549:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  14550:     free_ivector(tab,1,NCOVMAX);
                   14551:     fclose(ficresstdeij);
                   14552:     fclose(ficrescveij);
                   14553:     fclose(ficresvij);
                   14554:     fclose(ficrest);
                   14555:     fclose(ficpar);
                   14556:     
                   14557:     
1.126     brouard  14558:     /*---------- End : free ----------------*/
1.219     brouard  14559:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  14560:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   14561:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  14562:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   14563:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  14564:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  14565:   /* endfree:*/
                   14566:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   14567:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   14568:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.341     brouard  14569:   /* if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs); */
                   14570:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);
1.290     brouard  14571:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   14572:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   14573:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  14574:   free_matrix(matcov,1,npar,1,npar);
                   14575:   free_matrix(hess,1,npar,1,npar);
                   14576:   /*free_vector(delti,1,npar);*/
                   14577:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   14578:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  14579:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  14580:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   14581:   
                   14582:   free_ivector(ncodemax,1,NCOVMAX);
                   14583:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   14584:   free_ivector(Dummy,-1,NCOVMAX);
                   14585:   free_ivector(Fixed,-1,NCOVMAX);
1.238     brouard  14586:   free_ivector(DummyV,1,NCOVMAX);
                   14587:   free_ivector(FixedV,1,NCOVMAX);
1.227     brouard  14588:   free_ivector(Typevar,-1,NCOVMAX);
                   14589:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  14590:   free_ivector(TvarsQ,1,NCOVMAX);
                   14591:   free_ivector(TvarsQind,1,NCOVMAX);
                   14592:   free_ivector(TvarsD,1,NCOVMAX);
1.330     brouard  14593:   free_ivector(TnsdVar,1,NCOVMAX);
1.234     brouard  14594:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  14595:   free_ivector(TvarFD,1,NCOVMAX);
                   14596:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  14597:   free_ivector(TvarF,1,NCOVMAX);
                   14598:   free_ivector(TvarFind,1,NCOVMAX);
                   14599:   free_ivector(TvarV,1,NCOVMAX);
                   14600:   free_ivector(TvarVind,1,NCOVMAX);
                   14601:   free_ivector(TvarA,1,NCOVMAX);
                   14602:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  14603:   free_ivector(TvarFQ,1,NCOVMAX);
                   14604:   free_ivector(TvarFQind,1,NCOVMAX);
                   14605:   free_ivector(TvarVD,1,NCOVMAX);
                   14606:   free_ivector(TvarVDind,1,NCOVMAX);
                   14607:   free_ivector(TvarVQ,1,NCOVMAX);
                   14608:   free_ivector(TvarVQind,1,NCOVMAX);
1.339     brouard  14609:   free_ivector(TvarVV,1,NCOVMAX);
                   14610:   free_ivector(TvarVVind,1,NCOVMAX);
                   14611:   
1.230     brouard  14612:   free_ivector(Tvarsel,1,NCOVMAX);
                   14613:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  14614:   free_ivector(Tposprod,1,NCOVMAX);
                   14615:   free_ivector(Tprod,1,NCOVMAX);
                   14616:   free_ivector(Tvaraff,1,NCOVMAX);
1.338     brouard  14617:   free_ivector(invalidvarcomb,0,ncovcombmax);
1.227     brouard  14618:   free_ivector(Tage,1,NCOVMAX);
                   14619:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  14620:   free_ivector(TmodelInvind,1,NCOVMAX);
                   14621:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.332     brouard  14622: 
                   14623:   free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /* Could be elsewhere ?*/
                   14624: 
1.227     brouard  14625:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   14626:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  14627:   fflush(fichtm);
                   14628:   fflush(ficgp);
                   14629:   
1.227     brouard  14630:   
1.126     brouard  14631:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  14632:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   14633:     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  14634:   }else{
                   14635:     printf("End of Imach\n");
                   14636:     fprintf(ficlog,"End of Imach\n");
                   14637:   }
                   14638:   printf("See log file on %s\n",filelog);
                   14639:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  14640:   /*(void) gettimeofday(&end_time,&tzp);*/
                   14641:   rend_time = time(NULL);  
                   14642:   end_time = *localtime(&rend_time);
                   14643:   /* tml = *localtime(&end_time.tm_sec); */
                   14644:   strcpy(strtend,asctime(&end_time));
1.126     brouard  14645:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   14646:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  14647:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  14648:   
1.157     brouard  14649:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   14650:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   14651:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  14652:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   14653: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   14654:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   14655:   fclose(fichtm);
                   14656:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   14657:   fclose(fichtmcov);
                   14658:   fclose(ficgp);
                   14659:   fclose(ficlog);
                   14660:   /*------ End -----------*/
1.227     brouard  14661:   
1.281     brouard  14662: 
                   14663: /* Executes gnuplot */
1.227     brouard  14664:   
                   14665:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  14666: #ifdef WIN32
1.227     brouard  14667:   if (_chdir(pathcd) != 0)
                   14668:     printf("Can't move to directory %s!\n",path);
                   14669:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  14670: #else
1.227     brouard  14671:     if(chdir(pathcd) != 0)
                   14672:       printf("Can't move to directory %s!\n", path);
                   14673:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  14674: #endif 
1.126     brouard  14675:     printf("Current directory %s!\n",pathcd);
                   14676:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   14677:   sprintf(plotcmd,"gnuplot");
1.157     brouard  14678: #ifdef _WIN32
1.126     brouard  14679:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   14680: #endif
                   14681:   if(!stat(plotcmd,&info)){
1.158     brouard  14682:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  14683:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  14684:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  14685:     }else
                   14686:       strcpy(pplotcmd,plotcmd);
1.157     brouard  14687: #ifdef __unix
1.126     brouard  14688:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   14689:     if(!stat(plotcmd,&info)){
1.158     brouard  14690:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  14691:     }else
                   14692:       strcpy(pplotcmd,plotcmd);
                   14693: #endif
                   14694:   }else
                   14695:     strcpy(pplotcmd,plotcmd);
                   14696:   
                   14697:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  14698:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  14699:   strcpy(pplotcmd,plotcmd);
1.227     brouard  14700:   
1.126     brouard  14701:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  14702:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  14703:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  14704:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  14705:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  14706:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  14707:       strcpy(plotcmd,pplotcmd);
                   14708:     }
1.126     brouard  14709:   }
1.158     brouard  14710:   printf(" Successful, please wait...");
1.126     brouard  14711:   while (z[0] != 'q') {
                   14712:     /* chdir(path); */
1.154     brouard  14713:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  14714:     scanf("%s",z);
                   14715: /*     if (z[0] == 'c') system("./imach"); */
                   14716:     if (z[0] == 'e') {
1.158     brouard  14717: #ifdef __APPLE__
1.152     brouard  14718:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  14719: #elif __linux
                   14720:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  14721: #else
1.152     brouard  14722:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  14723: #endif
                   14724:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   14725:       system(pplotcmd);
1.126     brouard  14726:     }
                   14727:     else if (z[0] == 'g') system(plotcmd);
                   14728:     else if (z[0] == 'q') exit(0);
                   14729:   }
1.227     brouard  14730: end:
1.126     brouard  14731:   while (z[0] != 'q') {
1.195     brouard  14732:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  14733:     scanf("%s",z);
                   14734:   }
1.283     brouard  14735:   printf("End\n");
1.282     brouard  14736:   exit(0);
1.126     brouard  14737: }

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