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

1.346   ! brouard     1: /* $Id: imach.c,v 1.345 2022/09/16 13:40:11 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.346   ! brouard     4:   Revision 1.345  2022/09/16 13:40:11  brouard
        !             5:   Summary: Version 0.99r41
        !             6: 
        !             7:   * imach.c (Module): 0.99r41 Was an error when product of timevarying and fixed. Using FixedV[of name] now. Thank you  Feinuo
        !             8: 
1.345     brouard     9:   Revision 1.344  2022/09/14 19:33:30  brouard
                     10:   Summary: version 0.99r40
                     11: 
                     12:   * imach.c (Module): Fixing names of variables in T_ (thanks to Feinuo)
                     13: 
1.344     brouard    14:   Revision 1.343  2022/09/14 14:22:16  brouard
                     15:   Summary: version 0.99r39
                     16: 
                     17:   * imach.c (Module): Version 0.99r39 with colored dummy covariates
                     18:   (fixed or time varying), using new last columns of
                     19:   ILK_parameter.txt file.
                     20: 
1.343     brouard    21:   Revision 1.342  2022/09/11 19:54:09  brouard
                     22:   Summary: 0.99r38
                     23: 
                     24:   * imach.c (Module): Adding timevarying products of any kinds,
                     25:   should work before shifting cotvar from ncovcol+nqv columns in
                     26:   order to have a correspondance between the column of cotvar and
                     27:   the id of column.
                     28:   (Module): Some cleaning and adding covariates in ILK.txt
                     29: 
1.342     brouard    30:   Revision 1.341  2022/09/11 07:58:42  brouard
                     31:   Summary: Version 0.99r38
                     32: 
                     33:   After adding change in cotvar.
                     34: 
1.341     brouard    35:   Revision 1.340  2022/09/11 07:53:11  brouard
                     36:   Summary: Version imach 0.99r37
                     37: 
                     38:   * imach.c (Module): Adding timevarying products of any kinds,
                     39:   should work before shifting cotvar from ncovcol+nqv columns in
                     40:   order to have a correspondance between the column of cotvar and
                     41:   the id of column.
                     42: 
1.340     brouard    43:   Revision 1.339  2022/09/09 17:55:22  brouard
                     44:   Summary: version 0.99r37
                     45: 
                     46:   * imach.c (Module): Many improvements for fixing products of fixed
                     47:   timevarying as well as fixed * fixed, and test with quantitative
                     48:   covariate.
                     49: 
1.339     brouard    50:   Revision 1.338  2022/09/04 17:40:33  brouard
                     51:   Summary: 0.99r36
                     52: 
                     53:   * imach.c (Module): Now the easy runs i.e. without result or
                     54:   model=1+age only did not work. The defautl combination should be 1
                     55:   and not 0 because everything hasn't been tranformed yet.
                     56: 
1.338     brouard    57:   Revision 1.337  2022/09/02 14:26:02  brouard
                     58:   Summary: version 0.99r35
                     59: 
                     60:   * src/imach.c: Version 0.99r35 because it outputs same results with
                     61:   1+age+V1+V1*age for females and 1+age for females only
                     62:   (education=1 noweight)
                     63: 
1.337     brouard    64:   Revision 1.336  2022/08/31 09:52:36  brouard
                     65:   *** empty log message ***
                     66: 
1.336     brouard    67:   Revision 1.335  2022/08/31 08:23:16  brouard
                     68:   Summary: improvements...
                     69: 
1.335     brouard    70:   Revision 1.334  2022/08/25 09:08:41  brouard
                     71:   Summary: In progress for quantitative
                     72: 
1.334     brouard    73:   Revision 1.333  2022/08/21 09:10:30  brouard
                     74:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                     75:   reassigning covariates: my first idea was that people will always
                     76:   use the first covariate V1 into the model but in fact they are
                     77:   producing data with many covariates and can use an equation model
                     78:   with some of the covariate; it means that in a model V2+V3 instead
                     79:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                     80:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                     81:   the equation model is restricted to two variables only (V2, V3)
                     82:   and the combination for V2 should be codtabm(k,1) instead of
                     83:   (codtabm(k,2), and the code should be
                     84:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                     85:   made. All of these should be simplified once a day like we did in
                     86:   hpxij() for example by using precov[nres] which is computed in
                     87:   decoderesult for each nres of each resultline. Loop should be done
                     88:   on the equation model globally by distinguishing only product with
                     89:   age (which are changing with age) and no more on type of
                     90:   covariates, single dummies, single covariates.
                     91: 
1.333     brouard    92:   Revision 1.332  2022/08/21 09:06:25  brouard
                     93:   Summary: Version 0.99r33
                     94: 
                     95:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                     96:   reassigning covariates: my first idea was that people will always
                     97:   use the first covariate V1 into the model but in fact they are
                     98:   producing data with many covariates and can use an equation model
                     99:   with some of the covariate; it means that in a model V2+V3 instead
                    100:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                    101:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                    102:   the equation model is restricted to two variables only (V2, V3)
                    103:   and the combination for V2 should be codtabm(k,1) instead of
                    104:   (codtabm(k,2), and the code should be
                    105:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                    106:   made. All of these should be simplified once a day like we did in
                    107:   hpxij() for example by using precov[nres] which is computed in
                    108:   decoderesult for each nres of each resultline. Loop should be done
                    109:   on the equation model globally by distinguishing only product with
                    110:   age (which are changing with age) and no more on type of
                    111:   covariates, single dummies, single covariates.
                    112: 
1.332     brouard   113:   Revision 1.331  2022/08/07 05:40:09  brouard
                    114:   *** empty log message ***
                    115: 
1.331     brouard   116:   Revision 1.330  2022/08/06 07:18:25  brouard
                    117:   Summary: last 0.99r31
                    118: 
                    119:   *  imach.c (Module): Version of imach using partly decoderesult to rebuild xpxij function
                    120: 
1.330     brouard   121:   Revision 1.329  2022/08/03 17:29:54  brouard
                    122:   *  imach.c (Module): Many errors in graphs fixed with Vn*age covariates.
                    123: 
1.329     brouard   124:   Revision 1.328  2022/07/27 17:40:48  brouard
                    125:   Summary: valgrind bug fixed by initializing to zero DummyV as well as Tage
                    126: 
1.328     brouard   127:   Revision 1.327  2022/07/27 14:47:35  brouard
                    128:   Summary: Still a problem for one-step probabilities in case of quantitative variables
                    129: 
1.327     brouard   130:   Revision 1.326  2022/07/26 17:33:55  brouard
                    131:   Summary: some test with nres=1
                    132: 
1.326     brouard   133:   Revision 1.325  2022/07/25 14:27:23  brouard
                    134:   Summary: r30
                    135: 
                    136:   * imach.c (Module): Error cptcovn instead of nsd in bmij (was
                    137:   coredumped, revealed by Feiuno, thank you.
                    138: 
1.325     brouard   139:   Revision 1.324  2022/07/23 17:44:26  brouard
                    140:   *** empty log message ***
                    141: 
1.324     brouard   142:   Revision 1.323  2022/07/22 12:30:08  brouard
                    143:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    144: 
1.323     brouard   145:   Revision 1.322  2022/07/22 12:27:48  brouard
                    146:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    147: 
1.322     brouard   148:   Revision 1.321  2022/07/22 12:04:24  brouard
                    149:   Summary: r28
                    150: 
                    151:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    152: 
1.321     brouard   153:   Revision 1.320  2022/06/02 05:10:11  brouard
                    154:   *** empty log message ***
                    155: 
1.320     brouard   156:   Revision 1.319  2022/06/02 04:45:11  brouard
                    157:   * imach.c (Module): Adding the Wald tests from the log to the main
                    158:   htm for better display of the maximum likelihood estimators.
                    159: 
1.319     brouard   160:   Revision 1.318  2022/05/24 08:10:59  brouard
                    161:   * imach.c (Module): Some attempts to find a bug of wrong estimates
                    162:   of confidencce intervals with product in the equation modelC
                    163: 
1.318     brouard   164:   Revision 1.317  2022/05/15 15:06:23  brouard
                    165:   * imach.c (Module):  Some minor improvements
                    166: 
1.317     brouard   167:   Revision 1.316  2022/05/11 15:11:31  brouard
                    168:   Summary: r27
                    169: 
1.316     brouard   170:   Revision 1.315  2022/05/11 15:06:32  brouard
                    171:   *** empty log message ***
                    172: 
1.315     brouard   173:   Revision 1.314  2022/04/13 17:43:09  brouard
                    174:   * imach.c (Module): Adding link to text data files
                    175: 
1.314     brouard   176:   Revision 1.313  2022/04/11 15:57:42  brouard
                    177:   * imach.c (Module): Error in rewriting the 'r' file with yearsfproj or yearsbproj fixed
                    178: 
1.313     brouard   179:   Revision 1.312  2022/04/05 21:24:39  brouard
                    180:   *** empty log message ***
                    181: 
1.312     brouard   182:   Revision 1.311  2022/04/05 21:03:51  brouard
                    183:   Summary: Fixed quantitative covariates
                    184: 
                    185:          Fixed covariates (dummy or quantitative)
                    186:        with missing values have never been allowed but are ERRORS and
                    187:        program quits. Standard deviations of fixed covariates were
                    188:        wrongly computed. Mean and standard deviations of time varying
                    189:        covariates are still not computed.
                    190: 
1.311     brouard   191:   Revision 1.310  2022/03/17 08:45:53  brouard
                    192:   Summary: 99r25
                    193: 
                    194:   Improving detection of errors: result lines should be compatible with
                    195:   the model.
                    196: 
1.310     brouard   197:   Revision 1.309  2021/05/20 12:39:14  brouard
                    198:   Summary: Version 0.99r24
                    199: 
1.309     brouard   200:   Revision 1.308  2021/03/31 13:11:57  brouard
                    201:   Summary: Version 0.99r23
                    202: 
                    203: 
                    204:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
                    205: 
1.308     brouard   206:   Revision 1.307  2021/03/08 18:11:32  brouard
                    207:   Summary: 0.99r22 fixed bug on result:
                    208: 
1.307     brouard   209:   Revision 1.306  2021/02/20 15:44:02  brouard
                    210:   Summary: Version 0.99r21
                    211: 
                    212:   * imach.c (Module): Fix bug on quitting after result lines!
                    213:   (Module): Version 0.99r21
                    214: 
1.306     brouard   215:   Revision 1.305  2021/02/20 15:28:30  brouard
                    216:   * imach.c (Module): Fix bug on quitting after result lines!
                    217: 
1.305     brouard   218:   Revision 1.304  2021/02/12 11:34:20  brouard
                    219:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
                    220: 
1.304     brouard   221:   Revision 1.303  2021/02/11 19:50:15  brouard
                    222:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
                    223: 
1.303     brouard   224:   Revision 1.302  2020/02/22 21:00:05  brouard
                    225:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
                    226:   and life table from the data without any state)
                    227: 
1.302     brouard   228:   Revision 1.301  2019/06/04 13:51:20  brouard
                    229:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                    230: 
1.301     brouard   231:   Revision 1.300  2019/05/22 19:09:45  brouard
                    232:   Summary: version 0.99r19 of May 2019
                    233: 
1.300     brouard   234:   Revision 1.299  2019/05/22 18:37:08  brouard
                    235:   Summary: Cleaned 0.99r19
                    236: 
1.299     brouard   237:   Revision 1.298  2019/05/22 18:19:56  brouard
                    238:   *** empty log message ***
                    239: 
1.298     brouard   240:   Revision 1.297  2019/05/22 17:56:10  brouard
                    241:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                    242: 
1.297     brouard   243:   Revision 1.296  2019/05/20 13:03:18  brouard
                    244:   Summary: Projection syntax simplified
                    245: 
                    246: 
                    247:   We can now start projections, forward or backward, from the mean date
                    248:   of inteviews up to or down to a number of years of projection:
                    249:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                    250:   or
                    251:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                    252:   or
                    253:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                    254:   or
                    255:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                    256: 
1.296     brouard   257:   Revision 1.295  2019/05/18 09:52:50  brouard
                    258:   Summary: doxygen tex bug
                    259: 
1.295     brouard   260:   Revision 1.294  2019/05/16 14:54:33  brouard
                    261:   Summary: There was some wrong lines added
                    262: 
1.294     brouard   263:   Revision 1.293  2019/05/09 15:17:34  brouard
                    264:   *** empty log message ***
                    265: 
1.293     brouard   266:   Revision 1.292  2019/05/09 14:17:20  brouard
                    267:   Summary: Some updates
                    268: 
1.292     brouard   269:   Revision 1.291  2019/05/09 13:44:18  brouard
                    270:   Summary: Before ncovmax
                    271: 
1.291     brouard   272:   Revision 1.290  2019/05/09 13:39:37  brouard
                    273:   Summary: 0.99r18 unlimited number of individuals
                    274: 
                    275:   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.
                    276: 
1.290     brouard   277:   Revision 1.289  2018/12/13 09:16:26  brouard
                    278:   Summary: Bug for young ages (<-30) will be in r17
                    279: 
1.289     brouard   280:   Revision 1.288  2018/05/02 20:58:27  brouard
                    281:   Summary: Some bugs fixed
                    282: 
1.288     brouard   283:   Revision 1.287  2018/05/01 17:57:25  brouard
                    284:   Summary: Bug fixed by providing frequencies only for non missing covariates
                    285: 
1.287     brouard   286:   Revision 1.286  2018/04/27 14:27:04  brouard
                    287:   Summary: some minor bugs
                    288: 
1.286     brouard   289:   Revision 1.285  2018/04/21 21:02:16  brouard
                    290:   Summary: Some bugs fixed, valgrind tested
                    291: 
1.285     brouard   292:   Revision 1.284  2018/04/20 05:22:13  brouard
                    293:   Summary: Computing mean and stdeviation of fixed quantitative variables
                    294: 
1.284     brouard   295:   Revision 1.283  2018/04/19 14:49:16  brouard
                    296:   Summary: Some minor bugs fixed
                    297: 
1.283     brouard   298:   Revision 1.282  2018/02/27 22:50:02  brouard
                    299:   *** empty log message ***
                    300: 
1.282     brouard   301:   Revision 1.281  2018/02/27 19:25:23  brouard
                    302:   Summary: Adding second argument for quitting
                    303: 
1.281     brouard   304:   Revision 1.280  2018/02/21 07:58:13  brouard
                    305:   Summary: 0.99r15
                    306: 
                    307:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                    308: 
1.280     brouard   309:   Revision 1.279  2017/07/20 13:35:01  brouard
                    310:   Summary: temporary working
                    311: 
1.279     brouard   312:   Revision 1.278  2017/07/19 14:09:02  brouard
                    313:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                    314: 
1.278     brouard   315:   Revision 1.277  2017/07/17 08:53:49  brouard
                    316:   Summary: BOM files can be read now
                    317: 
1.277     brouard   318:   Revision 1.276  2017/06/30 15:48:31  brouard
                    319:   Summary: Graphs improvements
                    320: 
1.276     brouard   321:   Revision 1.275  2017/06/30 13:39:33  brouard
                    322:   Summary: Saito's color
                    323: 
1.275     brouard   324:   Revision 1.274  2017/06/29 09:47:08  brouard
                    325:   Summary: Version 0.99r14
                    326: 
1.274     brouard   327:   Revision 1.273  2017/06/27 11:06:02  brouard
                    328:   Summary: More documentation on projections
                    329: 
1.273     brouard   330:   Revision 1.272  2017/06/27 10:22:40  brouard
                    331:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    332: 
1.272     brouard   333:   Revision 1.271  2017/06/27 10:17:50  brouard
                    334:   Summary: Some bug with rint
                    335: 
1.271     brouard   336:   Revision 1.270  2017/05/24 05:45:29  brouard
                    337:   *** empty log message ***
                    338: 
1.270     brouard   339:   Revision 1.269  2017/05/23 08:39:25  brouard
                    340:   Summary: Code into subroutine, cleanings
                    341: 
1.269     brouard   342:   Revision 1.268  2017/05/18 20:09:32  brouard
                    343:   Summary: backprojection and confidence intervals of backprevalence
                    344: 
1.268     brouard   345:   Revision 1.267  2017/05/13 10:25:05  brouard
                    346:   Summary: temporary save for backprojection
                    347: 
1.267     brouard   348:   Revision 1.266  2017/05/13 07:26:12  brouard
                    349:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    350: 
1.266     brouard   351:   Revision 1.265  2017/04/26 16:22:11  brouard
                    352:   Summary: imach 0.99r13 Some bugs fixed
                    353: 
1.265     brouard   354:   Revision 1.264  2017/04/26 06:01:29  brouard
                    355:   Summary: Labels in graphs
                    356: 
1.264     brouard   357:   Revision 1.263  2017/04/24 15:23:15  brouard
                    358:   Summary: to save
                    359: 
1.263     brouard   360:   Revision 1.262  2017/04/18 16:48:12  brouard
                    361:   *** empty log message ***
                    362: 
1.262     brouard   363:   Revision 1.261  2017/04/05 10:14:09  brouard
                    364:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    365: 
1.261     brouard   366:   Revision 1.260  2017/04/04 17:46:59  brouard
                    367:   Summary: Gnuplot indexations fixed (humm)
                    368: 
1.260     brouard   369:   Revision 1.259  2017/04/04 13:01:16  brouard
                    370:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    371: 
1.259     brouard   372:   Revision 1.258  2017/04/03 10:17:47  brouard
                    373:   Summary: Version 0.99r12
                    374: 
                    375:   Some cleanings, conformed with updated documentation.
                    376: 
1.258     brouard   377:   Revision 1.257  2017/03/29 16:53:30  brouard
                    378:   Summary: Temp
                    379: 
1.257     brouard   380:   Revision 1.256  2017/03/27 05:50:23  brouard
                    381:   Summary: Temporary
                    382: 
1.256     brouard   383:   Revision 1.255  2017/03/08 16:02:28  brouard
                    384:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    385: 
1.255     brouard   386:   Revision 1.254  2017/03/08 07:13:00  brouard
                    387:   Summary: Fixing data parameter line
                    388: 
1.254     brouard   389:   Revision 1.253  2016/12/15 11:59:41  brouard
                    390:   Summary: 0.99 in progress
                    391: 
1.253     brouard   392:   Revision 1.252  2016/09/15 21:15:37  brouard
                    393:   *** empty log message ***
                    394: 
1.252     brouard   395:   Revision 1.251  2016/09/15 15:01:13  brouard
                    396:   Summary: not working
                    397: 
1.251     brouard   398:   Revision 1.250  2016/09/08 16:07:27  brouard
                    399:   Summary: continue
                    400: 
1.250     brouard   401:   Revision 1.249  2016/09/07 17:14:18  brouard
                    402:   Summary: Starting values from frequencies
                    403: 
1.249     brouard   404:   Revision 1.248  2016/09/07 14:10:18  brouard
                    405:   *** empty log message ***
                    406: 
1.248     brouard   407:   Revision 1.247  2016/09/02 11:11:21  brouard
                    408:   *** empty log message ***
                    409: 
1.247     brouard   410:   Revision 1.246  2016/09/02 08:49:22  brouard
                    411:   *** empty log message ***
                    412: 
1.246     brouard   413:   Revision 1.245  2016/09/02 07:25:01  brouard
                    414:   *** empty log message ***
                    415: 
1.245     brouard   416:   Revision 1.244  2016/09/02 07:17:34  brouard
                    417:   *** empty log message ***
                    418: 
1.244     brouard   419:   Revision 1.243  2016/09/02 06:45:35  brouard
                    420:   *** empty log message ***
                    421: 
1.243     brouard   422:   Revision 1.242  2016/08/30 15:01:20  brouard
                    423:   Summary: Fixing a lots
                    424: 
1.242     brouard   425:   Revision 1.241  2016/08/29 17:17:25  brouard
                    426:   Summary: gnuplot problem in Back projection to fix
                    427: 
1.241     brouard   428:   Revision 1.240  2016/08/29 07:53:18  brouard
                    429:   Summary: Better
                    430: 
1.240     brouard   431:   Revision 1.239  2016/08/26 15:51:03  brouard
                    432:   Summary: Improvement in Powell output in order to copy and paste
                    433: 
                    434:   Author:
                    435: 
1.239     brouard   436:   Revision 1.238  2016/08/26 14:23:35  brouard
                    437:   Summary: Starting tests of 0.99
                    438: 
1.238     brouard   439:   Revision 1.237  2016/08/26 09:20:19  brouard
                    440:   Summary: to valgrind
                    441: 
1.237     brouard   442:   Revision 1.236  2016/08/25 10:50:18  brouard
                    443:   *** empty log message ***
                    444: 
1.236     brouard   445:   Revision 1.235  2016/08/25 06:59:23  brouard
                    446:   *** empty log message ***
                    447: 
1.235     brouard   448:   Revision 1.234  2016/08/23 16:51:20  brouard
                    449:   *** empty log message ***
                    450: 
1.234     brouard   451:   Revision 1.233  2016/08/23 07:40:50  brouard
                    452:   Summary: not working
                    453: 
1.233     brouard   454:   Revision 1.232  2016/08/22 14:20:21  brouard
                    455:   Summary: not working
                    456: 
1.232     brouard   457:   Revision 1.231  2016/08/22 07:17:15  brouard
                    458:   Summary: not working
                    459: 
1.231     brouard   460:   Revision 1.230  2016/08/22 06:55:53  brouard
                    461:   Summary: Not working
                    462: 
1.230     brouard   463:   Revision 1.229  2016/07/23 09:45:53  brouard
                    464:   Summary: Completing for func too
                    465: 
1.229     brouard   466:   Revision 1.228  2016/07/22 17:45:30  brouard
                    467:   Summary: Fixing some arrays, still debugging
                    468: 
1.227     brouard   469:   Revision 1.226  2016/07/12 18:42:34  brouard
                    470:   Summary: temp
                    471: 
1.226     brouard   472:   Revision 1.225  2016/07/12 08:40:03  brouard
                    473:   Summary: saving but not running
                    474: 
1.225     brouard   475:   Revision 1.224  2016/07/01 13:16:01  brouard
                    476:   Summary: Fixes
                    477: 
1.224     brouard   478:   Revision 1.223  2016/02/19 09:23:35  brouard
                    479:   Summary: temporary
                    480: 
1.223     brouard   481:   Revision 1.222  2016/02/17 08:14:50  brouard
                    482:   Summary: Probably last 0.98 stable version 0.98r6
                    483: 
1.222     brouard   484:   Revision 1.221  2016/02/15 23:35:36  brouard
                    485:   Summary: minor bug
                    486: 
1.220     brouard   487:   Revision 1.219  2016/02/15 00:48:12  brouard
                    488:   *** empty log message ***
                    489: 
1.219     brouard   490:   Revision 1.218  2016/02/12 11:29:23  brouard
                    491:   Summary: 0.99 Back projections
                    492: 
1.218     brouard   493:   Revision 1.217  2015/12/23 17:18:31  brouard
                    494:   Summary: Experimental backcast
                    495: 
1.217     brouard   496:   Revision 1.216  2015/12/18 17:32:11  brouard
                    497:   Summary: 0.98r4 Warning and status=-2
                    498: 
                    499:   Version 0.98r4 is now:
                    500:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    501:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    502:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    503: 
1.216     brouard   504:   Revision 1.215  2015/12/16 08:52:24  brouard
                    505:   Summary: 0.98r4 working
                    506: 
1.215     brouard   507:   Revision 1.214  2015/12/16 06:57:54  brouard
                    508:   Summary: temporary not working
                    509: 
1.214     brouard   510:   Revision 1.213  2015/12/11 18:22:17  brouard
                    511:   Summary: 0.98r4
                    512: 
1.213     brouard   513:   Revision 1.212  2015/11/21 12:47:24  brouard
                    514:   Summary: minor typo
                    515: 
1.212     brouard   516:   Revision 1.211  2015/11/21 12:41:11  brouard
                    517:   Summary: 0.98r3 with some graph of projected cross-sectional
                    518: 
                    519:   Author: Nicolas Brouard
                    520: 
1.211     brouard   521:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   522:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   523:   Summary: Adding ftolpl parameter
                    524:   Author: N Brouard
                    525: 
                    526:   We had difficulties to get smoothed confidence intervals. It was due
                    527:   to the period prevalence which wasn't computed accurately. The inner
                    528:   parameter ftolpl is now an outer parameter of the .imach parameter
                    529:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    530:   computation are long.
                    531: 
1.209     brouard   532:   Revision 1.208  2015/11/17 14:31:57  brouard
                    533:   Summary: temporary
                    534: 
1.208     brouard   535:   Revision 1.207  2015/10/27 17:36:57  brouard
                    536:   *** empty log message ***
                    537: 
1.207     brouard   538:   Revision 1.206  2015/10/24 07:14:11  brouard
                    539:   *** empty log message ***
                    540: 
1.206     brouard   541:   Revision 1.205  2015/10/23 15:50:53  brouard
                    542:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    543: 
1.205     brouard   544:   Revision 1.204  2015/10/01 16:20:26  brouard
                    545:   Summary: Some new graphs of contribution to likelihood
                    546: 
1.204     brouard   547:   Revision 1.203  2015/09/30 17:45:14  brouard
                    548:   Summary: looking at better estimation of the hessian
                    549: 
                    550:   Also a better criteria for convergence to the period prevalence And
                    551:   therefore adding the number of years needed to converge. (The
                    552:   prevalence in any alive state shold sum to one
                    553: 
1.203     brouard   554:   Revision 1.202  2015/09/22 19:45:16  brouard
                    555:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    556: 
1.202     brouard   557:   Revision 1.201  2015/09/15 17:34:58  brouard
                    558:   Summary: 0.98r0
                    559: 
                    560:   - Some new graphs like suvival functions
                    561:   - Some bugs fixed like model=1+age+V2.
                    562: 
1.201     brouard   563:   Revision 1.200  2015/09/09 16:53:55  brouard
                    564:   Summary: Big bug thanks to Flavia
                    565: 
                    566:   Even model=1+age+V2. did not work anymore
                    567: 
1.200     brouard   568:   Revision 1.199  2015/09/07 14:09:23  brouard
                    569:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    570: 
1.199     brouard   571:   Revision 1.198  2015/09/03 07:14:39  brouard
                    572:   Summary: 0.98q5 Flavia
                    573: 
1.198     brouard   574:   Revision 1.197  2015/09/01 18:24:39  brouard
                    575:   *** empty log message ***
                    576: 
1.197     brouard   577:   Revision 1.196  2015/08/18 23:17:52  brouard
                    578:   Summary: 0.98q5
                    579: 
1.196     brouard   580:   Revision 1.195  2015/08/18 16:28:39  brouard
                    581:   Summary: Adding a hack for testing purpose
                    582: 
                    583:   After reading the title, ftol and model lines, if the comment line has
                    584:   a q, starting with #q, the answer at the end of the run is quit. It
                    585:   permits to run test files in batch with ctest. The former workaround was
                    586:   $ echo q | imach foo.imach
                    587: 
1.195     brouard   588:   Revision 1.194  2015/08/18 13:32:00  brouard
                    589:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    590: 
1.194     brouard   591:   Revision 1.193  2015/08/04 07:17:42  brouard
                    592:   Summary: 0.98q4
                    593: 
1.193     brouard   594:   Revision 1.192  2015/07/16 16:49:02  brouard
                    595:   Summary: Fixing some outputs
                    596: 
1.192     brouard   597:   Revision 1.191  2015/07/14 10:00:33  brouard
                    598:   Summary: Some fixes
                    599: 
1.191     brouard   600:   Revision 1.190  2015/05/05 08:51:13  brouard
                    601:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    602: 
                    603:   Fix 1+age+.
                    604: 
1.190     brouard   605:   Revision 1.189  2015/04/30 14:45:16  brouard
                    606:   Summary: 0.98q2
                    607: 
1.189     brouard   608:   Revision 1.188  2015/04/30 08:27:53  brouard
                    609:   *** empty log message ***
                    610: 
1.188     brouard   611:   Revision 1.187  2015/04/29 09:11:15  brouard
                    612:   *** empty log message ***
                    613: 
1.187     brouard   614:   Revision 1.186  2015/04/23 12:01:52  brouard
                    615:   Summary: V1*age is working now, version 0.98q1
                    616: 
                    617:   Some codes had been disabled in order to simplify and Vn*age was
                    618:   working in the optimization phase, ie, giving correct MLE parameters,
                    619:   but, as usual, outputs were not correct and program core dumped.
                    620: 
1.186     brouard   621:   Revision 1.185  2015/03/11 13:26:42  brouard
                    622:   Summary: Inclusion of compile and links command line for Intel Compiler
                    623: 
1.185     brouard   624:   Revision 1.184  2015/03/11 11:52:39  brouard
                    625:   Summary: Back from Windows 8. Intel Compiler
                    626: 
1.184     brouard   627:   Revision 1.183  2015/03/10 20:34:32  brouard
                    628:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    629: 
                    630:   We use directest instead of original Powell test; probably no
                    631:   incidence on the results, but better justifications;
                    632:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    633:   wrong results.
                    634: 
1.183     brouard   635:   Revision 1.182  2015/02/12 08:19:57  brouard
                    636:   Summary: Trying to keep directest which seems simpler and more general
                    637:   Author: Nicolas Brouard
                    638: 
1.182     brouard   639:   Revision 1.181  2015/02/11 23:22:24  brouard
                    640:   Summary: Comments on Powell added
                    641: 
                    642:   Author:
                    643: 
1.181     brouard   644:   Revision 1.180  2015/02/11 17:33:45  brouard
                    645:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    646: 
1.180     brouard   647:   Revision 1.179  2015/01/04 09:57:06  brouard
                    648:   Summary: back to OS/X
                    649: 
1.179     brouard   650:   Revision 1.178  2015/01/04 09:35:48  brouard
                    651:   *** empty log message ***
                    652: 
1.178     brouard   653:   Revision 1.177  2015/01/03 18:40:56  brouard
                    654:   Summary: Still testing ilc32 on OSX
                    655: 
1.177     brouard   656:   Revision 1.176  2015/01/03 16:45:04  brouard
                    657:   *** empty log message ***
                    658: 
1.176     brouard   659:   Revision 1.175  2015/01/03 16:33:42  brouard
                    660:   *** empty log message ***
                    661: 
1.175     brouard   662:   Revision 1.174  2015/01/03 16:15:49  brouard
                    663:   Summary: Still in cross-compilation
                    664: 
1.174     brouard   665:   Revision 1.173  2015/01/03 12:06:26  brouard
                    666:   Summary: trying to detect cross-compilation
                    667: 
1.173     brouard   668:   Revision 1.172  2014/12/27 12:07:47  brouard
                    669:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    670: 
1.172     brouard   671:   Revision 1.171  2014/12/23 13:26:59  brouard
                    672:   Summary: Back from Visual C
                    673: 
                    674:   Still problem with utsname.h on Windows
                    675: 
1.171     brouard   676:   Revision 1.170  2014/12/23 11:17:12  brouard
                    677:   Summary: Cleaning some \%% back to %%
                    678: 
                    679:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    680: 
1.170     brouard   681:   Revision 1.169  2014/12/22 23:08:31  brouard
                    682:   Summary: 0.98p
                    683: 
                    684:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    685: 
1.169     brouard   686:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   687:   Summary: update
1.169     brouard   688: 
1.168     brouard   689:   Revision 1.167  2014/12/22 13:50:56  brouard
                    690:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    691: 
                    692:   Testing on Linux 64
                    693: 
1.167     brouard   694:   Revision 1.166  2014/12/22 11:40:47  brouard
                    695:   *** empty log message ***
                    696: 
1.166     brouard   697:   Revision 1.165  2014/12/16 11:20:36  brouard
                    698:   Summary: After compiling on Visual C
                    699: 
                    700:   * imach.c (Module): Merging 1.61 to 1.162
                    701: 
1.165     brouard   702:   Revision 1.164  2014/12/16 10:52:11  brouard
                    703:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    704: 
                    705:   * imach.c (Module): Merging 1.61 to 1.162
                    706: 
1.164     brouard   707:   Revision 1.163  2014/12/16 10:30:11  brouard
                    708:   * imach.c (Module): Merging 1.61 to 1.162
                    709: 
1.163     brouard   710:   Revision 1.162  2014/09/25 11:43:39  brouard
                    711:   Summary: temporary backup 0.99!
                    712: 
1.162     brouard   713:   Revision 1.1  2014/09/16 11:06:58  brouard
                    714:   Summary: With some code (wrong) for nlopt
                    715: 
                    716:   Author:
                    717: 
                    718:   Revision 1.161  2014/09/15 20:41:41  brouard
                    719:   Summary: Problem with macro SQR on Intel compiler
                    720: 
1.161     brouard   721:   Revision 1.160  2014/09/02 09:24:05  brouard
                    722:   *** empty log message ***
                    723: 
1.160     brouard   724:   Revision 1.159  2014/09/01 10:34:10  brouard
                    725:   Summary: WIN32
                    726:   Author: Brouard
                    727: 
1.159     brouard   728:   Revision 1.158  2014/08/27 17:11:51  brouard
                    729:   *** empty log message ***
                    730: 
1.158     brouard   731:   Revision 1.157  2014/08/27 16:26:55  brouard
                    732:   Summary: Preparing windows Visual studio version
                    733:   Author: Brouard
                    734: 
                    735:   In order to compile on Visual studio, time.h is now correct and time_t
                    736:   and tm struct should be used. difftime should be used but sometimes I
                    737:   just make the differences in raw time format (time(&now).
                    738:   Trying to suppress #ifdef LINUX
                    739:   Add xdg-open for __linux in order to open default browser.
                    740: 
1.157     brouard   741:   Revision 1.156  2014/08/25 20:10:10  brouard
                    742:   *** empty log message ***
                    743: 
1.156     brouard   744:   Revision 1.155  2014/08/25 18:32:34  brouard
                    745:   Summary: New compile, minor changes
                    746:   Author: Brouard
                    747: 
1.155     brouard   748:   Revision 1.154  2014/06/20 17:32:08  brouard
                    749:   Summary: Outputs now all graphs of convergence to period prevalence
                    750: 
1.154     brouard   751:   Revision 1.153  2014/06/20 16:45:46  brouard
                    752:   Summary: If 3 live state, convergence to period prevalence on same graph
                    753:   Author: Brouard
                    754: 
1.153     brouard   755:   Revision 1.152  2014/06/18 17:54:09  brouard
                    756:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    757: 
1.152     brouard   758:   Revision 1.151  2014/06/18 16:43:30  brouard
                    759:   *** empty log message ***
                    760: 
1.151     brouard   761:   Revision 1.150  2014/06/18 16:42:35  brouard
                    762:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    763:   Author: brouard
                    764: 
1.150     brouard   765:   Revision 1.149  2014/06/18 15:51:14  brouard
                    766:   Summary: Some fixes in parameter files errors
                    767:   Author: Nicolas Brouard
                    768: 
1.149     brouard   769:   Revision 1.148  2014/06/17 17:38:48  brouard
                    770:   Summary: Nothing new
                    771:   Author: Brouard
                    772: 
                    773:   Just a new packaging for OS/X version 0.98nS
                    774: 
1.148     brouard   775:   Revision 1.147  2014/06/16 10:33:11  brouard
                    776:   *** empty log message ***
                    777: 
1.147     brouard   778:   Revision 1.146  2014/06/16 10:20:28  brouard
                    779:   Summary: Merge
                    780:   Author: Brouard
                    781: 
                    782:   Merge, before building revised version.
                    783: 
1.146     brouard   784:   Revision 1.145  2014/06/10 21:23:15  brouard
                    785:   Summary: Debugging with valgrind
                    786:   Author: Nicolas Brouard
                    787: 
                    788:   Lot of changes in order to output the results with some covariates
                    789:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    790:   improve the code.
                    791:   No more memory valgrind error but a lot has to be done in order to
                    792:   continue the work of splitting the code into subroutines.
                    793:   Also, decodemodel has been improved. Tricode is still not
                    794:   optimal. nbcode should be improved. Documentation has been added in
                    795:   the source code.
                    796: 
1.144     brouard   797:   Revision 1.143  2014/01/26 09:45:38  brouard
                    798:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    799: 
                    800:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    801:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    802: 
1.143     brouard   803:   Revision 1.142  2014/01/26 03:57:36  brouard
                    804:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    805: 
                    806:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    807: 
1.142     brouard   808:   Revision 1.141  2014/01/26 02:42:01  brouard
                    809:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    810: 
1.141     brouard   811:   Revision 1.140  2011/09/02 10:37:54  brouard
                    812:   Summary: times.h is ok with mingw32 now.
                    813: 
1.140     brouard   814:   Revision 1.139  2010/06/14 07:50:17  brouard
                    815:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    816:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    817: 
1.139     brouard   818:   Revision 1.138  2010/04/30 18:19:40  brouard
                    819:   *** empty log message ***
                    820: 
1.138     brouard   821:   Revision 1.137  2010/04/29 18:11:38  brouard
                    822:   (Module): Checking covariates for more complex models
                    823:   than V1+V2. A lot of change to be done. Unstable.
                    824: 
1.137     brouard   825:   Revision 1.136  2010/04/26 20:30:53  brouard
                    826:   (Module): merging some libgsl code. Fixing computation
                    827:   of likelione (using inter/intrapolation if mle = 0) in order to
                    828:   get same likelihood as if mle=1.
                    829:   Some cleaning of code and comments added.
                    830: 
1.136     brouard   831:   Revision 1.135  2009/10/29 15:33:14  brouard
                    832:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    833: 
1.135     brouard   834:   Revision 1.134  2009/10/29 13:18:53  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.134     brouard   837:   Revision 1.133  2009/07/06 10:21:25  brouard
                    838:   just nforces
                    839: 
1.133     brouard   840:   Revision 1.132  2009/07/06 08:22:05  brouard
                    841:   Many tings
                    842: 
1.132     brouard   843:   Revision 1.131  2009/06/20 16:22:47  brouard
                    844:   Some dimensions resccaled
                    845: 
1.131     brouard   846:   Revision 1.130  2009/05/26 06:44:34  brouard
                    847:   (Module): Max Covariate is now set to 20 instead of 8. A
                    848:   lot of cleaning with variables initialized to 0. Trying to make
                    849:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    850: 
1.130     brouard   851:   Revision 1.129  2007/08/31 13:49:27  lievre
                    852:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    853: 
1.129     lievre    854:   Revision 1.128  2006/06/30 13:02:05  brouard
                    855:   (Module): Clarifications on computing e.j
                    856: 
1.128     brouard   857:   Revision 1.127  2006/04/28 18:11:50  brouard
                    858:   (Module): Yes the sum of survivors was wrong since
                    859:   imach-114 because nhstepm was no more computed in the age
                    860:   loop. Now we define nhstepma in the age loop.
                    861:   (Module): In order to speed up (in case of numerous covariates) we
                    862:   compute health expectancies (without variances) in a first step
                    863:   and then all the health expectancies with variances or standard
                    864:   deviation (needs data from the Hessian matrices) which slows the
                    865:   computation.
                    866:   In the future we should be able to stop the program is only health
                    867:   expectancies and graph are needed without standard deviations.
                    868: 
1.127     brouard   869:   Revision 1.126  2006/04/28 17:23:28  brouard
                    870:   (Module): Yes the sum of survivors was wrong since
                    871:   imach-114 because nhstepm was no more computed in the age
                    872:   loop. Now we define nhstepma in the age loop.
                    873:   Version 0.98h
                    874: 
1.126     brouard   875:   Revision 1.125  2006/04/04 15:20:31  lievre
                    876:   Errors in calculation of health expectancies. Age was not initialized.
                    877:   Forecasting file added.
                    878: 
                    879:   Revision 1.124  2006/03/22 17:13:53  lievre
                    880:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    881:   The log-likelihood is printed in the log file
                    882: 
                    883:   Revision 1.123  2006/03/20 10:52:43  brouard
                    884:   * imach.c (Module): <title> changed, corresponds to .htm file
                    885:   name. <head> headers where missing.
                    886: 
                    887:   * imach.c (Module): Weights can have a decimal point as for
                    888:   English (a comma might work with a correct LC_NUMERIC environment,
                    889:   otherwise the weight is truncated).
                    890:   Modification of warning when the covariates values are not 0 or
                    891:   1.
                    892:   Version 0.98g
                    893: 
                    894:   Revision 1.122  2006/03/20 09:45:41  brouard
                    895:   (Module): Weights can have a decimal point as for
                    896:   English (a comma might work with a correct LC_NUMERIC environment,
                    897:   otherwise the weight is truncated).
                    898:   Modification of warning when the covariates values are not 0 or
                    899:   1.
                    900:   Version 0.98g
                    901: 
                    902:   Revision 1.121  2006/03/16 17:45:01  lievre
                    903:   * imach.c (Module): Comments concerning covariates added
                    904: 
                    905:   * imach.c (Module): refinements in the computation of lli if
                    906:   status=-2 in order to have more reliable computation if stepm is
                    907:   not 1 month. Version 0.98f
                    908: 
                    909:   Revision 1.120  2006/03/16 15:10:38  lievre
                    910:   (Module): refinements in the computation of lli if
                    911:   status=-2 in order to have more reliable computation if stepm is
                    912:   not 1 month. Version 0.98f
                    913: 
                    914:   Revision 1.119  2006/03/15 17:42:26  brouard
                    915:   (Module): Bug if status = -2, the loglikelihood was
                    916:   computed as likelihood omitting the logarithm. Version O.98e
                    917: 
                    918:   Revision 1.118  2006/03/14 18:20:07  brouard
                    919:   (Module): varevsij Comments added explaining the second
                    920:   table of variances if popbased=1 .
                    921:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    922:   (Module): Function pstamp added
                    923:   (Module): Version 0.98d
                    924: 
                    925:   Revision 1.117  2006/03/14 17:16:22  brouard
                    926:   (Module): varevsij Comments added explaining the second
                    927:   table of variances if popbased=1 .
                    928:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    929:   (Module): Function pstamp added
                    930:   (Module): Version 0.98d
                    931: 
                    932:   Revision 1.116  2006/03/06 10:29:27  brouard
                    933:   (Module): Variance-covariance wrong links and
                    934:   varian-covariance of ej. is needed (Saito).
                    935: 
                    936:   Revision 1.115  2006/02/27 12:17:45  brouard
                    937:   (Module): One freematrix added in mlikeli! 0.98c
                    938: 
                    939:   Revision 1.114  2006/02/26 12:57:58  brouard
                    940:   (Module): Some improvements in processing parameter
                    941:   filename with strsep.
                    942: 
                    943:   Revision 1.113  2006/02/24 14:20:24  brouard
                    944:   (Module): Memory leaks checks with valgrind and:
                    945:   datafile was not closed, some imatrix were not freed and on matrix
                    946:   allocation too.
                    947: 
                    948:   Revision 1.112  2006/01/30 09:55:26  brouard
                    949:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    950: 
                    951:   Revision 1.111  2006/01/25 20:38:18  brouard
                    952:   (Module): Lots of cleaning and bugs added (Gompertz)
                    953:   (Module): Comments can be added in data file. Missing date values
                    954:   can be a simple dot '.'.
                    955: 
                    956:   Revision 1.110  2006/01/25 00:51:50  brouard
                    957:   (Module): Lots of cleaning and bugs added (Gompertz)
                    958: 
                    959:   Revision 1.109  2006/01/24 19:37:15  brouard
                    960:   (Module): Comments (lines starting with a #) are allowed in data.
                    961: 
                    962:   Revision 1.108  2006/01/19 18:05:42  lievre
                    963:   Gnuplot problem appeared...
                    964:   To be fixed
                    965: 
                    966:   Revision 1.107  2006/01/19 16:20:37  brouard
                    967:   Test existence of gnuplot in imach path
                    968: 
                    969:   Revision 1.106  2006/01/19 13:24:36  brouard
                    970:   Some cleaning and links added in html output
                    971: 
                    972:   Revision 1.105  2006/01/05 20:23:19  lievre
                    973:   *** empty log message ***
                    974: 
                    975:   Revision 1.104  2005/09/30 16:11:43  lievre
                    976:   (Module): sump fixed, loop imx fixed, and simplifications.
                    977:   (Module): If the status is missing at the last wave but we know
                    978:   that the person is alive, then we can code his/her status as -2
                    979:   (instead of missing=-1 in earlier versions) and his/her
                    980:   contributions to the likelihood is 1 - Prob of dying from last
                    981:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    982:   the healthy state at last known wave). Version is 0.98
                    983: 
                    984:   Revision 1.103  2005/09/30 15:54:49  lievre
                    985:   (Module): sump fixed, loop imx fixed, and simplifications.
                    986: 
                    987:   Revision 1.102  2004/09/15 17:31:30  brouard
                    988:   Add the possibility to read data file including tab characters.
                    989: 
                    990:   Revision 1.101  2004/09/15 10:38:38  brouard
                    991:   Fix on curr_time
                    992: 
                    993:   Revision 1.100  2004/07/12 18:29:06  brouard
                    994:   Add version for Mac OS X. Just define UNIX in Makefile
                    995: 
                    996:   Revision 1.99  2004/06/05 08:57:40  brouard
                    997:   *** empty log message ***
                    998: 
                    999:   Revision 1.98  2004/05/16 15:05:56  brouard
                   1000:   New version 0.97 . First attempt to estimate force of mortality
                   1001:   directly from the data i.e. without the need of knowing the health
                   1002:   state at each age, but using a Gompertz model: log u =a + b*age .
                   1003:   This is the basic analysis of mortality and should be done before any
                   1004:   other analysis, in order to test if the mortality estimated from the
                   1005:   cross-longitudinal survey is different from the mortality estimated
                   1006:   from other sources like vital statistic data.
                   1007: 
                   1008:   The same imach parameter file can be used but the option for mle should be -3.
                   1009: 
1.324     brouard  1010:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard  1011:   former routines in order to include the new code within the former code.
                   1012: 
                   1013:   The output is very simple: only an estimate of the intercept and of
                   1014:   the slope with 95% confident intervals.
                   1015: 
                   1016:   Current limitations:
                   1017:   A) Even if you enter covariates, i.e. with the
                   1018:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                   1019:   B) There is no computation of Life Expectancy nor Life Table.
                   1020: 
                   1021:   Revision 1.97  2004/02/20 13:25:42  lievre
                   1022:   Version 0.96d. Population forecasting command line is (temporarily)
                   1023:   suppressed.
                   1024: 
                   1025:   Revision 1.96  2003/07/15 15:38:55  brouard
                   1026:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                   1027:   rewritten within the same printf. Workaround: many printfs.
                   1028: 
                   1029:   Revision 1.95  2003/07/08 07:54:34  brouard
                   1030:   * imach.c (Repository):
                   1031:   (Repository): Using imachwizard code to output a more meaningful covariance
                   1032:   matrix (cov(a12,c31) instead of numbers.
                   1033: 
                   1034:   Revision 1.94  2003/06/27 13:00:02  brouard
                   1035:   Just cleaning
                   1036: 
                   1037:   Revision 1.93  2003/06/25 16:33:55  brouard
                   1038:   (Module): On windows (cygwin) function asctime_r doesn't
                   1039:   exist so I changed back to asctime which exists.
                   1040:   (Module): Version 0.96b
                   1041: 
                   1042:   Revision 1.92  2003/06/25 16:30:45  brouard
                   1043:   (Module): On windows (cygwin) function asctime_r doesn't
                   1044:   exist so I changed back to asctime which exists.
                   1045: 
                   1046:   Revision 1.91  2003/06/25 15:30:29  brouard
                   1047:   * imach.c (Repository): Duplicated warning errors corrected.
                   1048:   (Repository): Elapsed time after each iteration is now output. It
                   1049:   helps to forecast when convergence will be reached. Elapsed time
                   1050:   is stamped in powell.  We created a new html file for the graphs
                   1051:   concerning matrix of covariance. It has extension -cov.htm.
                   1052: 
                   1053:   Revision 1.90  2003/06/24 12:34:15  brouard
                   1054:   (Module): Some bugs corrected for windows. Also, when
                   1055:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1056:   of the covariance matrix to be input.
                   1057: 
                   1058:   Revision 1.89  2003/06/24 12:30:52  brouard
                   1059:   (Module): Some bugs corrected for windows. Also, when
                   1060:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1061:   of the covariance matrix to be input.
                   1062: 
                   1063:   Revision 1.88  2003/06/23 17:54:56  brouard
                   1064:   * 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.
                   1065: 
                   1066:   Revision 1.87  2003/06/18 12:26:01  brouard
                   1067:   Version 0.96
                   1068: 
                   1069:   Revision 1.86  2003/06/17 20:04:08  brouard
                   1070:   (Module): Change position of html and gnuplot routines and added
                   1071:   routine fileappend.
                   1072: 
                   1073:   Revision 1.85  2003/06/17 13:12:43  brouard
                   1074:   * imach.c (Repository): Check when date of death was earlier that
                   1075:   current date of interview. It may happen when the death was just
                   1076:   prior to the death. In this case, dh was negative and likelihood
                   1077:   was wrong (infinity). We still send an "Error" but patch by
                   1078:   assuming that the date of death was just one stepm after the
                   1079:   interview.
                   1080:   (Repository): Because some people have very long ID (first column)
                   1081:   we changed int to long in num[] and we added a new lvector for
                   1082:   memory allocation. But we also truncated to 8 characters (left
                   1083:   truncation)
                   1084:   (Repository): No more line truncation errors.
                   1085: 
                   1086:   Revision 1.84  2003/06/13 21:44:43  brouard
                   1087:   * imach.c (Repository): Replace "freqsummary" at a correct
                   1088:   place. It differs from routine "prevalence" which may be called
                   1089:   many times. Probs is memory consuming and must be used with
                   1090:   parcimony.
                   1091:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                   1092: 
                   1093:   Revision 1.83  2003/06/10 13:39:11  lievre
                   1094:   *** empty log message ***
                   1095: 
                   1096:   Revision 1.82  2003/06/05 15:57:20  brouard
                   1097:   Add log in  imach.c and  fullversion number is now printed.
                   1098: 
                   1099: */
                   1100: /*
                   1101:    Interpolated Markov Chain
                   1102: 
                   1103:   Short summary of the programme:
                   1104:   
1.227     brouard  1105:   This program computes Healthy Life Expectancies or State-specific
                   1106:   (if states aren't health statuses) Expectancies from
                   1107:   cross-longitudinal data. Cross-longitudinal data consist in: 
                   1108: 
                   1109:   -1- a first survey ("cross") where individuals from different ages
                   1110:   are interviewed on their health status or degree of disability (in
                   1111:   the case of a health survey which is our main interest)
                   1112: 
                   1113:   -2- at least a second wave of interviews ("longitudinal") which
                   1114:   measure each change (if any) in individual health status.  Health
                   1115:   expectancies are computed from the time spent in each health state
                   1116:   according to a model. More health states you consider, more time is
                   1117:   necessary to reach the Maximum Likelihood of the parameters involved
                   1118:   in the model.  The simplest model is the multinomial logistic model
                   1119:   where pij is the probability to be observed in state j at the second
                   1120:   wave conditional to be observed in state i at the first
                   1121:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                   1122:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                   1123:   have a more complex model than "constant and age", you should modify
                   1124:   the program where the markup *Covariates have to be included here
                   1125:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard  1126:   convergence.
                   1127: 
                   1128:   The advantage of this computer programme, compared to a simple
                   1129:   multinomial logistic model, is clear when the delay between waves is not
                   1130:   identical for each individual. Also, if a individual missed an
                   1131:   intermediate interview, the information is lost, but taken into
                   1132:   account using an interpolation or extrapolation.  
                   1133: 
                   1134:   hPijx is the probability to be observed in state i at age x+h
                   1135:   conditional to the observed state i at age x. The delay 'h' can be
                   1136:   split into an exact number (nh*stepm) of unobserved intermediate
                   1137:   states. This elementary transition (by month, quarter,
                   1138:   semester or year) is modelled as a multinomial logistic.  The hPx
                   1139:   matrix is simply the matrix product of nh*stepm elementary matrices
                   1140:   and the contribution of each individual to the likelihood is simply
                   1141:   hPijx.
                   1142: 
                   1143:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard  1144:   of the life expectancies. It also computes the period (stable) prevalence.
                   1145: 
                   1146: Back prevalence and projections:
1.227     brouard  1147: 
                   1148:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                   1149:    double agemaxpar, double ftolpl, int *ncvyearp, double
                   1150:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                   1151:    mobilavproj)
                   1152: 
                   1153:     Computes the back prevalence limit for any combination of
                   1154:     covariate values k at any age between ageminpar and agemaxpar and
                   1155:     returns it in **bprlim. In the loops,
                   1156: 
                   1157:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                   1158:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                   1159: 
                   1160:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard  1161:    Computes for any combination of covariates k and any age between bage and fage 
                   1162:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1163:                        oldm=oldms;savm=savms;
1.227     brouard  1164: 
1.267     brouard  1165:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard  1166:      Computes the transition matrix starting at age 'age' over
                   1167:      'nhstepm*hstepm*stepm' months (i.e. until
                   1168:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard  1169:      nhstepm*hstepm matrices. 
                   1170: 
                   1171:      Returns p3mat[i][j][h] after calling
                   1172:      p3mat[i][j][h]=matprod2(newm,
                   1173:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                   1174:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                   1175:      oldm);
1.226     brouard  1176: 
                   1177: Important routines
                   1178: 
                   1179: - func (or funcone), computes logit (pij) distinguishing
                   1180:   o fixed variables (single or product dummies or quantitative);
                   1181:   o varying variables by:
                   1182:    (1) wave (single, product dummies, quantitative), 
                   1183:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                   1184:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                   1185:        % varying dummy (not done) or quantitative (not done);
                   1186: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                   1187:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                   1188: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
1.325     brouard  1189:   o There are 2**cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
1.226     brouard  1190:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard  1191: 
1.226     brouard  1192: 
                   1193:   
1.324     brouard  1194:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                   1195:            Institut national d'études démographiques, Paris.
1.126     brouard  1196:   This software have been partly granted by Euro-REVES, a concerted action
                   1197:   from the European Union.
                   1198:   It is copyrighted identically to a GNU software product, ie programme and
                   1199:   software can be distributed freely for non commercial use. Latest version
                   1200:   can be accessed at http://euroreves.ined.fr/imach .
                   1201: 
                   1202:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                   1203:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                   1204:   
                   1205:   **********************************************************************/
                   1206: /*
                   1207:   main
                   1208:   read parameterfile
                   1209:   read datafile
                   1210:   concatwav
                   1211:   freqsummary
                   1212:   if (mle >= 1)
                   1213:     mlikeli
                   1214:   print results files
                   1215:   if mle==1 
                   1216:      computes hessian
                   1217:   read end of parameter file: agemin, agemax, bage, fage, estepm
                   1218:       begin-prev-date,...
                   1219:   open gnuplot file
                   1220:   open html file
1.145     brouard  1221:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1222:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1223:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1224:     freexexit2 possible for memory heap.
                   1225: 
                   1226:   h Pij x                         | pij_nom  ficrestpij
                   1227:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1228:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1229:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1230: 
                   1231:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1232:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1233:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1234:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1235:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1236: 
1.126     brouard  1237:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1238:   health expectancies
                   1239:   Variance-covariance of DFLE
                   1240:   prevalence()
                   1241:    movingaverage()
                   1242:   varevsij() 
                   1243:   if popbased==1 varevsij(,popbased)
                   1244:   total life expectancies
                   1245:   Variance of period (stable) prevalence
                   1246:  end
                   1247: */
                   1248: 
1.187     brouard  1249: /* #define DEBUG */
                   1250: /* #define DEBUGBRENT */
1.203     brouard  1251: /* #define DEBUGLINMIN */
                   1252: /* #define DEBUGHESS */
                   1253: #define DEBUGHESSIJ
1.224     brouard  1254: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1255: #define POWELL /* Instead of NLOPT */
1.224     brouard  1256: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1257: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1258: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.319     brouard  1259: /* #define FLATSUP  *//* Suppresses directions where likelihood is flat */
1.126     brouard  1260: 
                   1261: #include <math.h>
                   1262: #include <stdio.h>
                   1263: #include <stdlib.h>
                   1264: #include <string.h>
1.226     brouard  1265: #include <ctype.h>
1.159     brouard  1266: 
                   1267: #ifdef _WIN32
                   1268: #include <io.h>
1.172     brouard  1269: #include <windows.h>
                   1270: #include <tchar.h>
1.159     brouard  1271: #else
1.126     brouard  1272: #include <unistd.h>
1.159     brouard  1273: #endif
1.126     brouard  1274: 
                   1275: #include <limits.h>
                   1276: #include <sys/types.h>
1.171     brouard  1277: 
                   1278: #if defined(__GNUC__)
                   1279: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1280: #endif
                   1281: 
1.126     brouard  1282: #include <sys/stat.h>
                   1283: #include <errno.h>
1.159     brouard  1284: /* extern int errno; */
1.126     brouard  1285: 
1.157     brouard  1286: /* #ifdef LINUX */
                   1287: /* #include <time.h> */
                   1288: /* #include "timeval.h" */
                   1289: /* #else */
                   1290: /* #include <sys/time.h> */
                   1291: /* #endif */
                   1292: 
1.126     brouard  1293: #include <time.h>
                   1294: 
1.136     brouard  1295: #ifdef GSL
                   1296: #include <gsl/gsl_errno.h>
                   1297: #include <gsl/gsl_multimin.h>
                   1298: #endif
                   1299: 
1.167     brouard  1300: 
1.162     brouard  1301: #ifdef NLOPT
                   1302: #include <nlopt.h>
                   1303: typedef struct {
                   1304:   double (* function)(double [] );
                   1305: } myfunc_data ;
                   1306: #endif
                   1307: 
1.126     brouard  1308: /* #include <libintl.h> */
                   1309: /* #define _(String) gettext (String) */
                   1310: 
1.251     brouard  1311: #define MAXLINE 2048 /* Was 256 and 1024. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1312: 
                   1313: #define GNUPLOTPROGRAM "gnuplot"
1.343     brouard  1314: #define GNUPLOTVERSION 5.1
                   1315: double gnuplotversion=GNUPLOTVERSION;
1.126     brouard  1316: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
1.329     brouard  1317: #define FILENAMELENGTH 256
1.126     brouard  1318: 
                   1319: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1320: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1321: 
1.144     brouard  1322: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                   1323: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1324: 
                   1325: #define NINTERVMAX 8
1.144     brouard  1326: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1327: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.325     brouard  1328: #define NCOVMAX 30  /**< Maximum number of covariates used in the model, including generated covariates V1*V2 or V1*age */
1.197     brouard  1329: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1330: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1331: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1332: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1333: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1334: /* #define AGESUP 130 */
1.288     brouard  1335: /* #define AGESUP 150 */
                   1336: #define AGESUP 200
1.268     brouard  1337: #define AGEINF 0
1.218     brouard  1338: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1339: #define AGEBASE 40
1.194     brouard  1340: #define AGEOVERFLOW 1.e20
1.164     brouard  1341: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1342: #ifdef _WIN32
                   1343: #define DIRSEPARATOR '\\'
                   1344: #define CHARSEPARATOR "\\"
                   1345: #define ODIRSEPARATOR '/'
                   1346: #else
1.126     brouard  1347: #define DIRSEPARATOR '/'
                   1348: #define CHARSEPARATOR "/"
                   1349: #define ODIRSEPARATOR '\\'
                   1350: #endif
                   1351: 
1.346   ! brouard  1352: /* $Id: imach.c,v 1.345 2022/09/16 13:40:11 brouard Exp $ */
1.126     brouard  1353: /* $State: Exp $ */
1.196     brouard  1354: #include "version.h"
                   1355: char version[]=__IMACH_VERSION__;
1.337     brouard  1356: 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.346   ! brouard  1357: char fullversion[]="$Revision: 1.345 $ $Date: 2022/09/16 13:40:11 $"; 
1.126     brouard  1358: char strstart[80];
                   1359: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1360: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.342     brouard  1361: int debugILK=0; /* debugILK is set by a #d in a comment line */
1.187     brouard  1362: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.330     brouard  1363: /* Number of covariates model (1)=V2+V1+ V3*age+V2*V4 */
                   1364: /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
1.335     brouard  1365: 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  1366: 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  1367: int cptcovs=0; /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   1368: int cptcovsnq=0; /**< cptcovsnq number of SIMPLE covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1369: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                   1370: int cptcovprodnoage=0; /**< Number of covariate products without age */   
1.335     brouard  1371: 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  1372: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1373: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.339     brouard  1374: int ncovvt=0; /* Total number of effective (wave) varying covariates (dummy or quantitative or products [without age]) in the model */
1.232     brouard  1375: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
1.234     brouard  1376: int nsd=0; /**< Total number of single dummy variables (output) */
                   1377: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1378: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1379: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1380: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1381: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1382: int cptcov=0; /* Working variable */
1.334     brouard  1383: int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs+1 declared globally ;*/
1.290     brouard  1384: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1385: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.302     brouard  1386: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
1.126     brouard  1387: int nlstate=2; /* Number of live states */
                   1388: int ndeath=1; /* Number of dead states */
1.130     brouard  1389: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.339     brouard  1390: int nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable*/
                   1391: int ncovcolt=0; /* ncovcolt=ncovcol+nqv+ntv+nqtv; total of covariates in the data, not in the model equation*/ 
1.126     brouard  1392: int popbased=0;
                   1393: 
                   1394: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1395: int maxwav=0; /* Maxim number of waves */
                   1396: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1397: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1398: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard  1399:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1400: int mle=1, weightopt=0;
1.126     brouard  1401: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1402: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1403: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1404:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1405: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1406: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1407: 
1.130     brouard  1408: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1409: double **matprod2(); /* test */
1.126     brouard  1410: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1411: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1412: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1413: 
1.136     brouard  1414: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1415: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1416: FILE *ficlog, *ficrespow;
1.130     brouard  1417: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1418: double fretone; /* Only one call to likelihood */
1.130     brouard  1419: long ipmx=0; /* Number of contributions */
1.126     brouard  1420: double sw; /* Sum of weights */
                   1421: char filerespow[FILENAMELENGTH];
                   1422: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1423: FILE *ficresilk;
                   1424: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1425: FILE *ficresprobmorprev;
                   1426: FILE *fichtm, *fichtmcov; /* Html File */
                   1427: FILE *ficreseij;
                   1428: char filerese[FILENAMELENGTH];
                   1429: FILE *ficresstdeij;
                   1430: char fileresstde[FILENAMELENGTH];
                   1431: FILE *ficrescveij;
                   1432: char filerescve[FILENAMELENGTH];
                   1433: FILE  *ficresvij;
                   1434: char fileresv[FILENAMELENGTH];
1.269     brouard  1435: 
1.126     brouard  1436: char title[MAXLINE];
1.234     brouard  1437: char model[MAXLINE]; /**< The model line */
1.217     brouard  1438: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1439: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1440: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1441: char command[FILENAMELENGTH];
                   1442: int  outcmd=0;
                   1443: 
1.217     brouard  1444: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1445: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1446: char filelog[FILENAMELENGTH]; /* Log file */
                   1447: char filerest[FILENAMELENGTH];
                   1448: char fileregp[FILENAMELENGTH];
                   1449: char popfile[FILENAMELENGTH];
                   1450: 
                   1451: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1452: 
1.157     brouard  1453: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1454: /* struct timezone tzp; */
                   1455: /* extern int gettimeofday(); */
                   1456: struct tm tml, *gmtime(), *localtime();
                   1457: 
                   1458: extern time_t time();
                   1459: 
                   1460: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1461: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                   1462: struct tm tm;
                   1463: 
1.126     brouard  1464: char strcurr[80], strfor[80];
                   1465: 
                   1466: char *endptr;
                   1467: long lval;
                   1468: double dval;
                   1469: 
                   1470: #define NR_END 1
                   1471: #define FREE_ARG char*
                   1472: #define FTOL 1.0e-10
                   1473: 
                   1474: #define NRANSI 
1.240     brouard  1475: #define ITMAX 200
                   1476: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1477: 
                   1478: #define TOL 2.0e-4 
                   1479: 
                   1480: #define CGOLD 0.3819660 
                   1481: #define ZEPS 1.0e-10 
                   1482: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1483: 
                   1484: #define GOLD 1.618034 
                   1485: #define GLIMIT 100.0 
                   1486: #define TINY 1.0e-20 
                   1487: 
                   1488: static double maxarg1,maxarg2;
                   1489: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1490: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1491:   
                   1492: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1493: #define rint(a) floor(a+0.5)
1.166     brouard  1494: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1495: #define mytinydouble 1.0e-16
1.166     brouard  1496: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1497: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1498: /* static double dsqrarg; */
                   1499: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1500: static double sqrarg;
                   1501: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1502: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1503: int agegomp= AGEGOMP;
                   1504: 
                   1505: int imx; 
                   1506: int stepm=1;
                   1507: /* Stepm, step in month: minimum step interpolation*/
                   1508: 
                   1509: int estepm;
                   1510: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1511: 
                   1512: int m,nb;
                   1513: long *num;
1.197     brouard  1514: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1515: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1516:                   covariate for which somebody answered excluding 
                   1517:                   undefined. Usually 2: 0 and 1. */
                   1518: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1519:                             covariate for which somebody answered including 
                   1520:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1521: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1522: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1523: double ***mobaverage, ***mobaverages; /* New global variable */
1.332     brouard  1524: 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  1525: double *ageexmed,*agecens;
                   1526: double dateintmean=0;
1.296     brouard  1527:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1528:   double anprojf, mprojf, jprojf;
1.126     brouard  1529: 
1.296     brouard  1530:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1531:   double anbackf, mbackf, jbackf;
                   1532:   double jintmean,mintmean,aintmean;  
1.126     brouard  1533: double *weight;
                   1534: int **s; /* Status */
1.141     brouard  1535: double *agedc;
1.145     brouard  1536: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1537:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1538:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1539: double **coqvar; /* Fixed quantitative covariate nqv */
1.341     brouard  1540: double ***cotvar; /* Time varying covariate start at ncovcol + nqv + (1 to ntv) */
1.225     brouard  1541: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1542: double  idx; 
                   1543: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.319     brouard  1544: /* Some documentation */
                   1545:       /*   Design original data
                   1546:        *  V1   V2   V3   V4  V5  V6  V7  V8  Weight ddb ddth d1st s1 V9 V10 V11 V12 s2 V9 V10 V11 V12 
                   1547:        *  <          ncovcol=6   >   nqv=2 (V7 V8)                   dv dv  dv  qtv    dv dv  dvv qtv
                   1548:        *                                                             ntv=3     nqtv=1
1.330     brouard  1549:        *  cptcovn number of covariates (not including constant and age or age*age) = number of plus sign + 1 = 10+1=11
1.319     brouard  1550:        * For time varying covariate, quanti or dummies
                   1551:        *       cotqvar[wav][iv(1 to nqtv)][i]= [1][12][i]=(V12) quanti
1.341     brouard  1552:        *       cotvar[wav][ncovcol+nqv+ iv(1 to nqtv)][i]= [(1 to nqtv)][i]=(V12) quanti
1.319     brouard  1553:        *       cotvar[wav][iv(1 to ntv)][i]= [1][1][i]=(V9) dummies at wav 1
                   1554:        *       cotvar[wav][iv(1 to ntv)][i]= [1][2][i]=(V10) dummies at wav 1
1.332     brouard  1555:        *       covar[Vk,i], value of the Vkth fixed covariate dummy or quanti for individual i:
1.319     brouard  1556:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   1557:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 + V9 + V9*age + V10
                   1558:        *   k=  1    2      3       4     5       6      7        8   9     10       11 
                   1559:        */
                   1560: /* According to the model, more columns can be added to covar by the product of covariates */
1.318     brouard  1561: /* 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
                   1562:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1563:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1564: */
1.343     brouard  1565: /*           V5+V4+ V3+V4*V3 +V5*age+V2 +V1*V2+V1*age+V1 */
                   1566: /*    kmodel  1  2   3   4     5    6    7     8    9 */
1.319     brouard  1567: /*Typevar[k]=  0  0   0   2     1    0    2     1    0 *//*0 for simple covariate (dummy, quantitative,*/
                   1568:                                                          /* fixed or varying), 1 for age product, 2 for*/
                   1569:                                                          /* product */
                   1570: /*Dummy[k]=    1  0   0   1     3    1    1     2    0 *//*Dummy[k] 0=dummy (0 1), 1 quantitative */
                   1571:                                                          /*(single or product without age), 2 dummy*/
                   1572:                                                          /* with age product, 3 quant with age product*/
                   1573: /*Tvar[k]=     5  4   3   6     5    2    7     1    1 */
                   1574: /*    nsd         1   2                              3 */ /* Counting single dummies covar fixed or tv */
1.330     brouard  1575: /*TnsdVar[Tvar]   1   2                              3 */ 
1.337     brouard  1576: /*Tvaraff[nsd]     4   3                              1 */ /* ID of single dummy cova fixed or timevary*/
1.319     brouard  1577: /*TvarsD[nsd]     4   3                              1 */ /* ID of single dummy cova fixed or timevary*/
1.338     brouard  1578: /*TvarsDind[nsd]  2   3                              9 */ /* position K of single dummy cova */
1.319     brouard  1579: /*    nsq      1                     2                 */ /* Counting single quantit tv */
                   1580: /* TvarsQ[k]   5                     2                 */ /* Number of single quantitative cova */
                   1581: /* TvarsQind   1                     6                 */ /* position K of single quantitative cova */
                   1582: /* Tprod[i]=k             1               2            */ /* Position in model of the ith prod without age */
                   1583: /* cptcovage                    1               2      */ /* Counting cov*age in the model equation */
                   1584: /* Tage[cptcovage]=k            5               8      */ /* Position in the model of ith cov*age */
                   1585: /* Tvard[1][1]@4={4,3,1,2}    V4*V3 V1*V2              */ /* Position in model of the ith prod without age */
1.330     brouard  1586: /* 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  1587: /* 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  1588: /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.234     brouard  1589: /* Type                    */
                   1590: /* V         1  2  3  4  5 */
                   1591: /*           F  F  V  V  V */
                   1592: /*           D  Q  D  D  Q */
                   1593: /*                         */
                   1594: int *TvarsD;
1.330     brouard  1595: int *TnsdVar;
1.234     brouard  1596: int *TvarsDind;
                   1597: int *TvarsQ;
                   1598: int *TvarsQind;
                   1599: 
1.318     brouard  1600: #define MAXRESULTLINESPONE 10+1
1.235     brouard  1601: int nresult=0;
1.258     brouard  1602: int parameterline=0; /* # of the parameter (type) line */
1.334     brouard  1603: int TKresult[MAXRESULTLINESPONE]; /* TKresult[nres]=k for each resultline nres give the corresponding combination of dummies */
                   1604: int resultmodel[MAXRESULTLINESPONE][NCOVMAX];/* resultmodel[k1]=k3: k1th position in the model corresponds to the k3 position in the resultline */
                   1605: int modelresult[MAXRESULTLINESPONE][NCOVMAX];/* modelresult[k3]=k1: k1th position in the model corresponds to the k3 position in the resultline */
                   1606: int Tresult[MAXRESULTLINESPONE][NCOVMAX];/* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1607: int Tinvresult[MAXRESULTLINESPONE][NCOVMAX];/* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line  */
                   1608: double TinvDoQresult[MAXRESULTLINESPONE][NCOVMAX];/* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line */
1.334     brouard  1609: int Tvresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1610: double Tqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
1.318     brouard  1611: double Tqinvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
1.332     brouard  1612: int Tvqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline */
1.318     brouard  1613: 
                   1614: /* 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
                   1615:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1616:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1617: */
1.234     brouard  1618: /* 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  1619: 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 */
                   1620: 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 */
                   1621: 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 */
                   1622: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1623: 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 */
                   1624: 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  1625: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1626: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1627: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1628: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1629: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1630: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1631: 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 */
                   1632: 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  1633: int *TvarVV; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1634: int *TvarVVind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1635:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   1636:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   1637:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   1638:       /* TvarVV={3,1,3}, for V3 and then the product V1*V3 is decomposed into V1 and V3 */            
                   1639:       /* TvarVVind={2,5,5}, for V3 and then the product V1*V3 is decomposed into V1 and V3 */         
1.230     brouard  1640: int *Tvarsel; /**< Selected covariates for output */
                   1641: double *Tvalsel; /**< Selected modality value of covariate for output */
1.226     brouard  1642: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.227     brouard  1643: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1644: 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  1645: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1646: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1647: int *Tage;
1.227     brouard  1648: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1649: 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  1650: 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*/ 
                   1651: 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  1652: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1653: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1654: int **Tvard;
1.330     brouard  1655: int **Tvardk;
1.227     brouard  1656: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1657: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1658: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1659:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1660:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1661: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1662: double *lsurv, *lpop, *tpop;
                   1663: 
1.231     brouard  1664: #define FD 1; /* Fixed dummy covariate */
                   1665: #define FQ 2; /* Fixed quantitative covariate */
                   1666: #define FP 3; /* Fixed product covariate */
                   1667: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1668: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1669: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1670: #define VD 10; /* Varying dummy covariate */
                   1671: #define VQ 11; /* Varying quantitative covariate */
                   1672: #define VP 12; /* Varying product covariate */
                   1673: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1674: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1675: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1676: #define APFD 16; /* Age product * fixed dummy covariate */
                   1677: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1678: #define APVD 18; /* Age product * varying dummy covariate */
                   1679: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1680: 
                   1681: #define FTYPE 1; /* Fixed covariate */
                   1682: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1683: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1684: 
                   1685: struct kmodel{
                   1686:        int maintype; /* main type */
                   1687:        int subtype; /* subtype */
                   1688: };
                   1689: struct kmodel modell[NCOVMAX];
                   1690: 
1.143     brouard  1691: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1692: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1693: 
                   1694: /**************** split *************************/
                   1695: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1696: {
                   1697:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1698:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1699:   */ 
                   1700:   char *ss;                            /* pointer */
1.186     brouard  1701:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1702: 
                   1703:   l1 = strlen(path );                  /* length of path */
                   1704:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1705:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1706:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1707:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1708:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1709:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1710:     /* get current working directory */
                   1711:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1712: #ifdef WIN32
                   1713:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1714: #else
                   1715:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1716: #endif
1.126     brouard  1717:       return( GLOCK_ERROR_GETCWD );
                   1718:     }
                   1719:     /* got dirc from getcwd*/
                   1720:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1721:   } else {                             /* strip directory from path */
1.126     brouard  1722:     ss++;                              /* after this, the filename */
                   1723:     l2 = strlen( ss );                 /* length of filename */
                   1724:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1725:     strcpy( name, ss );                /* save file name */
                   1726:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1727:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1728:     printf(" DIRC2 = %s \n",dirc);
                   1729:   }
                   1730:   /* We add a separator at the end of dirc if not exists */
                   1731:   l1 = strlen( dirc );                 /* length of directory */
                   1732:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1733:     dirc[l1] =  DIRSEPARATOR;
                   1734:     dirc[l1+1] = 0; 
                   1735:     printf(" DIRC3 = %s \n",dirc);
                   1736:   }
                   1737:   ss = strrchr( name, '.' );           /* find last / */
                   1738:   if (ss >0){
                   1739:     ss++;
                   1740:     strcpy(ext,ss);                    /* save extension */
                   1741:     l1= strlen( name);
                   1742:     l2= strlen(ss)+1;
                   1743:     strncpy( finame, name, l1-l2);
                   1744:     finame[l1-l2]= 0;
                   1745:   }
                   1746: 
                   1747:   return( 0 );                         /* we're done */
                   1748: }
                   1749: 
                   1750: 
                   1751: /******************************************/
                   1752: 
                   1753: void replace_back_to_slash(char *s, char*t)
                   1754: {
                   1755:   int i;
                   1756:   int lg=0;
                   1757:   i=0;
                   1758:   lg=strlen(t);
                   1759:   for(i=0; i<= lg; i++) {
                   1760:     (s[i] = t[i]);
                   1761:     if (t[i]== '\\') s[i]='/';
                   1762:   }
                   1763: }
                   1764: 
1.132     brouard  1765: char *trimbb(char *out, char *in)
1.137     brouard  1766: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1767:   char *s;
                   1768:   s=out;
                   1769:   while (*in != '\0'){
1.137     brouard  1770:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1771:       in++;
                   1772:     }
                   1773:     *out++ = *in++;
                   1774:   }
                   1775:   *out='\0';
                   1776:   return s;
                   1777: }
                   1778: 
1.187     brouard  1779: /* char *substrchaine(char *out, char *in, char *chain) */
                   1780: /* { */
                   1781: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1782: /*   char *s, *t; */
                   1783: /*   t=in;s=out; */
                   1784: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1785: /*     *out++ = *in++; */
                   1786: /*   } */
                   1787: 
                   1788: /*   /\* *in matches *chain *\/ */
                   1789: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1790: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1791: /*   } */
                   1792: /*   in--; chain--; */
                   1793: /*   while ( (*in != '\0')){ */
                   1794: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1795: /*     *out++ = *in++; */
                   1796: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1797: /*   } */
                   1798: /*   *out='\0'; */
                   1799: /*   out=s; */
                   1800: /*   return out; */
                   1801: /* } */
                   1802: char *substrchaine(char *out, char *in, char *chain)
                   1803: {
                   1804:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1805:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1806: 
                   1807:   char *strloc;
                   1808: 
                   1809:   strcpy (out, in); 
                   1810:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1811:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1812:   if(strloc != NULL){ 
                   1813:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1814:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1815:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1816:   }
                   1817:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1818:   return out;
                   1819: }
                   1820: 
                   1821: 
1.145     brouard  1822: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1823: {
1.187     brouard  1824:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1825:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.310     brouard  1826:      gives alocc="abcdef" and blocc="ghi2j".
1.145     brouard  1827:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1828:   */
1.160     brouard  1829:   char *s, *t;
1.145     brouard  1830:   t=in;s=in;
                   1831:   while ((*in != occ) && (*in != '\0')){
                   1832:     *alocc++ = *in++;
                   1833:   }
                   1834:   if( *in == occ){
                   1835:     *(alocc)='\0';
                   1836:     s=++in;
                   1837:   }
                   1838:  
                   1839:   if (s == t) {/* occ not found */
                   1840:     *(alocc-(in-s))='\0';
                   1841:     in=s;
                   1842:   }
                   1843:   while ( *in != '\0'){
                   1844:     *blocc++ = *in++;
                   1845:   }
                   1846: 
                   1847:   *blocc='\0';
                   1848:   return t;
                   1849: }
1.137     brouard  1850: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1851: {
1.187     brouard  1852:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1853:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1854:      gives blocc="abcdef2ghi" and alocc="j".
                   1855:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1856:   */
                   1857:   char *s, *t;
                   1858:   t=in;s=in;
                   1859:   while (*in != '\0'){
                   1860:     while( *in == occ){
                   1861:       *blocc++ = *in++;
                   1862:       s=in;
                   1863:     }
                   1864:     *blocc++ = *in++;
                   1865:   }
                   1866:   if (s == t) /* occ not found */
                   1867:     *(blocc-(in-s))='\0';
                   1868:   else
                   1869:     *(blocc-(in-s)-1)='\0';
                   1870:   in=s;
                   1871:   while ( *in != '\0'){
                   1872:     *alocc++ = *in++;
                   1873:   }
                   1874: 
                   1875:   *alocc='\0';
                   1876:   return s;
                   1877: }
                   1878: 
1.126     brouard  1879: int nbocc(char *s, char occ)
                   1880: {
                   1881:   int i,j=0;
                   1882:   int lg=20;
                   1883:   i=0;
                   1884:   lg=strlen(s);
                   1885:   for(i=0; i<= lg; i++) {
1.234     brouard  1886:     if  (s[i] == occ ) j++;
1.126     brouard  1887:   }
                   1888:   return j;
                   1889: }
                   1890: 
1.137     brouard  1891: /* void cutv(char *u,char *v, char*t, char occ) */
                   1892: /* { */
                   1893: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1894: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1895: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1896: /*   int i,lg,j,p=0; */
                   1897: /*   i=0; */
                   1898: /*   lg=strlen(t); */
                   1899: /*   for(j=0; j<=lg-1; j++) { */
                   1900: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1901: /*   } */
1.126     brouard  1902: 
1.137     brouard  1903: /*   for(j=0; j<p; j++) { */
                   1904: /*     (u[j] = t[j]); */
                   1905: /*   } */
                   1906: /*      u[p]='\0'; */
1.126     brouard  1907: 
1.137     brouard  1908: /*    for(j=0; j<= lg; j++) { */
                   1909: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1910: /*   } */
                   1911: /* } */
1.126     brouard  1912: 
1.160     brouard  1913: #ifdef _WIN32
                   1914: char * strsep(char **pp, const char *delim)
                   1915: {
                   1916:   char *p, *q;
                   1917:          
                   1918:   if ((p = *pp) == NULL)
                   1919:     return 0;
                   1920:   if ((q = strpbrk (p, delim)) != NULL)
                   1921:   {
                   1922:     *pp = q + 1;
                   1923:     *q = '\0';
                   1924:   }
                   1925:   else
                   1926:     *pp = 0;
                   1927:   return p;
                   1928: }
                   1929: #endif
                   1930: 
1.126     brouard  1931: /********************** nrerror ********************/
                   1932: 
                   1933: void nrerror(char error_text[])
                   1934: {
                   1935:   fprintf(stderr,"ERREUR ...\n");
                   1936:   fprintf(stderr,"%s\n",error_text);
                   1937:   exit(EXIT_FAILURE);
                   1938: }
                   1939: /*********************** vector *******************/
                   1940: double *vector(int nl, int nh)
                   1941: {
                   1942:   double *v;
                   1943:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1944:   if (!v) nrerror("allocation failure in vector");
                   1945:   return v-nl+NR_END;
                   1946: }
                   1947: 
                   1948: /************************ free vector ******************/
                   1949: void free_vector(double*v, int nl, int nh)
                   1950: {
                   1951:   free((FREE_ARG)(v+nl-NR_END));
                   1952: }
                   1953: 
                   1954: /************************ivector *******************************/
                   1955: int *ivector(long nl,long nh)
                   1956: {
                   1957:   int *v;
                   1958:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1959:   if (!v) nrerror("allocation failure in ivector");
                   1960:   return v-nl+NR_END;
                   1961: }
                   1962: 
                   1963: /******************free ivector **************************/
                   1964: void free_ivector(int *v, long nl, long nh)
                   1965: {
                   1966:   free((FREE_ARG)(v+nl-NR_END));
                   1967: }
                   1968: 
                   1969: /************************lvector *******************************/
                   1970: long *lvector(long nl,long nh)
                   1971: {
                   1972:   long *v;
                   1973:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1974:   if (!v) nrerror("allocation failure in ivector");
                   1975:   return v-nl+NR_END;
                   1976: }
                   1977: 
                   1978: /******************free lvector **************************/
                   1979: void free_lvector(long *v, long nl, long nh)
                   1980: {
                   1981:   free((FREE_ARG)(v+nl-NR_END));
                   1982: }
                   1983: 
                   1984: /******************* imatrix *******************************/
                   1985: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1986:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1987: { 
                   1988:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1989:   int **m; 
                   1990:   
                   1991:   /* allocate pointers to rows */ 
                   1992:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1993:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1994:   m += NR_END; 
                   1995:   m -= nrl; 
                   1996:   
                   1997:   
                   1998:   /* allocate rows and set pointers to them */ 
                   1999:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   2000:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   2001:   m[nrl] += NR_END; 
                   2002:   m[nrl] -= ncl; 
                   2003:   
                   2004:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   2005:   
                   2006:   /* return pointer to array of pointers to rows */ 
                   2007:   return m; 
                   2008: } 
                   2009: 
                   2010: /****************** free_imatrix *************************/
                   2011: void free_imatrix(m,nrl,nrh,ncl,nch)
                   2012:       int **m;
                   2013:       long nch,ncl,nrh,nrl; 
                   2014:      /* free an int matrix allocated by imatrix() */ 
                   2015: { 
                   2016:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   2017:   free((FREE_ARG) (m+nrl-NR_END)); 
                   2018: } 
                   2019: 
                   2020: /******************* matrix *******************************/
                   2021: double **matrix(long nrl, long nrh, long ncl, long nch)
                   2022: {
                   2023:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   2024:   double **m;
                   2025: 
                   2026:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2027:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2028:   m += NR_END;
                   2029:   m -= nrl;
                   2030: 
                   2031:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2032:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2033:   m[nrl] += NR_END;
                   2034:   m[nrl] -= ncl;
                   2035: 
                   2036:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2037:   return m;
1.145     brouard  2038:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   2039: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   2040: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  2041:    */
                   2042: }
                   2043: 
                   2044: /*************************free matrix ************************/
                   2045: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   2046: {
                   2047:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2048:   free((FREE_ARG)(m+nrl-NR_END));
                   2049: }
                   2050: 
                   2051: /******************* ma3x *******************************/
                   2052: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   2053: {
                   2054:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   2055:   double ***m;
                   2056: 
                   2057:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2058:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2059:   m += NR_END;
                   2060:   m -= nrl;
                   2061: 
                   2062:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2063:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2064:   m[nrl] += NR_END;
                   2065:   m[nrl] -= ncl;
                   2066: 
                   2067:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2068: 
                   2069:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   2070:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   2071:   m[nrl][ncl] += NR_END;
                   2072:   m[nrl][ncl] -= nll;
                   2073:   for (j=ncl+1; j<=nch; j++) 
                   2074:     m[nrl][j]=m[nrl][j-1]+nlay;
                   2075:   
                   2076:   for (i=nrl+1; i<=nrh; i++) {
                   2077:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   2078:     for (j=ncl+1; j<=nch; j++) 
                   2079:       m[i][j]=m[i][j-1]+nlay;
                   2080:   }
                   2081:   return m; 
                   2082:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   2083:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   2084:   */
                   2085: }
                   2086: 
                   2087: /*************************free ma3x ************************/
                   2088: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   2089: {
                   2090:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   2091:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2092:   free((FREE_ARG)(m+nrl-NR_END));
                   2093: }
                   2094: 
                   2095: /*************** function subdirf ***********/
                   2096: char *subdirf(char fileres[])
                   2097: {
                   2098:   /* Caution optionfilefiname is hidden */
                   2099:   strcpy(tmpout,optionfilefiname);
                   2100:   strcat(tmpout,"/"); /* Add to the right */
                   2101:   strcat(tmpout,fileres);
                   2102:   return tmpout;
                   2103: }
                   2104: 
                   2105: /*************** function subdirf2 ***********/
                   2106: char *subdirf2(char fileres[], char *preop)
                   2107: {
1.314     brouard  2108:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
                   2109:  Errors in subdirf, 2, 3 while printing tmpout is
1.315     brouard  2110:  rewritten within the same printf. Workaround: many printfs */
1.126     brouard  2111:   /* Caution optionfilefiname is hidden */
                   2112:   strcpy(tmpout,optionfilefiname);
                   2113:   strcat(tmpout,"/");
                   2114:   strcat(tmpout,preop);
                   2115:   strcat(tmpout,fileres);
                   2116:   return tmpout;
                   2117: }
                   2118: 
                   2119: /*************** function subdirf3 ***********/
                   2120: char *subdirf3(char fileres[], char *preop, char *preop2)
                   2121: {
                   2122:   
                   2123:   /* Caution optionfilefiname is hidden */
                   2124:   strcpy(tmpout,optionfilefiname);
                   2125:   strcat(tmpout,"/");
                   2126:   strcat(tmpout,preop);
                   2127:   strcat(tmpout,preop2);
                   2128:   strcat(tmpout,fileres);
                   2129:   return tmpout;
                   2130: }
1.213     brouard  2131:  
                   2132: /*************** function subdirfext ***********/
                   2133: char *subdirfext(char fileres[], char *preop, char *postop)
                   2134: {
                   2135:   
                   2136:   strcpy(tmpout,preop);
                   2137:   strcat(tmpout,fileres);
                   2138:   strcat(tmpout,postop);
                   2139:   return tmpout;
                   2140: }
1.126     brouard  2141: 
1.213     brouard  2142: /*************** function subdirfext3 ***********/
                   2143: char *subdirfext3(char fileres[], char *preop, char *postop)
                   2144: {
                   2145:   
                   2146:   /* Caution optionfilefiname is hidden */
                   2147:   strcpy(tmpout,optionfilefiname);
                   2148:   strcat(tmpout,"/");
                   2149:   strcat(tmpout,preop);
                   2150:   strcat(tmpout,fileres);
                   2151:   strcat(tmpout,postop);
                   2152:   return tmpout;
                   2153: }
                   2154:  
1.162     brouard  2155: char *asc_diff_time(long time_sec, char ascdiff[])
                   2156: {
                   2157:   long sec_left, days, hours, minutes;
                   2158:   days = (time_sec) / (60*60*24);
                   2159:   sec_left = (time_sec) % (60*60*24);
                   2160:   hours = (sec_left) / (60*60) ;
                   2161:   sec_left = (sec_left) %(60*60);
                   2162:   minutes = (sec_left) /60;
                   2163:   sec_left = (sec_left) % (60);
                   2164:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   2165:   return ascdiff;
                   2166: }
                   2167: 
1.126     brouard  2168: /***************** f1dim *************************/
                   2169: extern int ncom; 
                   2170: extern double *pcom,*xicom;
                   2171: extern double (*nrfunc)(double []); 
                   2172:  
                   2173: double f1dim(double x) 
                   2174: { 
                   2175:   int j; 
                   2176:   double f;
                   2177:   double *xt; 
                   2178:  
                   2179:   xt=vector(1,ncom); 
                   2180:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   2181:   f=(*nrfunc)(xt); 
                   2182:   free_vector(xt,1,ncom); 
                   2183:   return f; 
                   2184: } 
                   2185: 
                   2186: /*****************brent *************************/
                   2187: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  2188: {
                   2189:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   2190:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   2191:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   2192:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   2193:    * returned function value. 
                   2194:   */
1.126     brouard  2195:   int iter; 
                   2196:   double a,b,d,etemp;
1.159     brouard  2197:   double fu=0,fv,fw,fx;
1.164     brouard  2198:   double ftemp=0.;
1.126     brouard  2199:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   2200:   double e=0.0; 
                   2201:  
                   2202:   a=(ax < cx ? ax : cx); 
                   2203:   b=(ax > cx ? ax : cx); 
                   2204:   x=w=v=bx; 
                   2205:   fw=fv=fx=(*f)(x); 
                   2206:   for (iter=1;iter<=ITMAX;iter++) { 
                   2207:     xm=0.5*(a+b); 
                   2208:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   2209:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   2210:     printf(".");fflush(stdout);
                   2211:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  2212: #ifdef DEBUGBRENT
1.126     brouard  2213:     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);
                   2214:     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);
                   2215:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   2216: #endif
                   2217:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   2218:       *xmin=x; 
                   2219:       return fx; 
                   2220:     } 
                   2221:     ftemp=fu;
                   2222:     if (fabs(e) > tol1) { 
                   2223:       r=(x-w)*(fx-fv); 
                   2224:       q=(x-v)*(fx-fw); 
                   2225:       p=(x-v)*q-(x-w)*r; 
                   2226:       q=2.0*(q-r); 
                   2227:       if (q > 0.0) p = -p; 
                   2228:       q=fabs(q); 
                   2229:       etemp=e; 
                   2230:       e=d; 
                   2231:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  2232:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  2233:       else { 
1.224     brouard  2234:                                d=p/q; 
                   2235:                                u=x+d; 
                   2236:                                if (u-a < tol2 || b-u < tol2) 
                   2237:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  2238:       } 
                   2239:     } else { 
                   2240:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2241:     } 
                   2242:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   2243:     fu=(*f)(u); 
                   2244:     if (fu <= fx) { 
                   2245:       if (u >= x) a=x; else b=x; 
                   2246:       SHFT(v,w,x,u) 
1.183     brouard  2247:       SHFT(fv,fw,fx,fu) 
                   2248:     } else { 
                   2249:       if (u < x) a=u; else b=u; 
                   2250:       if (fu <= fw || w == x) { 
1.224     brouard  2251:                                v=w; 
                   2252:                                w=u; 
                   2253:                                fv=fw; 
                   2254:                                fw=fu; 
1.183     brouard  2255:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  2256:                                v=u; 
                   2257:                                fv=fu; 
1.183     brouard  2258:       } 
                   2259:     } 
1.126     brouard  2260:   } 
                   2261:   nrerror("Too many iterations in brent"); 
                   2262:   *xmin=x; 
                   2263:   return fx; 
                   2264: } 
                   2265: 
                   2266: /****************** mnbrak ***********************/
                   2267: 
                   2268: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2269:            double (*func)(double)) 
1.183     brouard  2270: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2271: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2272: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2273: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2274:    */
1.126     brouard  2275:   double ulim,u,r,q, dum;
                   2276:   double fu; 
1.187     brouard  2277: 
                   2278:   double scale=10.;
                   2279:   int iterscale=0;
                   2280: 
                   2281:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2282:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2283: 
                   2284: 
                   2285:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2286:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2287:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2288:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2289:   /* } */
                   2290: 
1.126     brouard  2291:   if (*fb > *fa) { 
                   2292:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2293:     SHFT(dum,*fb,*fa,dum) 
                   2294:   } 
1.126     brouard  2295:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2296:   *fc=(*func)(*cx); 
1.183     brouard  2297: #ifdef DEBUG
1.224     brouard  2298:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2299:   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  2300: #endif
1.224     brouard  2301:   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  2302:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2303:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2304:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2305:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2306:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2307:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2308:       fu=(*func)(u); 
1.163     brouard  2309: #ifdef DEBUG
                   2310:       /* f(x)=A(x-u)**2+f(u) */
                   2311:       double A, fparabu; 
                   2312:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2313:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2314:       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);
                   2315:       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  2316:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2317:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2318:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2319:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2320: #endif 
1.184     brouard  2321: #ifdef MNBRAKORIGINAL
1.183     brouard  2322: #else
1.191     brouard  2323: /*       if (fu > *fc) { */
                   2324: /* #ifdef DEBUG */
                   2325: /*       printf("mnbrak4  fu > fc \n"); */
                   2326: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2327: /* #endif */
                   2328: /*     /\* 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 *\\/  *\/ */
                   2329: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2330: /*     dum=u; /\* Shifting c and u *\/ */
                   2331: /*     u = *cx; */
                   2332: /*     *cx = dum; */
                   2333: /*     dum = fu; */
                   2334: /*     fu = *fc; */
                   2335: /*     *fc =dum; */
                   2336: /*       } else { /\* end *\/ */
                   2337: /* #ifdef DEBUG */
                   2338: /*       printf("mnbrak3  fu < fc \n"); */
                   2339: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2340: /* #endif */
                   2341: /*     dum=u; /\* Shifting c and u *\/ */
                   2342: /*     u = *cx; */
                   2343: /*     *cx = dum; */
                   2344: /*     dum = fu; */
                   2345: /*     fu = *fc; */
                   2346: /*     *fc =dum; */
                   2347: /*       } */
1.224     brouard  2348: #ifdef DEBUGMNBRAK
                   2349:                 double A, fparabu; 
                   2350:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2351:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2352:      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);
                   2353:      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  2354: #endif
1.191     brouard  2355:       dum=u; /* Shifting c and u */
                   2356:       u = *cx;
                   2357:       *cx = dum;
                   2358:       dum = fu;
                   2359:       fu = *fc;
                   2360:       *fc =dum;
1.183     brouard  2361: #endif
1.162     brouard  2362:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2363: #ifdef DEBUG
1.224     brouard  2364:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2365:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2366: #endif
1.126     brouard  2367:       fu=(*func)(u); 
                   2368:       if (fu < *fc) { 
1.183     brouard  2369: #ifdef DEBUG
1.224     brouard  2370:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2371:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2372: #endif
                   2373:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2374:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2375: #ifdef DEBUG
                   2376:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2377: #endif
                   2378:       } 
1.162     brouard  2379:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2380: #ifdef DEBUG
1.224     brouard  2381:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2382:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2383: #endif
1.126     brouard  2384:       u=ulim; 
                   2385:       fu=(*func)(u); 
1.183     brouard  2386:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2387: #ifdef DEBUG
1.224     brouard  2388:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2389:       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  2390: #endif
1.126     brouard  2391:       u=(*cx)+GOLD*(*cx-*bx); 
                   2392:       fu=(*func)(u); 
1.224     brouard  2393: #ifdef DEBUG
                   2394:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2395:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2396: #endif
1.183     brouard  2397:     } /* end tests */
1.126     brouard  2398:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2399:     SHFT(*fa,*fb,*fc,fu) 
                   2400: #ifdef DEBUG
1.224     brouard  2401:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2402:       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  2403: #endif
                   2404:   } /* 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  2405: } 
                   2406: 
                   2407: /*************** linmin ************************/
1.162     brouard  2408: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2409: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2410: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2411: the value of func at the returned location p . This is actually all accomplished by calling the
                   2412: routines mnbrak and brent .*/
1.126     brouard  2413: int ncom; 
                   2414: double *pcom,*xicom;
                   2415: double (*nrfunc)(double []); 
                   2416:  
1.224     brouard  2417: #ifdef LINMINORIGINAL
1.126     brouard  2418: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2419: #else
                   2420: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2421: #endif
1.126     brouard  2422: { 
                   2423:   double brent(double ax, double bx, double cx, 
                   2424:               double (*f)(double), double tol, double *xmin); 
                   2425:   double f1dim(double x); 
                   2426:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2427:              double *fc, double (*func)(double)); 
                   2428:   int j; 
                   2429:   double xx,xmin,bx,ax; 
                   2430:   double fx,fb,fa;
1.187     brouard  2431: 
1.203     brouard  2432: #ifdef LINMINORIGINAL
                   2433: #else
                   2434:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2435: #endif
                   2436:   
1.126     brouard  2437:   ncom=n; 
                   2438:   pcom=vector(1,n); 
                   2439:   xicom=vector(1,n); 
                   2440:   nrfunc=func; 
                   2441:   for (j=1;j<=n;j++) { 
                   2442:     pcom[j]=p[j]; 
1.202     brouard  2443:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2444:   } 
1.187     brouard  2445: 
1.203     brouard  2446: #ifdef LINMINORIGINAL
                   2447:   xx=1.;
                   2448: #else
                   2449:   axs=0.0;
                   2450:   xxs=1.;
                   2451:   do{
                   2452:     xx= xxs;
                   2453: #endif
1.187     brouard  2454:     ax=0.;
                   2455:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2456:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2457:     /* 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))   */
                   2458:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2459:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2460:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2461:     /* 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  2462: #ifdef LINMINORIGINAL
                   2463: #else
                   2464:     if (fx != fx){
1.224     brouard  2465:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2466:                        printf("|");
                   2467:                        fprintf(ficlog,"|");
1.203     brouard  2468: #ifdef DEBUGLINMIN
1.224     brouard  2469:                        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  2470: #endif
                   2471:     }
1.224     brouard  2472:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2473: #endif
                   2474:   
1.191     brouard  2475: #ifdef DEBUGLINMIN
                   2476:   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  2477:   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  2478: #endif
1.224     brouard  2479: #ifdef LINMINORIGINAL
                   2480: #else
1.317     brouard  2481:   if(fb == fx){ /* Flat function in the direction */
                   2482:     xmin=xx;
1.224     brouard  2483:     *flat=1;
1.317     brouard  2484:   }else{
1.224     brouard  2485:     *flat=0;
                   2486: #endif
                   2487:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2488:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2489:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2490:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2491:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2492:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2493: #ifdef DEBUG
1.224     brouard  2494:   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);
                   2495:   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);
                   2496: #endif
                   2497: #ifdef LINMINORIGINAL
                   2498: #else
                   2499:                        }
1.126     brouard  2500: #endif
1.191     brouard  2501: #ifdef DEBUGLINMIN
                   2502:   printf("linmin end ");
1.202     brouard  2503:   fprintf(ficlog,"linmin end ");
1.191     brouard  2504: #endif
1.126     brouard  2505:   for (j=1;j<=n;j++) { 
1.203     brouard  2506: #ifdef LINMINORIGINAL
                   2507:     xi[j] *= xmin; 
                   2508: #else
                   2509: #ifdef DEBUGLINMIN
                   2510:     if(xxs <1.0)
                   2511:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2512: #endif
                   2513:     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) */
                   2514: #ifdef DEBUGLINMIN
                   2515:     if(xxs <1.0)
                   2516:       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 );
                   2517: #endif
                   2518: #endif
1.187     brouard  2519:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2520:   } 
1.191     brouard  2521: #ifdef DEBUGLINMIN
1.203     brouard  2522:   printf("\n");
1.191     brouard  2523:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2524:   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  2525:   for (j=1;j<=n;j++) { 
1.202     brouard  2526:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2527:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2528:     if(j % ncovmodel == 0){
1.191     brouard  2529:       printf("\n");
1.202     brouard  2530:       fprintf(ficlog,"\n");
                   2531:     }
1.191     brouard  2532:   }
1.203     brouard  2533: #else
1.191     brouard  2534: #endif
1.126     brouard  2535:   free_vector(xicom,1,n); 
                   2536:   free_vector(pcom,1,n); 
                   2537: } 
                   2538: 
                   2539: 
                   2540: /*************** powell ************************/
1.162     brouard  2541: /*
1.317     brouard  2542: Minimization of a function func of n variables. Input consists in an initial starting point
                   2543: p[1..n] ; an initial matrix xi[1..n][1..n]  whose columns contain the initial set of di-
                   2544: rections (usually the n unit vectors); and ftol, the fractional tolerance in the function value
                   2545: such that failure to decrease by more than this amount in one iteration signals doneness. On
1.162     brouard  2546: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2547: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2548:  */
1.224     brouard  2549: #ifdef LINMINORIGINAL
                   2550: #else
                   2551:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2552:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2553: #endif
1.126     brouard  2554: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2555:            double (*func)(double [])) 
                   2556: { 
1.224     brouard  2557: #ifdef LINMINORIGINAL
                   2558:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2559:              double (*func)(double [])); 
1.224     brouard  2560: #else 
1.241     brouard  2561:  void linmin(double p[], double xi[], int n, double *fret,
                   2562:             double (*func)(double []),int *flat); 
1.224     brouard  2563: #endif
1.239     brouard  2564:  int i,ibig,j,jk,k; 
1.126     brouard  2565:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2566:   double directest;
1.126     brouard  2567:   double fp,fptt;
                   2568:   double *xits;
                   2569:   int niterf, itmp;
                   2570: 
                   2571:   pt=vector(1,n); 
                   2572:   ptt=vector(1,n); 
                   2573:   xit=vector(1,n); 
                   2574:   xits=vector(1,n); 
                   2575:   *fret=(*func)(p); 
                   2576:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.338     brouard  2577:   rcurr_time = time(NULL);
                   2578:   fp=(*fret); /* Initialisation */
1.126     brouard  2579:   for (*iter=1;;++(*iter)) { 
                   2580:     ibig=0; 
                   2581:     del=0.0; 
1.157     brouard  2582:     rlast_time=rcurr_time;
                   2583:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2584:     rcurr_time = time(NULL);  
                   2585:     curr_time = *localtime(&rcurr_time);
1.337     brouard  2586:     /* 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); */
                   2587:     /* 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); */
                   2588:     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);
                   2589:     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  2590: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.324     brouard  2591:     fp=(*fret); /* From former iteration or initial value */
1.192     brouard  2592:     for (i=1;i<=n;i++) {
1.126     brouard  2593:       fprintf(ficrespow," %.12lf", p[i]);
                   2594:     }
1.239     brouard  2595:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2596:     printf("\n#model=  1      +     age ");
                   2597:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2598:     if(nagesqr==1){
1.241     brouard  2599:        printf("  + age*age  ");
                   2600:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2601:     }
                   2602:     for(j=1;j <=ncovmodel-2;j++){
                   2603:       if(Typevar[j]==0) {
                   2604:        printf("  +      V%d  ",Tvar[j]);
                   2605:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2606:       }else if(Typevar[j]==1) {
                   2607:        printf("  +    V%d*age ",Tvar[j]);
                   2608:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2609:       }else if(Typevar[j]==2) {
                   2610:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2611:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2612:       }
                   2613:     }
1.126     brouard  2614:     printf("\n");
1.239     brouard  2615: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2616: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2617:     fprintf(ficlog,"\n");
1.239     brouard  2618:     for(i=1,jk=1; i <=nlstate; i++){
                   2619:       for(k=1; k <=(nlstate+ndeath); k++){
                   2620:        if (k != i) {
                   2621:          printf("%d%d ",i,k);
                   2622:          fprintf(ficlog,"%d%d ",i,k);
                   2623:          for(j=1; j <=ncovmodel; j++){
                   2624:            printf("%12.7f ",p[jk]);
                   2625:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2626:            jk++; 
                   2627:          }
                   2628:          printf("\n");
                   2629:          fprintf(ficlog,"\n");
                   2630:        }
                   2631:       }
                   2632:     }
1.241     brouard  2633:     if(*iter <=3 && *iter >1){
1.157     brouard  2634:       tml = *localtime(&rcurr_time);
                   2635:       strcpy(strcurr,asctime(&tml));
                   2636:       rforecast_time=rcurr_time; 
1.126     brouard  2637:       itmp = strlen(strcurr);
                   2638:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2639:        strcurr[itmp-1]='\0';
1.162     brouard  2640:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2641:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  2642:       for(niterf=10;niterf<=30;niterf+=10){
1.241     brouard  2643:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2644:        forecast_time = *localtime(&rforecast_time);
                   2645:        strcpy(strfor,asctime(&forecast_time));
                   2646:        itmp = strlen(strfor);
                   2647:        if(strfor[itmp-1]=='\n')
                   2648:          strfor[itmp-1]='\0';
                   2649:        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);
                   2650:        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  2651:       }
                   2652:     }
1.187     brouard  2653:     for (i=1;i<=n;i++) { /* For each direction i */
                   2654:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2655:       fptt=(*fret); 
                   2656: #ifdef DEBUG
1.203     brouard  2657:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2658:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2659: #endif
1.203     brouard  2660:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2661:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2662: #ifdef LINMINORIGINAL
1.188     brouard  2663:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2664: #else
                   2665:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2666:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2667: #endif
                   2668:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2669:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2670:                                /* because that direction will be replaced unless the gain del is small */
                   2671:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2672:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2673:                                /* with the new direction. */
                   2674:                                del=fabs(fptt-(*fret)); 
                   2675:                                ibig=i; 
1.126     brouard  2676:       } 
                   2677: #ifdef DEBUG
                   2678:       printf("%d %.12e",i,(*fret));
                   2679:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2680:       for (j=1;j<=n;j++) {
1.224     brouard  2681:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2682:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2683:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2684:       }
                   2685:       for(j=1;j<=n;j++) {
1.225     brouard  2686:                                printf(" p(%d)=%.12e",j,p[j]);
                   2687:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2688:       }
                   2689:       printf("\n");
                   2690:       fprintf(ficlog,"\n");
                   2691: #endif
1.187     brouard  2692:     } /* end loop on each direction i */
                   2693:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2694:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2695:     /* New value of last point Pn is not computed, P(n-1) */
1.319     brouard  2696:     for(j=1;j<=n;j++) {
                   2697:       if(flatdir[j] >0){
                   2698:         printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2699:         fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
1.302     brouard  2700:       }
1.319     brouard  2701:       /* printf("\n"); */
                   2702:       /* fprintf(ficlog,"\n"); */
                   2703:     }
1.243     brouard  2704:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2705:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2706:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2707:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2708:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2709:       /* decreased of more than 3.84  */
                   2710:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2711:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2712:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2713:                        
1.188     brouard  2714:       /* Starting the program with initial values given by a former maximization will simply change */
                   2715:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2716:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2717:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2718: #ifdef DEBUG
                   2719:       int k[2],l;
                   2720:       k[0]=1;
                   2721:       k[1]=-1;
                   2722:       printf("Max: %.12e",(*func)(p));
                   2723:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2724:       for (j=1;j<=n;j++) {
                   2725:        printf(" %.12e",p[j]);
                   2726:        fprintf(ficlog," %.12e",p[j]);
                   2727:       }
                   2728:       printf("\n");
                   2729:       fprintf(ficlog,"\n");
                   2730:       for(l=0;l<=1;l++) {
                   2731:        for (j=1;j<=n;j++) {
                   2732:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2733:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2734:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2735:        }
                   2736:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2737:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2738:       }
                   2739: #endif
                   2740: 
                   2741:       free_vector(xit,1,n); 
                   2742:       free_vector(xits,1,n); 
                   2743:       free_vector(ptt,1,n); 
                   2744:       free_vector(pt,1,n); 
                   2745:       return; 
1.192     brouard  2746:     } /* enough precision */ 
1.240     brouard  2747:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2748:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2749:       ptt[j]=2.0*p[j]-pt[j]; 
                   2750:       xit[j]=p[j]-pt[j]; 
                   2751:       pt[j]=p[j]; 
                   2752:     } 
1.181     brouard  2753:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2754: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2755:                if (*iter <=4) {
1.225     brouard  2756: #else
                   2757: #endif
1.224     brouard  2758: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2759: #else
1.161     brouard  2760:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2761: #endif
1.162     brouard  2762:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2763:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2764:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2765:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2766:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2767:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2768:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2769:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2770:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2771:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2772:       /* mu² and del² are equal when f3=f1 */
                   2773:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2774:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2775:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2776:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2777: #ifdef NRCORIGINAL
                   2778:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2779: #else
                   2780:       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  2781:       t= t- del*SQR(fp-fptt);
1.183     brouard  2782: #endif
1.202     brouard  2783:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2784: #ifdef DEBUG
1.181     brouard  2785:       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);
                   2786:       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  2787:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2788:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2789:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2790:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2791:       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);
                   2792:       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);
                   2793: #endif
1.183     brouard  2794: #ifdef POWELLORIGINAL
                   2795:       if (t < 0.0) { /* Then we use it for new direction */
                   2796: #else
1.182     brouard  2797:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2798:                                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  2799:         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  2800:         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  2801:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2802:       } 
1.181     brouard  2803:       if (directest < 0.0) { /* Then we use it for new direction */
                   2804: #endif
1.191     brouard  2805: #ifdef DEBUGLINMIN
1.234     brouard  2806:        printf("Before linmin in direction P%d-P0\n",n);
                   2807:        for (j=1;j<=n;j++) {
                   2808:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2809:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2810:          if(j % ncovmodel == 0){
                   2811:            printf("\n");
                   2812:            fprintf(ficlog,"\n");
                   2813:          }
                   2814:        }
1.224     brouard  2815: #endif
                   2816: #ifdef LINMINORIGINAL
1.234     brouard  2817:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2818: #else
1.234     brouard  2819:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2820:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2821: #endif
1.234     brouard  2822:        
1.191     brouard  2823: #ifdef DEBUGLINMIN
1.234     brouard  2824:        for (j=1;j<=n;j++) { 
                   2825:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2826:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2827:          if(j % ncovmodel == 0){
                   2828:            printf("\n");
                   2829:            fprintf(ficlog,"\n");
                   2830:          }
                   2831:        }
1.224     brouard  2832: #endif
1.234     brouard  2833:        for (j=1;j<=n;j++) { 
                   2834:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2835:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2836:        }
1.224     brouard  2837: #ifdef LINMINORIGINAL
                   2838: #else
1.234     brouard  2839:        for (j=1, flatd=0;j<=n;j++) {
                   2840:          if(flatdir[j]>0)
                   2841:            flatd++;
                   2842:        }
                   2843:        if(flatd >0){
1.255     brouard  2844:          printf("%d flat directions: ",flatd);
                   2845:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  2846:          for (j=1;j<=n;j++) { 
                   2847:            if(flatdir[j]>0){
                   2848:              printf("%d ",j);
                   2849:              fprintf(ficlog,"%d ",j);
                   2850:            }
                   2851:          }
                   2852:          printf("\n");
                   2853:          fprintf(ficlog,"\n");
1.319     brouard  2854: #ifdef FLATSUP
                   2855:           free_vector(xit,1,n); 
                   2856:           free_vector(xits,1,n); 
                   2857:           free_vector(ptt,1,n); 
                   2858:           free_vector(pt,1,n); 
                   2859:           return;
                   2860: #endif
1.234     brouard  2861:        }
1.191     brouard  2862: #endif
1.234     brouard  2863:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2864:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2865:        
1.126     brouard  2866: #ifdef DEBUG
1.234     brouard  2867:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2868:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2869:        for(j=1;j<=n;j++){
                   2870:          printf(" %lf",xit[j]);
                   2871:          fprintf(ficlog," %lf",xit[j]);
                   2872:        }
                   2873:        printf("\n");
                   2874:        fprintf(ficlog,"\n");
1.126     brouard  2875: #endif
1.192     brouard  2876:       } /* end of t or directest negative */
1.224     brouard  2877: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2878: #else
1.234     brouard  2879:       } /* end if (fptt < fp)  */
1.192     brouard  2880: #endif
1.225     brouard  2881: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2882:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2883: #else
1.224     brouard  2884: #endif
1.234     brouard  2885:                } /* loop iteration */ 
1.126     brouard  2886: } 
1.234     brouard  2887:   
1.126     brouard  2888: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2889:   
1.235     brouard  2890:   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  2891:   {
1.338     brouard  2892:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij . Nicely done
1.279     brouard  2893:      *   (and selected quantitative values in nres)
                   2894:      *  by left multiplying the unit
                   2895:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   2896:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   2897:      * Wx is row vector: population in state 1, population in state 2, population dead
                   2898:      * or prevalence in state 1, prevalence in state 2, 0
                   2899:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   2900:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   2901:      * Output is prlim.
                   2902:      * Initial matrix pimij 
                   2903:      */
1.206     brouard  2904:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2905:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2906:   /*  0,                   0                  , 1} */
                   2907:   /*
                   2908:    * and after some iteration: */
                   2909:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2910:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2911:   /*  0,                   0                  , 1} */
                   2912:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2913:   /* {0.51571254859325999, 0.4842874514067399, */
                   2914:   /*  0.51326036147820708, 0.48673963852179264} */
                   2915:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2916:     
1.332     brouard  2917:     int i, ii,j,k, k1;
1.209     brouard  2918:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2919:   /* double **matprod2(); */ /* test */
1.218     brouard  2920:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2921:   double **newm;
1.209     brouard  2922:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2923:   int ncvloop=0;
1.288     brouard  2924:   int first=0;
1.169     brouard  2925:   
1.209     brouard  2926:   min=vector(1,nlstate);
                   2927:   max=vector(1,nlstate);
                   2928:   meandiff=vector(1,nlstate);
                   2929: 
1.218     brouard  2930:        /* Starting with matrix unity */
1.126     brouard  2931:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2932:     for (j=1;j<=nlstate+ndeath;j++){
                   2933:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2934:     }
1.169     brouard  2935:   
                   2936:   cov[1]=1.;
                   2937:   
                   2938:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2939:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2940:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2941:     ncvloop++;
1.126     brouard  2942:     newm=savm;
                   2943:     /* Covariates have to be included here again */
1.138     brouard  2944:     cov[2]=agefin;
1.319     brouard  2945:      if(nagesqr==1){
                   2946:       cov[3]= agefin*agefin;
                   2947:      }
1.332     brouard  2948:      /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   2949:      /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   2950:      for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   2951:        if(Typevar[k1]==1){ /* A product with age */
                   2952:         cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   2953:        }else{
                   2954:         cov[2+nagesqr+k1]=precov[nres][k1];
                   2955:        }
                   2956:      }/* End of loop on model equation */
                   2957:      
                   2958: /* Start of old code (replaced by a loop on position in the model equation */
                   2959:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only of the model *\/ */
                   2960:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   2961:     /*   /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; *\/ */
                   2962:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TnsdVar[TvarsD[k]])]; */
                   2963:     /*   /\* model = 1 +age + V1*V3 + age*V1 + V2 + V1 + age*V2 + V3 + V3*age + V1*V2  */
                   2964:     /*    * k                  1        2      3    4      5      6     7        8 */
                   2965:     /*    *cov[]   1    2      3        4      5    6      7      8     9       10 */
                   2966:     /*    *TypeVar[k]          2        1      0    0      1      0     1        2 */
                   2967:     /*    *Dummy[k]            0        2      0    0      2      0     2        0 */
                   2968:     /*    *Tvar[k]             4        1      2    1      2      3     3        5 */
                   2969:     /*    *nsd=3                              (1)  (2)           (3) */
                   2970:     /*    *TvarsD[nsd]                      [1]=2    1             3 */
                   2971:     /*    *TnsdVar                          [2]=2 [1]=1         [3]=3 */
                   2972:     /*    *TvarsDind[nsd](=k)               [1]=3 [2]=4         [3]=6 */
                   2973:     /*    *Tage[]                  [1]=1                  [2]=2      [3]=3 */
                   2974:     /*    *Tvard[]       [1][1]=1                                           [2][1]=1 */
                   2975:     /*    *                   [1][2]=3                                           [2][2]=2 */
                   2976:     /*    *Tprod[](=k)     [1]=1                                              [2]=8 */
                   2977:     /*    *TvarsDp(=Tvar)   [1]=1            [2]=2             [3]=3          [4]=5 */
                   2978:     /*    *TvarD (=k)       [1]=1            [2]=3 [3]=4       [3]=6          [4]=6 */
                   2979:     /*    *TvarsDpType */
                   2980:     /*    *si model= 1 + age + V3 + V2*age + V2 + V3*age */
                   2981:     /*    * nsd=1              (1)           (2) */
                   2982:     /*    *TvarsD[nsd]          3             2 */
                   2983:     /*    *TnsdVar           (3)=1          (2)=2 */
                   2984:     /*    *TvarsDind[nsd](=k)  [1]=1        [2]=3 */
                   2985:     /*    *Tage[]                  [1]=2           [2]= 3    */
                   2986:     /*    *\/ */
                   2987:     /*   /\* cov[++k1]=nbcode[TvarsD[k]][codtabm(ij,k)]; *\/ */
                   2988:     /*   /\* 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)); *\/ */
                   2989:     /* } */
                   2990:     /* for (k=1; k<=nsq;k++) { /\* For single quantitative varying covariates only of the model *\/ */
                   2991:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   2992:     /*   /\* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 *\/ */
                   2993:     /*   /\* cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   2994:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][resultmodel[nres][k1]] */
                   2995:     /*   /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   2996:     /*   /\* 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]); *\/ */
                   2997:     /* } */
                   2998:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   2999:     /*   if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   3000:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3001:     /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   3002:     /*   } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   3003:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   3004:     /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   3005:     /*   } */
                   3006:     /*   /\* 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]); *\/ */
                   3007:     /* } */
                   3008:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   3009:     /*   /\* 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]); *\/ */
                   3010:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3011:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3012:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3013:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3014:     /*         }else{ */
                   3015:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3016:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   3017:     /*         } */
                   3018:     /*   }else{ */
                   3019:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3020:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3021:     /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   3022:     /*         }else{ */
                   3023:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3024:     /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   3025:     /*         } */
                   3026:     /*   } */
                   3027:     /* } /\* End product without age *\/ */
                   3028: /* ENd of old code */
1.138     brouard  3029:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3030:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3031:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  3032:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3033:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.319     brouard  3034:     /* age and covariate values of ij are in 'cov' */
1.142     brouard  3035:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  3036:     
1.126     brouard  3037:     savm=oldm;
                   3038:     oldm=newm;
1.209     brouard  3039: 
                   3040:     for(j=1; j<=nlstate; j++){
                   3041:       max[j]=0.;
                   3042:       min[j]=1.;
                   3043:     }
                   3044:     for(i=1;i<=nlstate;i++){
                   3045:       sumnew=0;
                   3046:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   3047:       for(j=1; j<=nlstate; j++){ 
                   3048:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   3049:        max[j]=FMAX(max[j],prlim[i][j]);
                   3050:        min[j]=FMIN(min[j],prlim[i][j]);
                   3051:       }
                   3052:     }
                   3053: 
1.126     brouard  3054:     maxmax=0.;
1.209     brouard  3055:     for(j=1; j<=nlstate; j++){
                   3056:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   3057:       maxmax=FMAX(maxmax,meandiff[j]);
                   3058:       /* 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  3059:     } /* j loop */
1.203     brouard  3060:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  3061:     /* 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  3062:     if(maxmax < ftolpl){
1.209     brouard  3063:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   3064:       free_vector(min,1,nlstate);
                   3065:       free_vector(max,1,nlstate);
                   3066:       free_vector(meandiff,1,nlstate);
1.126     brouard  3067:       return prlim;
                   3068:     }
1.288     brouard  3069:   } /* agefin loop */
1.208     brouard  3070:     /* After some age loop it doesn't converge */
1.288     brouard  3071:   if(!first){
                   3072:     first=1;
                   3073:     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  3074:     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);
                   3075:   }else if (first >=1 && first <10){
                   3076:     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);
                   3077:     first++;
                   3078:   }else if (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:     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");
                   3081:     fprintf(ficlog,"Warning: the stable prevalence no convergence; too many cases, giving up noticing, even in log file\n");
                   3082:     first++;
1.288     brouard  3083:   }
                   3084: 
1.209     brouard  3085:   /* 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); */
                   3086:   free_vector(min,1,nlstate);
                   3087:   free_vector(max,1,nlstate);
                   3088:   free_vector(meandiff,1,nlstate);
1.208     brouard  3089:   
1.169     brouard  3090:   return prlim; /* should not reach here */
1.126     brouard  3091: }
                   3092: 
1.217     brouard  3093: 
                   3094:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   3095: 
1.218     brouard  3096:  /* 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) */
                   3097:  /* 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  3098:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  3099: {
1.264     brouard  3100:   /* 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  3101:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   3102:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   3103:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   3104:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   3105:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   3106:   /* Initial matrix pimij */
                   3107:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   3108:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   3109:   /*  0,                   0                  , 1} */
                   3110:   /*
                   3111:    * and after some iteration: */
                   3112:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   3113:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   3114:   /*  0,                   0                  , 1} */
                   3115:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   3116:   /* {0.51571254859325999, 0.4842874514067399, */
                   3117:   /*  0.51326036147820708, 0.48673963852179264} */
                   3118:   /* If we start from prlim again, prlim tends to a constant matrix */
                   3119: 
1.332     brouard  3120:   int i, ii,j,k, k1;
1.247     brouard  3121:   int first=0;
1.217     brouard  3122:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   3123:   /* double **matprod2(); */ /* test */
                   3124:   double **out, cov[NCOVMAX+1], **bmij();
                   3125:   double **newm;
1.218     brouard  3126:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   3127:   double        **oldm, **savm;  /* for use */
                   3128: 
1.217     brouard  3129:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   3130:   int ncvloop=0;
                   3131:   
                   3132:   min=vector(1,nlstate);
                   3133:   max=vector(1,nlstate);
                   3134:   meandiff=vector(1,nlstate);
                   3135: 
1.266     brouard  3136:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   3137:   oldm=oldms; savm=savms;
                   3138:   
                   3139:   /* Starting with matrix unity */
                   3140:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   3141:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  3142:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3143:     }
                   3144:   
                   3145:   cov[1]=1.;
                   3146:   
                   3147:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3148:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  3149:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  3150:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   3151:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  3152:     ncvloop++;
1.218     brouard  3153:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   3154:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  3155:     /* Covariates have to be included here again */
                   3156:     cov[2]=agefin;
1.319     brouard  3157:     if(nagesqr==1){
1.217     brouard  3158:       cov[3]= agefin*agefin;;
1.319     brouard  3159:     }
1.332     brouard  3160:     for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   3161:       if(Typevar[k1]==1){ /* A product with age */
                   3162:        cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.242     brouard  3163:       }else{
1.332     brouard  3164:        cov[2+nagesqr+k1]=precov[nres][k1];
1.242     brouard  3165:       }
1.332     brouard  3166:     }/* End of loop on model equation */
                   3167: 
                   3168: /* Old code */ 
                   3169: 
                   3170:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   3171:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   3172:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; */
                   3173:     /*   /\* 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)); *\/ */
                   3174:     /* } */
                   3175:     /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   3176:     /* /\*   /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3177:     /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3178:     /* /\*   /\\* 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])]); *\\/ *\/ */
                   3179:     /* /\* } *\/ */
                   3180:     /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3181:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3182:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3183:     /*   /\* 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]); *\/ */
                   3184:     /* } */
                   3185:     /* /\* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; *\/ */
                   3186:     /* /\* for (k=1; k<=cptcovprod;k++) /\\* Useless *\\/ *\/ */
                   3187:     /* /\*   /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\\/ *\/ */
                   3188:     /* /\*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3189:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   3190:     /*   /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age *\\/ ERROR ???*\/ */
                   3191:     /*   if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3192:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3193:     /*   } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3194:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   3195:     /*   } */
                   3196:     /*   /\* 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]); *\/ */
                   3197:     /* } */
                   3198:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   3199:     /*   /\* 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]); *\/ */
                   3200:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3201:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3202:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3203:     /*         }else{ */
                   3204:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3205:     /*         } */
                   3206:     /*   }else{ */
                   3207:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3208:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3209:     /*         }else{ */
                   3210:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3211:     /*         } */
                   3212:     /*   } */
                   3213:     /* } */
1.217     brouard  3214:     
                   3215:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3216:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3217:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   3218:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3219:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  3220:                /* ij should be linked to the correct index of cov */
                   3221:                /* age and covariate values ij are in 'cov', but we need to pass
                   3222:                 * ij for the observed prevalence at age and status and covariate
                   3223:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   3224:                 */
                   3225:     /* 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 *\/ */
                   3226:     /* 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 *\/ */
                   3227:     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  3228:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  3229:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   3230:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   3231:     /*         printf("%d newm= ",i); */
                   3232:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3233:     /*           printf("%f ",newm[i][j]); */
                   3234:     /*         } */
                   3235:     /*         printf("oldm * "); */
                   3236:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3237:     /*           printf("%f ",oldm[i][j]); */
                   3238:     /*         } */
1.268     brouard  3239:     /*         printf(" bmmij "); */
1.266     brouard  3240:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3241:     /*           printf("%f ",pmmij[i][j]); */
                   3242:     /*         } */
                   3243:     /*         printf("\n"); */
                   3244:     /*   } */
                   3245:     /* } */
1.217     brouard  3246:     savm=oldm;
                   3247:     oldm=newm;
1.266     brouard  3248: 
1.217     brouard  3249:     for(j=1; j<=nlstate; j++){
                   3250:       max[j]=0.;
                   3251:       min[j]=1.;
                   3252:     }
                   3253:     for(j=1; j<=nlstate; j++){ 
                   3254:       for(i=1;i<=nlstate;i++){
1.234     brouard  3255:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   3256:        bprlim[i][j]= newm[i][j];
                   3257:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   3258:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  3259:       }
                   3260:     }
1.218     brouard  3261:                
1.217     brouard  3262:     maxmax=0.;
                   3263:     for(i=1; i<=nlstate; i++){
1.318     brouard  3264:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column, could be nan! */
1.217     brouard  3265:       maxmax=FMAX(maxmax,meandiff[i]);
                   3266:       /* 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  3267:     } /* i loop */
1.217     brouard  3268:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  3269:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3270:     if(maxmax < ftolpl){
1.220     brouard  3271:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3272:       free_vector(min,1,nlstate);
                   3273:       free_vector(max,1,nlstate);
                   3274:       free_vector(meandiff,1,nlstate);
                   3275:       return bprlim;
                   3276:     }
1.288     brouard  3277:   } /* agefin loop */
1.217     brouard  3278:     /* After some age loop it doesn't converge */
1.288     brouard  3279:   if(!first){
1.247     brouard  3280:     first=1;
                   3281:     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\
                   3282: 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);
                   3283:   }
                   3284:   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  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:   /* 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); */
                   3287:   free_vector(min,1,nlstate);
                   3288:   free_vector(max,1,nlstate);
                   3289:   free_vector(meandiff,1,nlstate);
                   3290:   
                   3291:   return bprlim; /* should not reach here */
                   3292: }
                   3293: 
1.126     brouard  3294: /*************** transition probabilities ***************/ 
                   3295: 
                   3296: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   3297: {
1.138     brouard  3298:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  3299:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  3300:      model to the ncovmodel covariates (including constant and age).
                   3301:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3302:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3303:      ncth covariate in the global vector x is given by the formula:
                   3304:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3305:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3306:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3307:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  3308:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  3309:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  3310:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  3311:   */
                   3312:   double s1, lnpijopii;
1.126     brouard  3313:   /*double t34;*/
1.164     brouard  3314:   int i,j, nc, ii, jj;
1.126     brouard  3315: 
1.223     brouard  3316:   for(i=1; i<= nlstate; i++){
                   3317:     for(j=1; j<i;j++){
                   3318:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3319:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3320:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3321:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3322:       }
                   3323:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3324:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3325:     }
                   3326:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3327:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3328:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3329:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3330:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3331:       }
                   3332:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3333:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3334:     }
                   3335:   }
1.218     brouard  3336:   
1.223     brouard  3337:   for(i=1; i<= nlstate; i++){
                   3338:     s1=0;
                   3339:     for(j=1; j<i; j++){
1.339     brouard  3340:       /* printf("debug1 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  3341:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3342:     }
                   3343:     for(j=i+1; j<=nlstate+ndeath; j++){
1.339     brouard  3344:       /* printf("debug2 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  3345:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3346:     }
                   3347:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3348:     ps[i][i]=1./(s1+1.);
                   3349:     /* Computing other pijs */
                   3350:     for(j=1; j<i; j++)
1.325     brouard  3351:       ps[i][j]= exp(ps[i][j])*ps[i][i];/* Bug valgrind */
1.223     brouard  3352:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3353:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3354:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3355:   } /* end i */
1.218     brouard  3356:   
1.223     brouard  3357:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3358:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3359:       ps[ii][jj]=0;
                   3360:       ps[ii][ii]=1;
                   3361:     }
                   3362:   }
1.294     brouard  3363: 
                   3364: 
1.223     brouard  3365:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3366:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3367:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3368:   /*   } */
                   3369:   /*   printf("\n "); */
                   3370:   /* } */
                   3371:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3372:   /*
                   3373:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  3374:                goto end;*/
1.266     brouard  3375:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  3376: }
                   3377: 
1.218     brouard  3378: /*************** backward transition probabilities ***************/ 
                   3379: 
                   3380:  /* 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 ) */
                   3381: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   3382:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   3383: {
1.302     brouard  3384:   /* 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  3385:    * 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  3386:    */
1.218     brouard  3387:   int i, ii, j,k;
1.222     brouard  3388:   
                   3389:   double **out, **pmij();
                   3390:   double sumnew=0.;
1.218     brouard  3391:   double agefin;
1.292     brouard  3392:   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  3393:   double **dnewm, **dsavm, **doldm;
                   3394:   double **bbmij;
                   3395:   
1.218     brouard  3396:   doldm=ddoldms; /* global pointers */
1.222     brouard  3397:   dnewm=ddnewms;
                   3398:   dsavm=ddsavms;
1.318     brouard  3399: 
                   3400:   /* Debug */
                   3401:   /* printf("Bmij ij=%d, cov[2}=%f\n", ij, cov[2]); */
1.222     brouard  3402:   agefin=cov[2];
1.268     brouard  3403:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  3404:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  3405:      the observed prevalence (with this covariate ij) at beginning of transition */
                   3406:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  3407: 
                   3408:   /* P_x */
1.325     brouard  3409:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm *//* Bug valgrind */
1.268     brouard  3410:   /* outputs pmmij which is a stochastic matrix in row */
                   3411: 
                   3412:   /* Diag(w_x) */
1.292     brouard  3413:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  3414:   sumnew=0.;
1.269     brouard  3415:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  3416:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  3417:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  3418:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   3419:   }
                   3420:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   3421:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3422:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  3423:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  3424:     }
                   3425:   }else{
                   3426:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3427:       for (j=1;j<=nlstate+ndeath;j++)
                   3428:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   3429:     }
                   3430:     /* if(sumnew <0.9){ */
                   3431:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   3432:     /* } */
                   3433:   }
                   3434:   k3=0.0;  /* We put the last diagonal to 0 */
                   3435:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   3436:       doldm[ii][ii]= k3;
                   3437:   }
                   3438:   /* End doldm, At the end doldm is diag[(w_i)] */
                   3439:   
1.292     brouard  3440:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   3441:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  3442: 
1.292     brouard  3443:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  3444:   /* 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  3445:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  3446:     sumnew=0.;
1.222     brouard  3447:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  3448:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  3449:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  3450:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  3451:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  3452:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  3453:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3454:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  3455:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3456:        /* }else */
1.268     brouard  3457:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   3458:     } /*End ii */
                   3459:   } /* 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 */
                   3460: 
1.292     brouard  3461:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  3462:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  3463:   /* end bmij */
1.266     brouard  3464:   return ps; /*pointer is unchanged */
1.218     brouard  3465: }
1.217     brouard  3466: /*************** transition probabilities ***************/ 
                   3467: 
1.218     brouard  3468: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  3469: {
                   3470:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3471:      computes the probability to be observed in state j being in state i by appying the
                   3472:      model to the ncovmodel covariates (including constant and age).
                   3473:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3474:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3475:      ncth covariate in the global vector x is given by the formula:
                   3476:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3477:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3478:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3479:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3480:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   3481:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3482:   */
                   3483:   double s1, lnpijopii;
                   3484:   /*double t34;*/
                   3485:   int i,j, nc, ii, jj;
                   3486: 
1.234     brouard  3487:   for(i=1; i<= nlstate; i++){
                   3488:     for(j=1; j<i;j++){
                   3489:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3490:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3491:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3492:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3493:       }
                   3494:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3495:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3496:     }
                   3497:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3498:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3499:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3500:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3501:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3502:       }
                   3503:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3504:     }
                   3505:   }
                   3506:   
                   3507:   for(i=1; i<= nlstate; i++){
                   3508:     s1=0;
                   3509:     for(j=1; j<i; j++){
                   3510:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3511:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3512:     }
                   3513:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3514:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3515:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3516:     }
                   3517:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3518:     ps[i][i]=1./(s1+1.);
                   3519:     /* Computing other pijs */
                   3520:     for(j=1; j<i; j++)
                   3521:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3522:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3523:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3524:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3525:   } /* end i */
                   3526:   
                   3527:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3528:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3529:       ps[ii][jj]=0;
                   3530:       ps[ii][ii]=1;
                   3531:     }
                   3532:   }
1.296     brouard  3533:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  3534:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3535:     s1=0.;
                   3536:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   3537:       s1+=ps[ii][jj];
                   3538:     }
                   3539:     for(ii=1; ii<= nlstate; ii++){
                   3540:       ps[ii][jj]=ps[ii][jj]/s1;
                   3541:     }
                   3542:   }
                   3543:   /* Transposition */
                   3544:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3545:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   3546:       s1=ps[ii][jj];
                   3547:       ps[ii][jj]=ps[jj][ii];
                   3548:       ps[jj][ii]=s1;
                   3549:     }
                   3550:   }
                   3551:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3552:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3553:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3554:   /*   } */
                   3555:   /*   printf("\n "); */
                   3556:   /* } */
                   3557:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3558:   /*
                   3559:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3560:     goto end;*/
                   3561:   return ps;
1.217     brouard  3562: }
                   3563: 
                   3564: 
1.126     brouard  3565: /**************** Product of 2 matrices ******************/
                   3566: 
1.145     brouard  3567: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  3568: {
                   3569:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3570:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3571:   /* in, b, out are matrice of pointers which should have been initialized 
                   3572:      before: only the contents of out is modified. The function returns
                   3573:      a pointer to pointers identical to out */
1.145     brouard  3574:   int i, j, k;
1.126     brouard  3575:   for(i=nrl; i<= nrh; i++)
1.145     brouard  3576:     for(k=ncolol; k<=ncoloh; k++){
                   3577:       out[i][k]=0.;
                   3578:       for(j=ncl; j<=nch; j++)
                   3579:        out[i][k] +=in[i][j]*b[j][k];
                   3580:     }
1.126     brouard  3581:   return out;
                   3582: }
                   3583: 
                   3584: 
                   3585: /************* Higher Matrix Product ***************/
                   3586: 
1.235     brouard  3587: 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  3588: {
1.336     brouard  3589:   /* Already optimized with precov.
                   3590:      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  3591:      'nhstepm*hstepm*stepm' months (i.e. until
                   3592:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3593:      nhstepm*hstepm matrices. 
                   3594:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3595:      (typically every 2 years instead of every month which is too big 
                   3596:      for the memory).
                   3597:      Model is determined by parameters x and covariates have to be 
                   3598:      included manually here. 
                   3599: 
                   3600:      */
                   3601: 
1.330     brouard  3602:   int i, j, d, h, k, k1;
1.131     brouard  3603:   double **out, cov[NCOVMAX+1];
1.126     brouard  3604:   double **newm;
1.187     brouard  3605:   double agexact;
1.214     brouard  3606:   double agebegin, ageend;
1.126     brouard  3607: 
                   3608:   /* Hstepm could be zero and should return the unit matrix */
                   3609:   for (i=1;i<=nlstate+ndeath;i++)
                   3610:     for (j=1;j<=nlstate+ndeath;j++){
                   3611:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3612:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3613:     }
                   3614:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3615:   for(h=1; h <=nhstepm; h++){
                   3616:     for(d=1; d <=hstepm; d++){
                   3617:       newm=savm;
                   3618:       /* Covariates have to be included here again */
                   3619:       cov[1]=1.;
1.214     brouard  3620:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3621:       cov[2]=agexact;
1.319     brouard  3622:       if(nagesqr==1){
1.227     brouard  3623:        cov[3]= agexact*agexact;
1.319     brouard  3624:       }
1.330     brouard  3625:       /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   3626:       /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   3627:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.332     brouard  3628:        if(Typevar[k1]==1){ /* A product with age */
                   3629:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   3630:        }else{
                   3631:          cov[2+nagesqr+k1]=precov[nres][k1];
                   3632:        }
                   3633:       }/* End of loop on model equation */
                   3634:        /* Old code */ 
                   3635: /*     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /\* Single dummy  *\/ */
                   3636: /* /\*    V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) *\/ */
                   3637: /* /\*       for (k=1; k<=nsd;k++) { /\\* For single dummy covariates only *\\/ *\/ */
                   3638: /* /\* /\\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\\/ *\/ */
                   3639: /*     /\* codtabm(ij,k)  (1 & (ij-1) >> (k-1))+1 *\/ */
                   3640: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3641: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3642: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
                   3643: /* /\*    nsd         1   2                              3 *\/ /\* Counting single dummies covar fixed or tv *\/ */
                   3644: /* /\*TvarsD[nsd]     4   3                              1 *\/ /\* ID of single dummy cova fixed or timevary*\/ */
                   3645: /* /\*TvarsDind[k]    2   3                              9 *\/ /\* position K of single dummy cova *\/ */
                   3646: /*       /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];or [codtabm(ij,TnsdVar[TvarsD[k]] *\/ */
                   3647: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]]; */
                   3648: /*       /\* 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]])); *\/ */
                   3649: /*       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); */
                   3650: /*       printf("hpxij new Dummy precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3651: /*     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /\* Single quantitative variables  *\/ */
                   3652: /*       /\* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline *\/ */
                   3653: /*       cov[2+nagesqr+k1]=Tqresult[nres][resultmodel[nres][k1]];  */
                   3654: /*       /\* for (k=1; k<=nsq;k++) { /\\* For single varying covariates only *\\/ *\/ */
                   3655: /*       /\*   /\\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\\/ *\/ */
                   3656: /*       /\*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   3657: /*       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]]); */
                   3658: /*       printf("hpxij new Quanti precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3659: /*     }else if( Dummy[k1]==2 ){ /\* For dummy with age product *\/ */
                   3660: /*       /\* Tvar[k1] Variable in the age product age*V1 is 1 *\/ */
                   3661: /*       /\* [Tinvresult[nres][V1] is its value in the resultline nres *\/ */
                   3662: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvar[k1]]*cov[2]; */
                   3663: /*       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]); */
                   3664: /*       printf("hpxij new Dummy with age product precov[nres=%d][k1=%d]=%.4f * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3665: 
                   3666: /*       /\* cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];    *\/ */
                   3667: /*       /\* for (k=1; k<=cptcovage;k++){ /\\* For product with age V1+V1*age +V4 +age*V3 *\\/ *\/ */
                   3668: /*       /\* 1+2 Tage[1]=2 TVar[2]=1 Dummy[2]=2, Tage[2]=4 TVar[4]=3 Dummy[4]=3 quant*\/ */
                   3669: /*       /\* *\/ */
1.330     brouard  3670: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3671: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3672: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
1.332     brouard  3673: /* /\*cptcovage=2                   1               2      *\/ */
                   3674: /* /\*Tage[k]=                      5               8      *\/  */
                   3675: /*     }else if( Dummy[k1]==3 ){ /\* For quant with age product *\/ */
                   3676: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];        */
                   3677: /*       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]]); */
                   3678: /*       printf("hpxij new Quanti with age product precov[nres=%d][k1=%d] * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3679: /*       /\* if(Dummy[Tage[k]]== 2){ /\\* dummy with age *\\/ *\/ */
                   3680: /*       /\* /\\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\\* dummy with age *\\\/ *\\/ *\/ */
                   3681: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\\/ *\/ */
                   3682: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\\/ *\/ */
                   3683: /*       /\*   cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\/ */
                   3684: /*       /\*   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); *\/ */
                   3685: /*       /\* } else if(Dummy[Tage[k]]== 3){ /\\* quantitative with age *\\/ *\/ */
                   3686: /*       /\*   cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; *\/ */
                   3687: /*       /\* } *\/ */
                   3688: /*       /\* 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]); *\/ */
                   3689: /*     }else if(Typevar[k1]==2 ){ /\* For product (not with age) *\/ */
                   3690: /* /\*       for (k=1; k<=cptcovprod;k++){ /\\*  For product without age *\\/ *\/ */
                   3691: /* /\* /\\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\\/ *\/ */
                   3692: /* /\* /\\*    k        1  2   3   4     5    6    7     8    9 *\\/ *\/ */
                   3693: /* /\* /\\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\\/ *\/ */
                   3694: /* /\* /\\*cptcovprod=1            1               2            *\\/ *\/ */
                   3695: /* /\* /\\*Tprod[]=                4               7            *\\/ *\/ */
                   3696: /* /\* /\\*Tvard[][1]             4               1             *\\/ *\/ */
                   3697: /* /\* /\\*Tvard[][2]               3               2           *\\/ *\/ */
1.330     brouard  3698:          
1.332     brouard  3699: /*       /\* 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])]); *\/ */
                   3700: /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3701: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];     */
                   3702: /*       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]]); */
                   3703: /*       printf("hpxij new Product no age product precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3704: 
                   3705: /*       /\* if(Dummy[Tvardk[k1][1]]==0){ *\/ */
                   3706: /*       /\*   if(Dummy[Tvardk[k1][2]]==0){ /\\* Product of dummies *\\/ *\/ */
                   3707: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3708: /*           /\* cov[2+nagesqr+k1]=Tinvresult[nres][Tvardk[k1][1]] * Tinvresult[nres][Tvardk[k1][2]];   *\/ */
                   3709: /*           /\* 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]])]; *\/ */
                   3710: /*         /\* }else{ /\\* Product of dummy by quantitative *\\/ *\/ */
                   3711: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,TnsdVar[Tvard[k][1]])] * Tqresult[nres][k]; *\/ */
                   3712: /*           /\* cov[2+nagesqr+k1]=Tresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]; *\/ */
                   3713: /*       /\*   } *\/ */
                   3714: /*       /\* }else{ /\\* Product of quantitative by...*\\/ *\/ */
                   3715: /*       /\*   if(Dummy[Tvard[k][2]]==0){  /\\* quant by dummy *\\/ *\/ */
                   3716: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][Tvard[k][1]]; *\\/ *\/ */
                   3717: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3718: /*       /\*   }else{ /\\* Product of two quant *\\/ *\/ */
                   3719: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\\/ *\/ */
                   3720: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3721: /*       /\*   } *\/ */
                   3722: /*       /\* }/\\*end of products quantitative *\\/ *\/ */
                   3723: /*     }/\*end of products *\/ */
                   3724:       /* } /\* End of loop on model equation *\/ */
1.235     brouard  3725:       /* for (k=1; k<=cptcovn;k++)  */
                   3726:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3727:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3728:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3729:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3730:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3731:       
                   3732:       
1.126     brouard  3733:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3734:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.319     brouard  3735:       /* right multiplication of oldm by the current matrix */
1.126     brouard  3736:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3737:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3738:       /* if((int)age == 70){ */
                   3739:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3740:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3741:       /*         printf("%d pmmij ",i); */
                   3742:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3743:       /*           printf("%f ",pmmij[i][j]); */
                   3744:       /*         } */
                   3745:       /*         printf(" oldm "); */
                   3746:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3747:       /*           printf("%f ",oldm[i][j]); */
                   3748:       /*         } */
                   3749:       /*         printf("\n"); */
                   3750:       /*       } */
                   3751:       /* } */
1.126     brouard  3752:       savm=oldm;
                   3753:       oldm=newm;
                   3754:     }
                   3755:     for(i=1; i<=nlstate+ndeath; i++)
                   3756:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  3757:        po[i][j][h]=newm[i][j];
                   3758:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3759:       }
1.128     brouard  3760:     /*printf("h=%d ",h);*/
1.126     brouard  3761:   } /* end h */
1.267     brouard  3762:   /*     printf("\n H=%d \n",h); */
1.126     brouard  3763:   return po;
                   3764: }
                   3765: 
1.217     brouard  3766: /************* Higher Back Matrix Product ***************/
1.218     brouard  3767: /* 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  3768: 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  3769: {
1.332     brouard  3770:   /* For dummy covariates given in each resultline (for historical, computes the corresponding combination ij),
                   3771:      computes the transition matrix starting at age 'age' over
1.217     brouard  3772:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3773:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3774:      nhstepm*hstepm matrices.
                   3775:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3776:      (typically every 2 years instead of every month which is too big
1.217     brouard  3777:      for the memory).
1.218     brouard  3778:      Model is determined by parameters x and covariates have to be
1.266     brouard  3779:      included manually here. Then we use a call to bmij(x and cov)
                   3780:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  3781:   */
1.217     brouard  3782: 
1.332     brouard  3783:   int i, j, d, h, k, k1;
1.266     brouard  3784:   double **out, cov[NCOVMAX+1], **bmij();
                   3785:   double **newm, ***newmm;
1.217     brouard  3786:   double agexact;
                   3787:   double agebegin, ageend;
1.222     brouard  3788:   double **oldm, **savm;
1.217     brouard  3789: 
1.266     brouard  3790:   newmm=po; /* To be saved */
                   3791:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  3792:   /* Hstepm could be zero and should return the unit matrix */
                   3793:   for (i=1;i<=nlstate+ndeath;i++)
                   3794:     for (j=1;j<=nlstate+ndeath;j++){
                   3795:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3796:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3797:     }
                   3798:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3799:   for(h=1; h <=nhstepm; h++){
                   3800:     for(d=1; d <=hstepm; d++){
                   3801:       newm=savm;
                   3802:       /* Covariates have to be included here again */
                   3803:       cov[1]=1.;
1.271     brouard  3804:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  3805:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
1.318     brouard  3806:         /* Debug */
                   3807:       /* printf("hBxij age=%lf, agexact=%lf\n", age, agexact); */
1.217     brouard  3808:       cov[2]=agexact;
1.332     brouard  3809:       if(nagesqr==1){
1.222     brouard  3810:        cov[3]= agexact*agexact;
1.332     brouard  3811:       }
                   3812:       /** New code */
                   3813:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   3814:        if(Typevar[k1]==1){ /* A product with age */
                   3815:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.325     brouard  3816:        }else{
1.332     brouard  3817:          cov[2+nagesqr+k1]=precov[nres][k1];
1.325     brouard  3818:        }
1.332     brouard  3819:       }/* End of loop on model equation */
                   3820:       /** End of new code */
                   3821:   /** This was old code */
                   3822:       /* for (k=1; k<=nsd;k++){ /\* For single dummy covariates only *\//\* cptcovn error *\/ */
                   3823:       /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3824:       /* /\* /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3825:       /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])];/\* Bug valgrind *\/ */
                   3826:       /*   /\* 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)); *\/ */
                   3827:       /* } */
                   3828:       /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3829:       /*       /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3830:       /*       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3831:       /*       /\* 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]); *\/ */
                   3832:       /* } */
                   3833:       /* for (k=1; k<=cptcovage;k++){ /\* Should start at cptcovn+1 *\//\* For product with age *\/ */
                   3834:       /*       /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age error!!!*\\/ *\/ */
                   3835:       /*       if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3836:       /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3837:       /*       } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3838:       /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];  */
                   3839:       /*       } */
                   3840:       /*       /\* 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]); *\/ */
                   3841:       /* } */
                   3842:       /* for (k=1; k<=cptcovprod;k++){ /\* Useless because included in cptcovn *\/ */
                   3843:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3844:       /*       if(Dummy[Tvard[k][1]]==0){ */
                   3845:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3846:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][1])]; */
                   3847:       /*         }else{ */
                   3848:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3849:       /*         } */
                   3850:       /*       }else{ */
                   3851:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3852:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3853:       /*         }else{ */
                   3854:       /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3855:       /*         } */
                   3856:       /*       } */
                   3857:       /* }                      */
                   3858:       /* /\*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*\/ */
                   3859:       /* /\*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*\/ */
                   3860: /** End of old code */
                   3861:       
1.218     brouard  3862:       /* Careful transposed matrix */
1.266     brouard  3863:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  3864:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3865:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3866:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.325     brouard  3867:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);/* Bug valgrind */
1.217     brouard  3868:       /* if((int)age == 70){ */
                   3869:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3870:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3871:       /*         printf("%d pmmij ",i); */
                   3872:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3873:       /*           printf("%f ",pmmij[i][j]); */
                   3874:       /*         } */
                   3875:       /*         printf(" oldm "); */
                   3876:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3877:       /*           printf("%f ",oldm[i][j]); */
                   3878:       /*         } */
                   3879:       /*         printf("\n"); */
                   3880:       /*       } */
                   3881:       /* } */
                   3882:       savm=oldm;
                   3883:       oldm=newm;
                   3884:     }
                   3885:     for(i=1; i<=nlstate+ndeath; i++)
                   3886:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3887:        po[i][j][h]=newm[i][j];
1.268     brouard  3888:        /* if(h==nhstepm) */
                   3889:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  3890:       }
1.268     brouard  3891:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  3892:   } /* end h */
1.268     brouard  3893:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  3894:   return po;
                   3895: }
                   3896: 
                   3897: 
1.162     brouard  3898: #ifdef NLOPT
                   3899:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3900:   double fret;
                   3901:   double *xt;
                   3902:   int j;
                   3903:   myfunc_data *d2 = (myfunc_data *) pd;
                   3904: /* xt = (p1-1); */
                   3905:   xt=vector(1,n); 
                   3906:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3907: 
                   3908:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3909:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3910:   printf("Function = %.12lf ",fret);
                   3911:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3912:   printf("\n");
                   3913:  free_vector(xt,1,n);
                   3914:   return fret;
                   3915: }
                   3916: #endif
1.126     brouard  3917: 
                   3918: /*************** log-likelihood *************/
                   3919: double func( double *x)
                   3920: {
1.336     brouard  3921:   int i, ii, j, k, mi, d, kk, kf=0;
1.226     brouard  3922:   int ioffset=0;
1.339     brouard  3923:   int ipos=0,iposold=0,ncovv=0;
                   3924: 
1.340     brouard  3925:   double cotvarv, cotvarvold;
1.226     brouard  3926:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3927:   double **out;
                   3928:   double lli; /* Individual log likelihood */
                   3929:   int s1, s2;
1.228     brouard  3930:   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  3931: 
1.226     brouard  3932:   double bbh, survp;
                   3933:   double agexact;
1.336     brouard  3934:   double agebegin, ageend;
1.226     brouard  3935:   /*extern weight */
                   3936:   /* We are differentiating ll according to initial status */
                   3937:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3938:   /*for(i=1;i<imx;i++) 
                   3939:     printf(" %d\n",s[4][i]);
                   3940:   */
1.162     brouard  3941: 
1.226     brouard  3942:   ++countcallfunc;
1.162     brouard  3943: 
1.226     brouard  3944:   cov[1]=1.;
1.126     brouard  3945: 
1.226     brouard  3946:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3947:   ioffset=0;
1.226     brouard  3948:   if(mle==1){
                   3949:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3950:       /* Computes the values of the ncovmodel covariates of the model
                   3951:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3952:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   3953:         to be observed in j being in i according to the model.
                   3954:       */
1.243     brouard  3955:       ioffset=2+nagesqr ;
1.233     brouard  3956:    /* Fixed */
1.345     brouard  3957:       for (kf=1; kf<=ncovf;kf++){ /* For each fixed covariate dummy or quant or prod */
1.319     brouard  3958:        /* # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi */
                   3959:         /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   3960:        /*  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  3961:         /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.336     brouard  3962:        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  3963:        /* V1*V2 (7)  TvarFind[2]=7, TvarFind[3]=9 */
1.234     brouard  3964:       }
1.226     brouard  3965:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.319     brouard  3966:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
1.226     brouard  3967:         has been calculated etc */
                   3968:       /* For an individual i, wav[i] gives the number of effective waves */
                   3969:       /* We compute the contribution to Likelihood of each effective transition
                   3970:         mw[mi][i] is real wave of the mi th effectve wave */
                   3971:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   3972:         s2=s[mw[mi+1][i]][i];
1.341     brouard  3973:         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  3974:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   3975:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   3976:       */
1.336     brouard  3977:       for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
                   3978:       /* Wave varying (but not age varying) */
1.339     brouard  3979:        /* 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*\/ */
                   3980:        /*   /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; but where is the crossproduct? *\/ */
                   3981:        /*   cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   3982:        /* } */
1.340     brouard  3983:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age )*/
                   3984:          itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   3985:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
1.345     brouard  3986:          if(FixedV[itv]!=0){ /* Not a fixed covariate */
1.341     brouard  3987:            cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* cotvar[wav][ncovcol+nqv+iv][i] */
1.340     brouard  3988:          }else{ /* fixed covariate */
1.345     brouard  3989:            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  3990:          }
1.339     brouard  3991:          if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  3992:            cotvarvold=cotvarv;
                   3993:          }else{ /* A second product */
                   3994:            cotvarv=cotvarv*cotvarvold;
1.339     brouard  3995:          }
                   3996:          iposold=ipos;
1.340     brouard  3997:          cov[ioffset+ipos]=cotvarv;
1.234     brouard  3998:        }
1.339     brouard  3999:        /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
                   4000:        /*   iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4001:        /*   cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
                   4002:        /*   k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
                   4003:        /*   cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
                   4004:        /*   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]); */
                   4005:        /* } */
                   4006:        /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
                   4007:        /*   iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4008:        /*   /\* 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]); *\/ */
                   4009:        /*   cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
                   4010:        /* } */
                   4011:        /* for products of time varying to be done */
1.234     brouard  4012:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4013:          for (j=1;j<=nlstate+ndeath;j++){
                   4014:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4015:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4016:          }
1.336     brouard  4017: 
                   4018:        agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4019:        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  4020:        for(d=0; d<dh[mi][i]; d++){
                   4021:          newm=savm;
                   4022:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4023:          cov[2]=agexact;
                   4024:          if(nagesqr==1)
                   4025:            cov[3]= agexact*agexact;  /* Should be changed here */
                   4026:          for (kk=1; kk<=cptcovage;kk++) {
1.318     brouard  4027:            if(!FixedV[Tvar[Tage[kk]]])
                   4028:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4029:            else
1.341     brouard  4030:              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  4031:          }
                   4032:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4033:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4034:          savm=oldm;
                   4035:          oldm=newm;
                   4036:        } /* end mult */
                   4037:        
                   4038:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   4039:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   4040:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   4041:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   4042:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   4043:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   4044:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   4045:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  4046:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   4047:                                 * -stepm/2 to stepm/2 .
                   4048:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   4049:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   4050:                                 */
1.234     brouard  4051:        s1=s[mw[mi][i]][i];
                   4052:        s2=s[mw[mi+1][i]][i];
                   4053:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4054:        /* bias bh is positive if real duration
                   4055:         * is higher than the multiple of stepm and negative otherwise.
                   4056:         */
                   4057:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   4058:        if( s2 > nlstate){ 
                   4059:          /* i.e. if s2 is a death state and if the date of death is known 
                   4060:             then the contribution to the likelihood is the probability to 
                   4061:             die between last step unit time and current  step unit time, 
                   4062:             which is also equal to probability to die before dh 
                   4063:             minus probability to die before dh-stepm . 
                   4064:             In version up to 0.92 likelihood was computed
                   4065:             as if date of death was unknown. Death was treated as any other
                   4066:             health state: the date of the interview describes the actual state
                   4067:             and not the date of a change in health state. The former idea was
                   4068:             to consider that at each interview the state was recorded
                   4069:             (healthy, disable or death) and IMaCh was corrected; but when we
                   4070:             introduced the exact date of death then we should have modified
                   4071:             the contribution of an exact death to the likelihood. This new
                   4072:             contribution is smaller and very dependent of the step unit
                   4073:             stepm. It is no more the probability to die between last interview
                   4074:             and month of death but the probability to survive from last
                   4075:             interview up to one month before death multiplied by the
                   4076:             probability to die within a month. Thanks to Chris
                   4077:             Jackson for correcting this bug.  Former versions increased
                   4078:             mortality artificially. The bad side is that we add another loop
                   4079:             which slows down the processing. The difference can be up to 10%
                   4080:             lower mortality.
                   4081:          */
                   4082:          /* If, at the beginning of the maximization mostly, the
                   4083:             cumulative probability or probability to be dead is
                   4084:             constant (ie = 1) over time d, the difference is equal to
                   4085:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   4086:             s1 at precedent wave, to be dead a month before current
                   4087:             wave is equal to probability, being at state s1 at
                   4088:             precedent wave, to be dead at mont of the current
                   4089:             wave. Then the observed probability (that this person died)
                   4090:             is null according to current estimated parameter. In fact,
                   4091:             it should be very low but not zero otherwise the log go to
                   4092:             infinity.
                   4093:          */
1.183     brouard  4094: /* #ifdef INFINITYORIGINAL */
                   4095: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4096: /* #else */
                   4097: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   4098: /*         lli=log(mytinydouble); */
                   4099: /*       else */
                   4100: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4101: /* #endif */
1.226     brouard  4102:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4103:          
1.226     brouard  4104:        } else if  ( s2==-1 ) { /* alive */
                   4105:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4106:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4107:          /*survp += out[s1][j]; */
                   4108:          lli= log(survp);
                   4109:        }
1.336     brouard  4110:        /* else if  (s2==-4) {  */
                   4111:        /*   for (j=3,survp=0. ; j<=nlstate; j++)   */
                   4112:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4113:        /*   lli= log(survp);  */
                   4114:        /* }  */
                   4115:        /* else if  (s2==-5) {  */
                   4116:        /*   for (j=1,survp=0. ; j<=2; j++)   */
                   4117:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4118:        /*   lli= log(survp);  */
                   4119:        /* }  */
1.226     brouard  4120:        else{
                   4121:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4122:          /*  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 */
                   4123:        } 
                   4124:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   4125:        /*if(lli ==000.0)*/
1.340     brouard  4126:        /* 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  4127:        ipmx +=1;
                   4128:        sw += weight[i];
                   4129:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4130:        /* if (lli < log(mytinydouble)){ */
                   4131:        /*   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); */
                   4132:        /*   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]); */
                   4133:        /* } */
                   4134:       } /* end of wave */
                   4135:     } /* end of individual */
                   4136:   }  else if(mle==2){
                   4137:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.319     brouard  4138:       ioffset=2+nagesqr ;
                   4139:       for (k=1; k<=ncovf;k++)
                   4140:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];
1.226     brouard  4141:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  4142:        for(k=1; k <= ncovv ; k++){
1.341     brouard  4143:          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  4144:        }
1.226     brouard  4145:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4146:          for (j=1;j<=nlstate+ndeath;j++){
                   4147:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4148:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4149:          }
                   4150:        for(d=0; d<=dh[mi][i]; d++){
                   4151:          newm=savm;
                   4152:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4153:          cov[2]=agexact;
                   4154:          if(nagesqr==1)
                   4155:            cov[3]= agexact*agexact;
                   4156:          for (kk=1; kk<=cptcovage;kk++) {
                   4157:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4158:          }
                   4159:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4160:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4161:          savm=oldm;
                   4162:          oldm=newm;
                   4163:        } /* end mult */
                   4164:       
                   4165:        s1=s[mw[mi][i]][i];
                   4166:        s2=s[mw[mi+1][i]][i];
                   4167:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4168:        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 */
                   4169:        ipmx +=1;
                   4170:        sw += weight[i];
                   4171:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4172:       } /* end of wave */
                   4173:     } /* end of individual */
                   4174:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   4175:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4176:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4177:       for(mi=1; mi<= wav[i]-1; mi++){
                   4178:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4179:          for (j=1;j<=nlstate+ndeath;j++){
                   4180:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4181:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4182:          }
                   4183:        for(d=0; d<dh[mi][i]; d++){
                   4184:          newm=savm;
                   4185:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4186:          cov[2]=agexact;
                   4187:          if(nagesqr==1)
                   4188:            cov[3]= agexact*agexact;
                   4189:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  4190:            if(!FixedV[Tvar[Tage[kk]]])
                   4191:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4192:            else
1.341     brouard  4193:              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  4194:          }
                   4195:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4196:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4197:          savm=oldm;
                   4198:          oldm=newm;
                   4199:        } /* end mult */
                   4200:       
                   4201:        s1=s[mw[mi][i]][i];
                   4202:        s2=s[mw[mi+1][i]][i];
                   4203:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4204:        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 */
                   4205:        ipmx +=1;
                   4206:        sw += weight[i];
                   4207:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4208:       } /* end of wave */
                   4209:     } /* end of individual */
                   4210:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   4211:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4212:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4213:       for(mi=1; mi<= wav[i]-1; mi++){
                   4214:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4215:          for (j=1;j<=nlstate+ndeath;j++){
                   4216:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4217:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4218:          }
                   4219:        for(d=0; d<dh[mi][i]; d++){
                   4220:          newm=savm;
                   4221:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4222:          cov[2]=agexact;
                   4223:          if(nagesqr==1)
                   4224:            cov[3]= agexact*agexact;
                   4225:          for (kk=1; kk<=cptcovage;kk++) {
                   4226:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4227:          }
1.126     brouard  4228:        
1.226     brouard  4229:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4230:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4231:          savm=oldm;
                   4232:          oldm=newm;
                   4233:        } /* end mult */
                   4234:       
                   4235:        s1=s[mw[mi][i]][i];
                   4236:        s2=s[mw[mi+1][i]][i];
                   4237:        if( s2 > nlstate){ 
                   4238:          lli=log(out[s1][s2] - savm[s1][s2]);
                   4239:        } else if  ( s2==-1 ) { /* alive */
                   4240:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4241:            survp += out[s1][j];
                   4242:          lli= log(survp);
                   4243:        }else{
                   4244:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4245:        }
                   4246:        ipmx +=1;
                   4247:        sw += weight[i];
                   4248:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.343     brouard  4249:        /* 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  4250:       } /* end of wave */
                   4251:     } /* end of individual */
                   4252:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   4253:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4254:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4255:       for(mi=1; mi<= wav[i]-1; mi++){
                   4256:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4257:          for (j=1;j<=nlstate+ndeath;j++){
                   4258:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4259:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4260:          }
                   4261:        for(d=0; d<dh[mi][i]; d++){
                   4262:          newm=savm;
                   4263:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4264:          cov[2]=agexact;
                   4265:          if(nagesqr==1)
                   4266:            cov[3]= agexact*agexact;
                   4267:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  4268:            if(!FixedV[Tvar[Tage[kk]]])
                   4269:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4270:            else
1.341     brouard  4271:              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  4272:          }
1.126     brouard  4273:        
1.226     brouard  4274:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4275:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4276:          savm=oldm;
                   4277:          oldm=newm;
                   4278:        } /* end mult */
                   4279:       
                   4280:        s1=s[mw[mi][i]][i];
                   4281:        s2=s[mw[mi+1][i]][i];
                   4282:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4283:        ipmx +=1;
                   4284:        sw += weight[i];
                   4285:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4286:        /*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]);*/
                   4287:       } /* end of wave */
                   4288:     } /* end of individual */
                   4289:   } /* End of if */
                   4290:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   4291:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   4292:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4293:   return -l;
1.126     brouard  4294: }
                   4295: 
                   4296: /*************** log-likelihood *************/
                   4297: double funcone( double *x)
                   4298: {
1.228     brouard  4299:   /* Same as func but slower because of a lot of printf and if */
1.335     brouard  4300:   int i, ii, j, k, mi, d, kk, kf=0;
1.228     brouard  4301:   int ioffset=0;
1.339     brouard  4302:   int ipos=0,iposold=0,ncovv=0;
                   4303: 
1.340     brouard  4304:   double cotvarv, cotvarvold;
1.131     brouard  4305:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  4306:   double **out;
                   4307:   double lli; /* Individual log likelihood */
                   4308:   double llt;
                   4309:   int s1, s2;
1.228     brouard  4310:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   4311: 
1.126     brouard  4312:   double bbh, survp;
1.187     brouard  4313:   double agexact;
1.214     brouard  4314:   double agebegin, ageend;
1.126     brouard  4315:   /*extern weight */
                   4316:   /* We are differentiating ll according to initial status */
                   4317:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   4318:   /*for(i=1;i<imx;i++) 
                   4319:     printf(" %d\n",s[4][i]);
                   4320:   */
                   4321:   cov[1]=1.;
                   4322: 
                   4323:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  4324:   ioffset=0;
                   4325:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.336     brouard  4326:     /* Computes the values of the ncovmodel covariates of the model
                   4327:        depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   4328:        Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   4329:        to be observed in j being in i according to the model.
                   4330:     */
1.243     brouard  4331:     /* ioffset=2+nagesqr+cptcovage; */
                   4332:     ioffset=2+nagesqr;
1.232     brouard  4333:     /* Fixed */
1.224     brouard  4334:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  4335:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
1.335     brouard  4336:     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  4337:       /* printf("Debug3 TvarFind[%d]=%d",kf, TvarFind[kf]); */
                   4338:       /* printf(" Tvar[TvarFind[kf]]=%d", Tvar[TvarFind[kf]]); */
                   4339:       /* printf(" i=%d covar[Tvar[TvarFind[kf]]][i]=%f\n",i,covar[Tvar[TvarFind[kf]]][i]); */
1.335     brouard  4340:       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  4341: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   4342: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   4343: /*    cov[2+6]=covar[2][i]; V2  */
                   4344: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   4345: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   4346: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   4347: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   4348: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   4349: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  4350:     }
1.336     brouard  4351:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   4352:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
                   4353:         has been calculated etc */
                   4354:       /* For an individual i, wav[i] gives the number of effective waves */
                   4355:       /* We compute the contribution to Likelihood of each effective transition
                   4356:         mw[mi][i] is real wave of the mi th effectve wave */
                   4357:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   4358:         s2=s[mw[mi+1][i]][i];
1.341     brouard  4359:         And the iv th varying covariate in the DATA is the cotvar[mw[mi+1][i]][ncovcol+nqv+iv][i]
1.336     brouard  4360:       */
                   4361:     /* This part may be useless now because everythin should be in covar */
1.232     brouard  4362:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   4363:     /*   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?)*\/ */
                   4364:     /* } */
1.231     brouard  4365:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   4366:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   4367:     /* } */
1.225     brouard  4368:     
1.233     brouard  4369: 
                   4370:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.339     brouard  4371:       /* 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 */
                   4372:       /* for(k=1; k <= ncovv ; k++){ /\* Varying  covariates (single and product but no age )*\/ */
                   4373:       /*       /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; *\/ */
                   4374:       /*       cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   4375:       /* } */
                   4376:       
                   4377:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   4378:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   4379:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   4380:       /*  TvarVV[1]=V3 (first time varying in the model equation, TvarVV[2]=V1 (in V1*V3) TvarVV[3]=3(V3)  */
                   4381:       /* We need the position of the time varying or product in the model */
                   4382:       /* 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 */            
                   4383:       /* TvarVV gives the variable name */
1.340     brouard  4384:       /* Other example V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   4385:       *      k=         1   2     3     4         5        6        7       8        9
                   4386:       *  varying            1     2                                 3       4        5
                   4387:       *  ncovv              1     2                                3 4     5 6      7 8
1.343     brouard  4388:       * TvarVV[ncovv]      V3     5                                1 3     3 5      1 5
1.340     brouard  4389:       * TvarVVind           2     3                                7 7     8 8      9 9
                   4390:       * TvarFind[k]     1   0     0     0         0        0        0       0        0
                   4391:       */
1.345     brouard  4392:       /* Other model ncovcol=5 nqv=0 ntv=3 nqtv=0 nlstate=3
1.346   ! brouard  4393:        * 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  4394:        * FixedV[ncovcol+qv+ntv+nqtv]       V5
                   4395:        *             V1  V2     V3    V4   V5 V6     V7  V8
                   4396:        *             0   0      0      0    0  1      1   1 
                   4397:        * model=          V2  +  V3  +  V4  +  V6  +  V7  +  V6*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4
                   4398:        * kmodel           1     2      3      4      5        6         7         8         9        10        11
                   4399:        * ncovf            1     2      3
                   4400:        * ncovvt=14                            1      2       3 4       5 6       7 8       9 10     11 12     13 14
                   4401:        * TvarVV[1]@14 = itv                   {6,     7,     6, 2,     7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
                   4402:        * TvarVVind[1]@14=                    {4,     5,      6, 6,     7, 7,     8, 8,      9, 9,   10, 10,   11, 11}
                   4403:        * TvarFind[1]@14= {1,    2,     3,     0 <repeats 12 times>}
                   4404:        * Tvar[1]@20=     {2,    3,     4,    6,      7,      9,      10,        11,       12,      13,       14}
                   4405:        * TvarFind[itv]                        0      0       0
                   4406:        * FixedV[itv]                          1      1       1  0      1 0       1 0       1 0       0
                   4407:        * Tvar[TvarFind[ncovf]]=[1]=2 [2]=3 [4]=4
                   4408:        * Tvar[TvarFind[itv]]                [0]=?      ?ncovv 1 à ncovvt]
                   4409:        *   Not a fixed cotvar[mw][itv][i]     6       7      6  2      7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
                   4410:        *   fixed covar[itv]                  [6]     [7]    [6][2]                            
                   4411:        */
                   4412: 
1.340     brouard  4413:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age) including individual from products */
1.345     brouard  4414:        itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product  */
1.340     brouard  4415:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
1.345     brouard  4416:        /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   4417:        if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   4418:          cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
1.340     brouard  4419:        }else{ /* fixed covariate */
1.345     brouard  4420:          /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
                   4421:          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  4422:        }
1.339     brouard  4423:        if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  4424:          cotvarvold=cotvarv;
                   4425:        }else{ /* A second product */
                   4426:          cotvarv=cotvarv*cotvarvold;
1.339     brouard  4427:        }
                   4428:        iposold=ipos;
1.340     brouard  4429:        cov[ioffset+ipos]=cotvarv;
1.339     brouard  4430:        /* For products */
                   4431:       }
                   4432:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates single *\/ */
                   4433:       /*       iv=TvarVDind[itv]; /\* iv, position in the model equation of time varying covariate itv *\/ */
                   4434:       /*       /\*         "V1+V3+age*V1+age*V3+V1*V3" with V3 time varying *\/ */
                   4435:       /*       /\*           1  2   3      4      5                         *\/ */
                   4436:       /*       /\*itv           1                                           *\/ */
                   4437:       /*       /\* TvarVInd[1]= 2                                           *\/ */
                   4438:       /*       /\* iv= Tvar[Tmodelind[itv]]-ncovcol-nqv;  /\\* Counting the # varying covariate from 1 to ntveff *\\/ *\/ */
                   4439:       /*       /\* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; *\/ */
                   4440:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; *\/ */
                   4441:       /*       /\* k=ioffset-2-nagesqr-cptcovage+itv; /\\* position in simple model *\\/ *\/ */
                   4442:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; *\/ */
                   4443:       /*       cov[ioffset+iv]=cotvar[mw[mi][i]][itv][i]; */
                   4444:       /*       /\* 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]); *\/ */
                   4445:       /* } */
1.232     brouard  4446:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  4447:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4448:       /*       /\* 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]); *\/ */
                   4449:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  4450:       /* } */
1.126     brouard  4451:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  4452:        for (j=1;j<=nlstate+ndeath;j++){
                   4453:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4454:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4455:        }
1.214     brouard  4456:       
                   4457:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4458:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   4459:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  4460:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  4461:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4462:          and mw[mi+1][i]. dh depends on stepm.*/
                   4463:        newm=savm;
1.247     brouard  4464:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  4465:        cov[2]=agexact;
                   4466:        if(nagesqr==1)
                   4467:          cov[3]= agexact*agexact;
                   4468:        for (kk=1; kk<=cptcovage;kk++) {
                   4469:          if(!FixedV[Tvar[Tage[kk]]])
                   4470:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4471:          else
1.341     brouard  4472:            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  4473:        }
                   4474:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   4475:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4476:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4477:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4478:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   4479:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   4480:        savm=oldm;
                   4481:        oldm=newm;
1.126     brouard  4482:       } /* end mult */
1.336     brouard  4483:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   4484:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   4485:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   4486:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   4487:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   4488:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   4489:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   4490:         * probability in order to take into account the bias as a fraction of the way
                   4491:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   4492:                                 * -stepm/2 to stepm/2 .
                   4493:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   4494:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   4495:                                 */
1.126     brouard  4496:       s1=s[mw[mi][i]][i];
                   4497:       s2=s[mw[mi+1][i]][i];
1.217     brouard  4498:       /* if(s2==-1){ */
1.268     brouard  4499:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  4500:       /*       /\* exit(1); *\/ */
                   4501:       /* } */
1.126     brouard  4502:       bbh=(double)bh[mi][i]/(double)stepm; 
                   4503:       /* bias is positive if real duration
                   4504:        * is higher than the multiple of stepm and negative otherwise.
                   4505:        */
                   4506:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  4507:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4508:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  4509:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   4510:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4511:        lli= log(survp);
1.126     brouard  4512:       }else if (mle==1){
1.242     brouard  4513:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  4514:       } else if(mle==2){
1.242     brouard  4515:        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  4516:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  4517:        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  4518:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  4519:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  4520:       } else{  /* mle=0 back to 1 */
1.242     brouard  4521:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4522:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  4523:       } /* End of if */
                   4524:       ipmx +=1;
                   4525:       sw += weight[i];
                   4526:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.342     brouard  4527:       /* Printing covariates values for each contribution for checking */
1.343     brouard  4528:       /* 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  4529:       if(globpr){
1.246     brouard  4530:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  4531:  %11.6f %11.6f %11.6f ", \
1.242     brouard  4532:                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  4533:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.343     brouard  4534:        /*      printf("%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\ */
                   4535:        /* %11.6f %11.6f %11.6f ", \ */
                   4536:        /*              num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw, */
                   4537:        /*              2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
1.242     brouard  4538:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   4539:          llt +=ll[k]*gipmx/gsw;
                   4540:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
1.335     brouard  4541:          /* printf(" %10.6f",-ll[k]*gipmx/gsw); */
1.242     brouard  4542:        }
1.343     brouard  4543:        fprintf(ficresilk," %10.6f ", -llt);
1.335     brouard  4544:        /* printf(" %10.6f\n", -llt); */
1.342     brouard  4545:        /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
1.343     brouard  4546:        /* fprintf(ficresilk,"%09ld ", num[i]); */ /* not necessary */
                   4547:        for (kf=1; kf<=ncovf;kf++){ /* Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
                   4548:          fprintf(ficresilk," %g",covar[Tvar[TvarFind[kf]]][i]);
                   4549:        }
                   4550:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age) including individual from products */
                   4551:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4552:          if(ipos!=iposold){ /* Not a product or first of a product */
                   4553:            fprintf(ficresilk," %g",cov[ioffset+ipos]);
                   4554:            /* printf(" %g",cov[ioffset+ipos]); */
                   4555:          }else{
                   4556:            fprintf(ficresilk,"*");
                   4557:            /* printf("*"); */
1.342     brouard  4558:          }
1.343     brouard  4559:          iposold=ipos;
                   4560:        }
                   4561:        for (kk=1; kk<=cptcovage;kk++) {
                   4562:          if(!FixedV[Tvar[Tage[kk]]]){
                   4563:            fprintf(ficresilk," %g*age",covar[Tvar[Tage[kk]]][i]);
                   4564:            /* printf(" %g*age",covar[Tvar[Tage[kk]]][i]); */
                   4565:          }else{
                   4566:            fprintf(ficresilk," %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
                   4567:            /* 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  4568:          }
1.343     brouard  4569:        }
                   4570:        /* printf("\n"); */
1.342     brouard  4571:        /* } /\*  End debugILK *\/ */
                   4572:        fprintf(ficresilk,"\n");
                   4573:       } /* End if globpr */
1.335     brouard  4574:     } /* end of wave */
                   4575:   } /* end of individual */
                   4576:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
1.232     brouard  4577: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
1.335     brouard  4578:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4579:   if(globpr==0){ /* First time we count the contributions and weights */
                   4580:     gipmx=ipmx;
                   4581:     gsw=sw;
                   4582:   }
1.343     brouard  4583:   return -l;
1.126     brouard  4584: }
                   4585: 
                   4586: 
                   4587: /*************** function likelione ***********/
1.292     brouard  4588: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  4589: {
                   4590:   /* This routine should help understanding what is done with 
                   4591:      the selection of individuals/waves and
                   4592:      to check the exact contribution to the likelihood.
                   4593:      Plotting could be done.
1.342     brouard  4594:   */
                   4595:   void pstamp(FILE *ficres);
1.343     brouard  4596:   int k, kf, kk, kvar, ncovv, iposold, ipos;
1.126     brouard  4597: 
                   4598:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  4599:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  4600:     strcat(fileresilk,fileresu);
1.126     brouard  4601:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   4602:       printf("Problem with resultfile: %s\n", fileresilk);
                   4603:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   4604:     }
1.342     brouard  4605:     pstamp(ficresilk);fprintf(ficresilk,"# model=1+age+%s\n",model);
1.214     brouard  4606:     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");
                   4607:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  4608:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   4609:     for(k=1; k<=nlstate; k++) 
                   4610:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
1.342     brouard  4611:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total) ");
                   4612: 
                   4613:     /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
                   4614:       for(kf=1;kf <= ncovf; kf++){
                   4615:        fprintf(ficresilk,"V%d",Tvar[TvarFind[kf]]);
                   4616:        /* printf("V%d",Tvar[TvarFind[kf]]); */
                   4617:       }
                   4618:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){
1.343     brouard  4619:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
1.342     brouard  4620:        if(ipos!=iposold){ /* Not a product or first of a product */
                   4621:          /* printf(" %d",ipos); */
                   4622:          fprintf(ficresilk," V%d",TvarVV[ncovv]);
                   4623:        }else{
                   4624:          /* printf("*"); */
                   4625:          fprintf(ficresilk,"*");
1.343     brouard  4626:        }
1.342     brouard  4627:        iposold=ipos;
                   4628:       }
                   4629:       for (kk=1; kk<=cptcovage;kk++) {
                   4630:        if(!FixedV[Tvar[Tage[kk]]]){
                   4631:          /* printf(" %d*age(Fixed)",Tvar[Tage[kk]]); */
                   4632:          fprintf(ficresilk," %d*age(Fixed)",Tvar[Tage[kk]]);
                   4633:        }else{
                   4634:          fprintf(ficresilk," %d*age(Varying)",Tvar[Tage[kk]]);/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
                   4635:          /* printf(" %d*age(Varying)",Tvar[Tage[kk]]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
                   4636:        }
                   4637:       }
                   4638:     /* } /\* End if debugILK *\/ */
                   4639:     /* printf("\n"); */
                   4640:     fprintf(ficresilk,"\n");
                   4641:   } /* End glogpri */
1.126     brouard  4642: 
1.292     brouard  4643:   *fretone=(*func)(p);
1.126     brouard  4644:   if(*globpri !=0){
                   4645:     fclose(ficresilk);
1.205     brouard  4646:     if (mle ==0)
                   4647:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   4648:     else if(mle >=1)
                   4649:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   4650:     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  4651:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  4652:       
1.207     brouard  4653:     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  4654: <img src=\"%s-ori.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4655:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.343     brouard  4656: <img src=\"%s-dest.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
                   4657:     
                   4658:     for (k=1; k<= nlstate ; k++) {
                   4659:       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 \
                   4660: <img src=\"%s-p%dj.png\">\n",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   4661:       for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
                   4662:        /* kvar=Tvar[TvarFind[kf]]; */ /* variable */
                   4663:        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> \
                   4664: <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]]);
                   4665:       }
                   4666:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Loop on the time varying extended covariates (with extension of Vn*Vm */
                   4667:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   4668:        kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   4669:        /* 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]); */
                   4670:        if(ipos!=iposold){ /* Not a product or first of a product */
                   4671:          /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   4672:          /* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); */
                   4673:          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)  */
                   4674:            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> \
                   4675: <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);
                   4676:          } /* End only for dummies time varying (single?) */
                   4677:        }else{ /* Useless product */
                   4678:          /* printf("*"); */
                   4679:          /* fprintf(ficresilk,"*"); */ 
                   4680:        }
                   4681:        iposold=ipos;
                   4682:       } /* For each time varying covariate */
                   4683:     } /* End loop on states */
                   4684: 
                   4685: /*     if(debugILK){ */
                   4686: /*       for(kf=1; kf <= ncovf; kf++){ /\* For each simple dummy covariate of the model *\/ */
                   4687: /*     /\* kvar=Tvar[TvarFind[kf]]; *\/ /\* variable *\/ */
                   4688: /*     for (k=1; k<= nlstate ; k++) { */
                   4689: /*       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> \ */
                   4690: /* <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]]); */
                   4691: /*     } */
                   4692: /*       } */
                   4693: /*       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /\* Loop on the time varying extended covariates (with extension of Vn*Vm *\/ */
                   4694: /*     ipos=TvarVVind[ncovv]; /\* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate *\/ */
                   4695: /*     kvar=TvarVV[ncovv]; /\*  TvarVV={3, 1, 3} gives the name of each varying covariate *\/ */
                   4696: /*     /\* 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]); *\/ */
                   4697: /*     if(ipos!=iposold){ /\* Not a product or first of a product *\/ */
                   4698: /*       /\* fprintf(ficresilk," V%d",TvarVV[ncovv]); *\/ */
                   4699: /*       /\* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); *\/ */
                   4700: /*       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)  *\/ */
                   4701: /*         for (k=1; k<= nlstate ; k++) { */
                   4702: /*           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> \ */
                   4703: /* <img src=\"%s-p%dj-%d.png\">",k,k,kvar,kvar,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,kvar); */
                   4704: /*         } /\* End state *\/ */
                   4705: /*       } /\* End only for dummies time varying (single?) *\/ */
                   4706: /*     }else{ /\* Useless product *\/ */
                   4707: /*       /\* printf("*"); *\/ */
                   4708: /*       /\* fprintf(ficresilk,"*"); *\/  */
                   4709: /*     } */
                   4710: /*     iposold=ipos; */
                   4711: /*       } /\* For each time varying covariate *\/ */
                   4712: /*     }/\* End debugILK *\/ */
1.207     brouard  4713:     fflush(fichtm);
1.343     brouard  4714:   }/* End globpri */
1.126     brouard  4715:   return;
                   4716: }
                   4717: 
                   4718: 
                   4719: /*********** Maximum Likelihood Estimation ***************/
                   4720: 
                   4721: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   4722: {
1.319     brouard  4723:   int i,j,k, jk, jkk=0, iter=0;
1.126     brouard  4724:   double **xi;
                   4725:   double fret;
                   4726:   double fretone; /* Only one call to likelihood */
                   4727:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  4728: 
                   4729: #ifdef NLOPT
                   4730:   int creturn;
                   4731:   nlopt_opt opt;
                   4732:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   4733:   double *lb;
                   4734:   double minf; /* the minimum objective value, upon return */
                   4735:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   4736:   myfunc_data dinst, *d = &dinst;
                   4737: #endif
                   4738: 
                   4739: 
1.126     brouard  4740:   xi=matrix(1,npar,1,npar);
                   4741:   for (i=1;i<=npar;i++)
                   4742:     for (j=1;j<=npar;j++)
                   4743:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   4744:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  4745:   strcpy(filerespow,"POW_"); 
1.126     brouard  4746:   strcat(filerespow,fileres);
                   4747:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   4748:     printf("Problem with resultfile: %s\n", filerespow);
                   4749:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   4750:   }
                   4751:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   4752:   for (i=1;i<=nlstate;i++)
                   4753:     for(j=1;j<=nlstate+ndeath;j++)
                   4754:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   4755:   fprintf(ficrespow,"\n");
1.162     brouard  4756: #ifdef POWELL
1.319     brouard  4757: #ifdef LINMINORIGINAL
                   4758: #else /* LINMINORIGINAL */
                   4759:   
                   4760:   flatdir=ivector(1,npar); 
                   4761:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   4762: #endif /*LINMINORIGINAL */
                   4763: 
                   4764: #ifdef FLATSUP
                   4765:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4766:   /* reorganizing p by suppressing flat directions */
                   4767:   for(i=1, jk=1; i <=nlstate; i++){
                   4768:     for(k=1; k <=(nlstate+ndeath); k++){
                   4769:       if (k != i) {
                   4770:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4771:         if(flatdir[jk]==1){
                   4772:           printf(" To be skipped %d%d flatdir[%d]=%d ",i,k,jk, flatdir[jk]);
                   4773:         }
                   4774:         for(j=1; j <=ncovmodel; j++){
                   4775:           printf("%12.7f ",p[jk]);
                   4776:           jk++; 
                   4777:         }
                   4778:         printf("\n");
                   4779:       }
                   4780:     }
                   4781:   }
                   4782: /* skipping */
                   4783:   /* for(i=1, jk=1, jkk=1;(flatdir[jk]==0)&& (i <=nlstate); i++){ */
                   4784:   for(i=1, jk=1, jkk=1;i <=nlstate; i++){
                   4785:     for(k=1; k <=(nlstate+ndeath); k++){
                   4786:       if (k != i) {
                   4787:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4788:         if(flatdir[jk]==1){
                   4789:           printf(" To be skipped %d%d flatdir[%d]=%d jk=%d p[%d] ",i,k,jk, flatdir[jk],jk, jk);
                   4790:           for(j=1; j <=ncovmodel;  jk++,j++){
                   4791:             printf(" p[%d]=%12.7f",jk, p[jk]);
                   4792:             /*q[jjk]=p[jk];*/
                   4793:           }
                   4794:         }else{
                   4795:           printf(" To be kept %d%d flatdir[%d]=%d jk=%d q[%d]=p[%d] ",i,k,jk, flatdir[jk],jk, jkk, jk);
                   4796:           for(j=1; j <=ncovmodel;  jk++,jkk++,j++){
                   4797:             printf(" p[%d]=%12.7f=q[%d]",jk, p[jk],jkk);
                   4798:             /*q[jjk]=p[jk];*/
                   4799:           }
                   4800:         }
                   4801:         printf("\n");
                   4802:       }
                   4803:       fflush(stdout);
                   4804:     }
                   4805:   }
                   4806:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4807: #else  /* FLATSUP */
1.126     brouard  4808:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.319     brouard  4809: #endif  /* FLATSUP */
                   4810: 
                   4811: #ifdef LINMINORIGINAL
                   4812: #else
                   4813:       free_ivector(flatdir,1,npar); 
                   4814: #endif  /* LINMINORIGINAL*/
                   4815: #endif /* POWELL */
1.126     brouard  4816: 
1.162     brouard  4817: #ifdef NLOPT
                   4818: #ifdef NEWUOA
                   4819:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   4820: #else
                   4821:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   4822: #endif
                   4823:   lb=vector(0,npar-1);
                   4824:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   4825:   nlopt_set_lower_bounds(opt, lb);
                   4826:   nlopt_set_initial_step1(opt, 0.1);
                   4827:   
                   4828:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   4829:   d->function = func;
                   4830:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   4831:   nlopt_set_min_objective(opt, myfunc, d);
                   4832:   nlopt_set_xtol_rel(opt, ftol);
                   4833:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   4834:     printf("nlopt failed! %d\n",creturn); 
                   4835:   }
                   4836:   else {
                   4837:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   4838:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   4839:     iter=1; /* not equal */
                   4840:   }
                   4841:   nlopt_destroy(opt);
                   4842: #endif
1.319     brouard  4843: #ifdef FLATSUP
                   4844:   /* npared = npar -flatd/ncovmodel; */
                   4845:   /* xired= matrix(1,npared,1,npared); */
                   4846:   /* paramred= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */
                   4847:   /* powell(pred,xired,npared,ftol,&iter,&fret,flatdir,func); */
                   4848:   /* free_matrix(xire,1,npared,1,npared); */
                   4849: #else  /* FLATSUP */
                   4850: #endif /* FLATSUP */
1.126     brouard  4851:   free_matrix(xi,1,npar,1,npar);
                   4852:   fclose(ficrespow);
1.203     brouard  4853:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   4854:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  4855:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  4856: 
                   4857: }
                   4858: 
                   4859: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  4860: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  4861: {
                   4862:   double  **a,**y,*x,pd;
1.203     brouard  4863:   /* double **hess; */
1.164     brouard  4864:   int i, j;
1.126     brouard  4865:   int *indx;
                   4866: 
                   4867:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  4868:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  4869:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   4870:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   4871:   double gompertz(double p[]);
1.203     brouard  4872:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  4873: 
                   4874:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   4875:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   4876:   for (i=1;i<=npar;i++){
1.203     brouard  4877:     printf("%d-",i);fflush(stdout);
                   4878:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  4879:    
                   4880:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   4881:     
                   4882:     /*  printf(" %f ",p[i]);
                   4883:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   4884:   }
                   4885:   
                   4886:   for (i=1;i<=npar;i++) {
                   4887:     for (j=1;j<=npar;j++)  {
                   4888:       if (j>i) { 
1.203     brouard  4889:        printf(".%d-%d",i,j);fflush(stdout);
                   4890:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   4891:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  4892:        
                   4893:        hess[j][i]=hess[i][j];    
                   4894:        /*printf(" %lf ",hess[i][j]);*/
                   4895:       }
                   4896:     }
                   4897:   }
                   4898:   printf("\n");
                   4899:   fprintf(ficlog,"\n");
                   4900: 
                   4901:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4902:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4903:   
                   4904:   a=matrix(1,npar,1,npar);
                   4905:   y=matrix(1,npar,1,npar);
                   4906:   x=vector(1,npar);
                   4907:   indx=ivector(1,npar);
                   4908:   for (i=1;i<=npar;i++)
                   4909:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   4910:   ludcmp(a,npar,indx,&pd);
                   4911: 
                   4912:   for (j=1;j<=npar;j++) {
                   4913:     for (i=1;i<=npar;i++) x[i]=0;
                   4914:     x[j]=1;
                   4915:     lubksb(a,npar,indx,x);
                   4916:     for (i=1;i<=npar;i++){ 
                   4917:       matcov[i][j]=x[i];
                   4918:     }
                   4919:   }
                   4920: 
                   4921:   printf("\n#Hessian matrix#\n");
                   4922:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   4923:   for (i=1;i<=npar;i++) { 
                   4924:     for (j=1;j<=npar;j++) { 
1.203     brouard  4925:       printf("%.6e ",hess[i][j]);
                   4926:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  4927:     }
                   4928:     printf("\n");
                   4929:     fprintf(ficlog,"\n");
                   4930:   }
                   4931: 
1.203     brouard  4932:   /* printf("\n#Covariance matrix#\n"); */
                   4933:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   4934:   /* for (i=1;i<=npar;i++) {  */
                   4935:   /*   for (j=1;j<=npar;j++) {  */
                   4936:   /*     printf("%.6e ",matcov[i][j]); */
                   4937:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   4938:   /*   } */
                   4939:   /*   printf("\n"); */
                   4940:   /*   fprintf(ficlog,"\n"); */
                   4941:   /* } */
                   4942: 
1.126     brouard  4943:   /* Recompute Inverse */
1.203     brouard  4944:   /* for (i=1;i<=npar;i++) */
                   4945:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   4946:   /* ludcmp(a,npar,indx,&pd); */
                   4947: 
                   4948:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   4949: 
                   4950:   /* for (j=1;j<=npar;j++) { */
                   4951:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   4952:   /*   x[j]=1; */
                   4953:   /*   lubksb(a,npar,indx,x); */
                   4954:   /*   for (i=1;i<=npar;i++){  */
                   4955:   /*     y[i][j]=x[i]; */
                   4956:   /*     printf("%.3e ",y[i][j]); */
                   4957:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   4958:   /*   } */
                   4959:   /*   printf("\n"); */
                   4960:   /*   fprintf(ficlog,"\n"); */
                   4961:   /* } */
                   4962: 
                   4963:   /* Verifying the inverse matrix */
                   4964: #ifdef DEBUGHESS
                   4965:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  4966: 
1.203     brouard  4967:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   4968:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  4969: 
                   4970:   for (j=1;j<=npar;j++) {
                   4971:     for (i=1;i<=npar;i++){ 
1.203     brouard  4972:       printf("%.2f ",y[i][j]);
                   4973:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  4974:     }
                   4975:     printf("\n");
                   4976:     fprintf(ficlog,"\n");
                   4977:   }
1.203     brouard  4978: #endif
1.126     brouard  4979: 
                   4980:   free_matrix(a,1,npar,1,npar);
                   4981:   free_matrix(y,1,npar,1,npar);
                   4982:   free_vector(x,1,npar);
                   4983:   free_ivector(indx,1,npar);
1.203     brouard  4984:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  4985: 
                   4986: 
                   4987: }
                   4988: 
                   4989: /*************** hessian matrix ****************/
                   4990: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  4991: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  4992:   int i;
                   4993:   int l=1, lmax=20;
1.203     brouard  4994:   double k1,k2, res, fx;
1.132     brouard  4995:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  4996:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   4997:   int k=0,kmax=10;
                   4998:   double l1;
                   4999: 
                   5000:   fx=func(x);
                   5001:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  5002:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  5003:     l1=pow(10,l);
                   5004:     delts=delt;
                   5005:     for(k=1 ; k <kmax; k=k+1){
                   5006:       delt = delta*(l1*k);
                   5007:       p2[theta]=x[theta] +delt;
1.145     brouard  5008:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  5009:       p2[theta]=x[theta]-delt;
                   5010:       k2=func(p2)-fx;
                   5011:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  5012:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  5013:       
1.203     brouard  5014: #ifdef DEBUGHESSII
1.126     brouard  5015:       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);
                   5016:       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);
                   5017: #endif
                   5018:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   5019:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   5020:        k=kmax;
                   5021:       }
                   5022:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  5023:        k=kmax; l=lmax*10;
1.126     brouard  5024:       }
                   5025:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   5026:        delts=delt;
                   5027:       }
1.203     brouard  5028:     } /* End loop k */
1.126     brouard  5029:   }
                   5030:   delti[theta]=delts;
                   5031:   return res; 
                   5032:   
                   5033: }
                   5034: 
1.203     brouard  5035: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  5036: {
                   5037:   int i;
1.164     brouard  5038:   int l=1, lmax=20;
1.126     brouard  5039:   double k1,k2,k3,k4,res,fx;
1.132     brouard  5040:   double p2[MAXPARM+1];
1.203     brouard  5041:   int k, kmax=1;
                   5042:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  5043: 
                   5044:   int firstime=0;
1.203     brouard  5045:   
1.126     brouard  5046:   fx=func(x);
1.203     brouard  5047:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  5048:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  5049:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   5050:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  5051:     k1=func(p2)-fx;
                   5052:   
1.203     brouard  5053:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   5054:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  5055:     k2=func(p2)-fx;
                   5056:   
1.203     brouard  5057:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   5058:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  5059:     k3=func(p2)-fx;
                   5060:   
1.203     brouard  5061:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   5062:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  5063:     k4=func(p2)-fx;
1.203     brouard  5064:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   5065:     if(k1*k2*k3*k4 <0.){
1.208     brouard  5066:       firstime=1;
1.203     brouard  5067:       kmax=kmax+10;
1.208     brouard  5068:     }
                   5069:     if(kmax >=10 || firstime ==1){
1.246     brouard  5070:       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);
                   5071:       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  5072:       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);
                   5073:       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);
                   5074:     }
                   5075: #ifdef DEBUGHESSIJ
                   5076:     v1=hess[thetai][thetai];
                   5077:     v2=hess[thetaj][thetaj];
                   5078:     cv12=res;
                   5079:     /* Computing eigen value of Hessian matrix */
                   5080:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5081:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5082:     if ((lc2 <0) || (lc1 <0) ){
                   5083:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   5084:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   5085:       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);
                   5086:       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);
                   5087:     }
1.126     brouard  5088: #endif
                   5089:   }
                   5090:   return res;
                   5091: }
                   5092: 
1.203     brouard  5093:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   5094: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   5095: /* { */
                   5096: /*   int i; */
                   5097: /*   int l=1, lmax=20; */
                   5098: /*   double k1,k2,k3,k4,res,fx; */
                   5099: /*   double p2[MAXPARM+1]; */
                   5100: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   5101: /*   int k=0,kmax=10; */
                   5102: /*   double l1; */
                   5103:   
                   5104: /*   fx=func(x); */
                   5105: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   5106: /*     l1=pow(10,l); */
                   5107: /*     delts=delt; */
                   5108: /*     for(k=1 ; k <kmax; k=k+1){ */
                   5109: /*       delt = delti*(l1*k); */
                   5110: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   5111: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   5112: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   5113: /*       k1=func(p2)-fx; */
                   5114:       
                   5115: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   5116: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   5117: /*       k2=func(p2)-fx; */
                   5118:       
                   5119: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   5120: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   5121: /*       k3=func(p2)-fx; */
                   5122:       
                   5123: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   5124: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   5125: /*       k4=func(p2)-fx; */
                   5126: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   5127: /* #ifdef DEBUGHESSIJ */
                   5128: /*       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); */
                   5129: /*       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); */
                   5130: /* #endif */
                   5131: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   5132: /*     k=kmax; */
                   5133: /*       } */
                   5134: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   5135: /*     k=kmax; l=lmax*10; */
                   5136: /*       } */
                   5137: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   5138: /*     delts=delt; */
                   5139: /*       } */
                   5140: /*     } /\* End loop k *\/ */
                   5141: /*   } */
                   5142: /*   delti[theta]=delts; */
                   5143: /*   return res;  */
                   5144: /* } */
                   5145: 
                   5146: 
1.126     brouard  5147: /************** Inverse of matrix **************/
                   5148: void ludcmp(double **a, int n, int *indx, double *d) 
                   5149: { 
                   5150:   int i,imax,j,k; 
                   5151:   double big,dum,sum,temp; 
                   5152:   double *vv; 
                   5153:  
                   5154:   vv=vector(1,n); 
                   5155:   *d=1.0; 
                   5156:   for (i=1;i<=n;i++) { 
                   5157:     big=0.0; 
                   5158:     for (j=1;j<=n;j++) 
                   5159:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  5160:     if (big == 0.0){
                   5161:       printf(" Singular Hessian matrix at row %d:\n",i);
                   5162:       for (j=1;j<=n;j++) {
                   5163:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   5164:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   5165:       }
                   5166:       fflush(ficlog);
                   5167:       fclose(ficlog);
                   5168:       nrerror("Singular matrix in routine ludcmp"); 
                   5169:     }
1.126     brouard  5170:     vv[i]=1.0/big; 
                   5171:   } 
                   5172:   for (j=1;j<=n;j++) { 
                   5173:     for (i=1;i<j;i++) { 
                   5174:       sum=a[i][j]; 
                   5175:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   5176:       a[i][j]=sum; 
                   5177:     } 
                   5178:     big=0.0; 
                   5179:     for (i=j;i<=n;i++) { 
                   5180:       sum=a[i][j]; 
                   5181:       for (k=1;k<j;k++) 
                   5182:        sum -= a[i][k]*a[k][j]; 
                   5183:       a[i][j]=sum; 
                   5184:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   5185:        big=dum; 
                   5186:        imax=i; 
                   5187:       } 
                   5188:     } 
                   5189:     if (j != imax) { 
                   5190:       for (k=1;k<=n;k++) { 
                   5191:        dum=a[imax][k]; 
                   5192:        a[imax][k]=a[j][k]; 
                   5193:        a[j][k]=dum; 
                   5194:       } 
                   5195:       *d = -(*d); 
                   5196:       vv[imax]=vv[j]; 
                   5197:     } 
                   5198:     indx[j]=imax; 
                   5199:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   5200:     if (j != n) { 
                   5201:       dum=1.0/(a[j][j]); 
                   5202:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   5203:     } 
                   5204:   } 
                   5205:   free_vector(vv,1,n);  /* Doesn't work */
                   5206: ;
                   5207: } 
                   5208: 
                   5209: void lubksb(double **a, int n, int *indx, double b[]) 
                   5210: { 
                   5211:   int i,ii=0,ip,j; 
                   5212:   double sum; 
                   5213:  
                   5214:   for (i=1;i<=n;i++) { 
                   5215:     ip=indx[i]; 
                   5216:     sum=b[ip]; 
                   5217:     b[ip]=b[i]; 
                   5218:     if (ii) 
                   5219:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   5220:     else if (sum) ii=i; 
                   5221:     b[i]=sum; 
                   5222:   } 
                   5223:   for (i=n;i>=1;i--) { 
                   5224:     sum=b[i]; 
                   5225:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   5226:     b[i]=sum/a[i][i]; 
                   5227:   } 
                   5228: } 
                   5229: 
                   5230: void pstamp(FILE *fichier)
                   5231: {
1.196     brouard  5232:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  5233: }
                   5234: 
1.297     brouard  5235: void date2dmy(double date,double *day, double *month, double *year){
                   5236:   double yp=0., yp1=0., yp2=0.;
                   5237:   
                   5238:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   5239:                        fractional in yp1 */
                   5240:   *year=yp;
                   5241:   yp2=modf((yp1*12),&yp);
                   5242:   *month=yp;
                   5243:   yp1=modf((yp2*30.5),&yp);
                   5244:   *day=yp;
                   5245:   if(*day==0) *day=1;
                   5246:   if(*month==0) *month=1;
                   5247: }
                   5248: 
1.253     brouard  5249: 
                   5250: 
1.126     brouard  5251: /************ Frequencies ********************/
1.251     brouard  5252: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  5253:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   5254:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  5255: {  /* Some frequencies as well as proposing some starting values */
1.332     brouard  5256:   /* Frequencies of any combination of dummy covariate used in the model equation */ 
1.265     brouard  5257:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  5258:   int iind=0, iage=0;
                   5259:   int mi; /* Effective wave */
                   5260:   int first;
                   5261:   double ***freq; /* Frequencies */
1.268     brouard  5262:   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 */
                   5263:   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  5264:   double *meanq, *stdq, *idq;
1.226     brouard  5265:   double **meanqt;
                   5266:   double *pp, **prop, *posprop, *pospropt;
                   5267:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   5268:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   5269:   double agebegin, ageend;
                   5270:     
                   5271:   pp=vector(1,nlstate);
1.251     brouard  5272:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  5273:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   5274:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   5275:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   5276:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  5277:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  5278:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  5279:   meanqt=matrix(1,lastpass,1,nqtveff);
                   5280:   strcpy(fileresp,"P_");
                   5281:   strcat(fileresp,fileresu);
                   5282:   /*strcat(fileresphtm,fileresu);*/
                   5283:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   5284:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   5285:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   5286:     exit(0);
                   5287:   }
1.240     brouard  5288:   
1.226     brouard  5289:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   5290:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   5291:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5292:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5293:     fflush(ficlog);
                   5294:     exit(70); 
                   5295:   }
                   5296:   else{
                   5297:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  5298: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  5299: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5300:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5301:   }
1.319     brouard  5302:   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  5303:   
1.226     brouard  5304:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   5305:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   5306:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5307:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5308:     fflush(ficlog);
                   5309:     exit(70); 
1.240     brouard  5310:   } else{
1.226     brouard  5311:     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  5312: ,<hr size=\"2\" color=\"#EC5E5E\"> \n                                  \
1.214     brouard  5313: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5314:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5315:   }
1.319     brouard  5316:   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  5317:   
1.253     brouard  5318:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   5319:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  5320:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  5321:   j1=0;
1.126     brouard  5322:   
1.227     brouard  5323:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
1.335     brouard  5324:   j=cptcoveff;  /* Only simple dummy covariates used in the model */
1.330     brouard  5325:   /* j=cptcovn;  /\* Only dummy covariates of the model *\/ */
1.226     brouard  5326:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  5327:   
                   5328:   
1.226     brouard  5329:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   5330:      reference=low_education V1=0,V2=0
                   5331:      med_educ                V1=1 V2=0, 
                   5332:      high_educ               V1=0 V2=1
1.330     brouard  5333:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcovn 
1.226     brouard  5334:   */
1.249     brouard  5335:   dateintsum=0;
                   5336:   k2cpt=0;
                   5337: 
1.253     brouard  5338:   if(cptcoveff == 0 )
1.265     brouard  5339:     nl=1;  /* Constant and age model only */
1.253     brouard  5340:   else
                   5341:     nl=2;
1.265     brouard  5342: 
                   5343:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   5344:   /* Loop on nj=1 or 2 if dummy covariates j!=0
1.335     brouard  5345:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
1.265     brouard  5346:    *     freq[s1][s2][iage] =0.
                   5347:    *     Loop on iind
                   5348:    *       ++freq[s1][s2][iage] weighted
                   5349:    *     end iind
                   5350:    *     if covariate and j!0
                   5351:    *       headers Variable on one line
                   5352:    *     endif cov j!=0
                   5353:    *     header of frequency table by age
                   5354:    *     Loop on age
                   5355:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   5356:    *       pos+=freq[s1][s2][iage] weighted
                   5357:    *       Loop on s1 initial state
                   5358:    *         fprintf(ficresp
                   5359:    *       end s1
                   5360:    *     end age
                   5361:    *     if j!=0 computes starting values
                   5362:    *     end compute starting values
                   5363:    *   end j1
                   5364:    * end nl 
                   5365:    */
1.253     brouard  5366:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   5367:     if(nj==1)
                   5368:       j=0;  /* First pass for the constant */
1.265     brouard  5369:     else{
1.335     brouard  5370:       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  5371:     }
1.251     brouard  5372:     first=1;
1.332     brouard  5373:     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  5374:       posproptt=0.;
1.330     brouard  5375:       /*printf("cptcovn=%d Tvaraff=%d", cptcovn,Tvaraff[1]);
1.251     brouard  5376:        scanf("%d", i);*/
                   5377:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  5378:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  5379:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  5380:            freq[i][s2][m]=0;
1.251     brouard  5381:       
                   5382:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  5383:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  5384:          prop[i][m]=0;
                   5385:        posprop[i]=0;
                   5386:        pospropt[i]=0;
                   5387:       }
1.283     brouard  5388:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  5389:         idq[z1]=0.;
                   5390:         meanq[z1]=0.;
                   5391:         stdq[z1]=0.;
1.283     brouard  5392:       }
                   5393:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  5394:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  5395:       /*         meanqt[m][z1]=0.; */
                   5396:       /*       } */
                   5397:       /* }       */
1.251     brouard  5398:       /* dateintsum=0; */
                   5399:       /* k2cpt=0; */
                   5400:       
1.265     brouard  5401:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  5402:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   5403:        bool=1;
                   5404:        if(j !=0){
                   5405:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.335     brouard  5406:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   5407:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
1.251     brouard  5408:                /* if(Tvaraff[z1] ==-20){ */
                   5409:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   5410:                /* }else  if(Tvaraff[z1] ==-10){ */
                   5411:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
1.330     brouard  5412:                /* }else  */ /* TODO TODO codtabm(j1,z1) or codtabm(j1,Tvaraff[z1]]z1)*/
1.335     brouard  5413:                /* 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); */
                   5414:                if(Tvaraff[z1]<1 || Tvaraff[z1]>=NCOVMAX)
1.338     brouard  5415:                  printf("Error Tvaraff[z1]=%d<1 or >=%d, cptcoveff=%d model=1+age+%s\n",Tvaraff[z1],NCOVMAX, cptcoveff, model);
1.332     brouard  5416:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]){ /* for combination j1 of covariates */
1.265     brouard  5417:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  5418:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
1.332     brouard  5419:                  /* 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", */
                   5420:                  /*   bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),*/
                   5421:                   /*   j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
1.251     brouard  5422:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   5423:                } /* Onlyf fixed */
                   5424:              } /* end z1 */
1.335     brouard  5425:            } /* cptcoveff > 0 */
1.251     brouard  5426:          } /* end any */
                   5427:        }/* end j==0 */
1.265     brouard  5428:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  5429:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  5430:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  5431:            m=mw[mi][iind];
                   5432:            if(j!=0){
                   5433:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
1.335     brouard  5434:                for (z1=1; z1<=cptcoveff; z1++) {
1.251     brouard  5435:                  if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  5436:                    /* iv= Tvar[Tmodelind[z1]]-ncovcol-nqv; /\* Good *\/ */
                   5437:                    iv= Tvar[Tmodelind[z1]]; /* Good *//* because cotvar starts now at first at ncovcol+nqv+ntv */ 
1.332     brouard  5438:                    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  5439:                                                                                      value is -1, we don't select. It differs from the 
                   5440:                                                                                      constant and age model which counts them. */
                   5441:                      bool=0; /* not selected */
                   5442:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
1.334     brouard  5443:                    /* i1=Tvaraff[z1]; */
                   5444:                    /* i2=TnsdVar[i1]; */
                   5445:                    /* i3=nbcode[i1][i2]; */
                   5446:                    /* i4=covar[i1][iind]; */
                   5447:                    /* if(i4 != i3){ */
                   5448:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) { /* Bug valgrind */
1.251     brouard  5449:                      bool=0;
                   5450:                    }
                   5451:                  }
                   5452:                }
                   5453:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   5454:            } /* end j==0 */
                   5455:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  5456:            if(bool==1){ /*Selected */
1.251     brouard  5457:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   5458:                 and mw[mi+1][iind]. dh depends on stepm. */
                   5459:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   5460:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   5461:              if(m >=firstpass && m <=lastpass){
                   5462:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   5463:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   5464:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   5465:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   5466:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   5467:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   5468:                if (m<lastpass) {
                   5469:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   5470:                  /*   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]); */
                   5471:                  if(s[m][iind]==-1)
                   5472:                    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.));
                   5473:                  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  5474:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
                   5475:                    if(!isnan(covar[ncovcol+z1][iind])){
1.332     brouard  5476:                      idq[z1]=idq[z1]+weight[iind];
                   5477:                      meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   5478:                      /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
                   5479:                      stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
1.311     brouard  5480:                    }
1.284     brouard  5481:                  }
1.251     brouard  5482:                  /* if((int)agev[m][iind] == 55) */
                   5483:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   5484:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   5485:                  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  5486:                }
1.251     brouard  5487:              } /* end if between passes */  
                   5488:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   5489:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   5490:                k2cpt++;
                   5491:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  5492:              }
1.251     brouard  5493:            }else{
                   5494:              bool=1;
                   5495:            }/* end bool 2 */
                   5496:          } /* end m */
1.284     brouard  5497:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   5498:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   5499:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   5500:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   5501:          /* } */
1.251     brouard  5502:        } /* end bool */
                   5503:       } /* end iind = 1 to imx */
1.319     brouard  5504:       /* prop[s][age] is fed for any initial and valid live state as well as
1.251     brouard  5505:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   5506:       
                   5507:       
                   5508:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.335     brouard  5509:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
1.265     brouard  5510:         pstamp(ficresp);
1.335     brouard  5511:       if  (cptcoveff>0 && j!=0){
1.265     brouard  5512:         pstamp(ficresp);
1.251     brouard  5513:        printf( "\n#********** Variable "); 
                   5514:        fprintf(ficresp, "\n#********** Variable "); 
                   5515:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   5516:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   5517:        fprintf(ficlog, "\n#********** Variable "); 
1.340     brouard  5518:        for (z1=1; z1<=cptcoveff; z1++){
1.251     brouard  5519:          if(!FixedV[Tvaraff[z1]]){
1.330     brouard  5520:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5521:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5522:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5523:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5524:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.250     brouard  5525:          }else{
1.330     brouard  5526:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5527:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5528:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5529:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5530:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.251     brouard  5531:          }
                   5532:        }
                   5533:        printf( "**********\n#");
                   5534:        fprintf(ficresp, "**********\n#");
                   5535:        fprintf(ficresphtm, "**********</h3>\n");
                   5536:        fprintf(ficresphtmfr, "**********</h3>\n");
                   5537:        fprintf(ficlog, "**********\n");
                   5538:       }
1.284     brouard  5539:       /*
                   5540:        Printing means of quantitative variables if any
                   5541:       */
                   5542:       for (z1=1; z1<= nqfveff; z1++) {
1.311     brouard  5543:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.312     brouard  5544:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
1.284     brouard  5545:        if(weightopt==1){
                   5546:          printf(" Weighted mean and standard deviation of");
                   5547:          fprintf(ficlog," Weighted mean and standard deviation of");
                   5548:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   5549:        }
1.311     brouard  5550:        /* mu = \frac{w x}{\sum w}
                   5551:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
                   5552:        */
                   5553:        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]));
                   5554:        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]));
                   5555:        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  5556:       }
                   5557:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   5558:       /*       for(m=1;m<=lastpass;m++){ */
                   5559:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   5560:       /*   } */
                   5561:       /* } */
1.283     brouard  5562: 
1.251     brouard  5563:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.335     brouard  5564:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
1.265     brouard  5565:         fprintf(ficresp, " Age");
1.335     brouard  5566:       if(nj==2) for (z1=1; z1<=cptcoveff; z1++) {
                   5567:          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]]);
                   5568:          fprintf(ficresp, " V%d=%d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5569:        }
1.251     brouard  5570:       for(i=1; i<=nlstate;i++) {
1.335     brouard  5571:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  5572:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   5573:       }
1.335     brouard  5574:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  5575:       fprintf(ficresphtm, "\n");
                   5576:       
                   5577:       /* Header of frequency table by age */
                   5578:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   5579:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  5580:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  5581:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5582:          if(s2!=0 && m!=0)
                   5583:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  5584:        }
1.226     brouard  5585:       }
1.251     brouard  5586:       fprintf(ficresphtmfr, "\n");
                   5587:     
                   5588:       /* For each age */
                   5589:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   5590:        fprintf(ficresphtm,"<tr>");
                   5591:        if(iage==iagemax+1){
                   5592:          fprintf(ficlog,"1");
                   5593:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   5594:        }else if(iage==iagemax+2){
                   5595:          fprintf(ficlog,"0");
                   5596:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   5597:        }else if(iage==iagemax+3){
                   5598:          fprintf(ficlog,"Total");
                   5599:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   5600:        }else{
1.240     brouard  5601:          if(first==1){
1.251     brouard  5602:            first=0;
                   5603:            printf("See log file for details...\n");
                   5604:          }
                   5605:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   5606:          fprintf(ficlog,"Age %d", iage);
                   5607:        }
1.265     brouard  5608:        for(s1=1; s1 <=nlstate ; s1++){
                   5609:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   5610:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  5611:        }
1.265     brouard  5612:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5613:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  5614:            pos += freq[s1][m][iage];
                   5615:          if(pp[s1]>=1.e-10){
1.251     brouard  5616:            if(first==1){
1.265     brouard  5617:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5618:            }
1.265     brouard  5619:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5620:          }else{
                   5621:            if(first==1)
1.265     brouard  5622:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   5623:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  5624:          }
                   5625:        }
                   5626:       
1.265     brouard  5627:        for(s1=1; s1 <=nlstate ; s1++){ 
                   5628:          /* posprop[s1]=0; */
                   5629:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   5630:            pp[s1] += freq[s1][m][iage];
                   5631:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   5632:       
                   5633:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   5634:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   5635:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5636:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5637:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5638:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5639:        }
                   5640:        
                   5641:        /* Writing ficresp */
1.335     brouard  5642:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5643:           if( iage <= iagemax){
                   5644:            fprintf(ficresp," %d",iage);
                   5645:           }
                   5646:         }else if( nj==2){
                   5647:           if( iage <= iagemax){
                   5648:            fprintf(ficresp," %d",iage);
1.335     brouard  5649:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.265     brouard  5650:           }
1.240     brouard  5651:        }
1.265     brouard  5652:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  5653:          if(pos>=1.e-5){
1.251     brouard  5654:            if(first==1)
1.265     brouard  5655:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   5656:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  5657:          }else{
                   5658:            if(first==1)
1.265     brouard  5659:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   5660:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  5661:          }
                   5662:          if( iage <= iagemax){
                   5663:            if(pos>=1.e-5){
1.335     brouard  5664:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5665:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5666:               }else if( nj==2){
                   5667:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5668:               }
                   5669:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5670:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   5671:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   5672:            } else{
1.335     brouard  5673:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
1.265     brouard  5674:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  5675:            }
1.240     brouard  5676:          }
1.265     brouard  5677:          pospropt[s1] +=posprop[s1];
                   5678:        } /* end loop s1 */
1.251     brouard  5679:        /* pospropt=0.; */
1.265     brouard  5680:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  5681:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5682:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  5683:              if(first==1){
1.265     brouard  5684:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5685:              }
1.265     brouard  5686:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   5687:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5688:            }
1.265     brouard  5689:            if(s1!=0 && m!=0)
                   5690:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  5691:          }
1.265     brouard  5692:        } /* end loop s1 */
1.251     brouard  5693:        posproptt=0.; 
1.265     brouard  5694:        for(s1=1; s1 <=nlstate; s1++){
                   5695:          posproptt += pospropt[s1];
1.251     brouard  5696:        }
                   5697:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  5698:        fprintf(ficresphtm,"</tr>\n");
1.335     brouard  5699:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
1.265     brouard  5700:          if(iage <= iagemax)
                   5701:            fprintf(ficresp,"\n");
1.240     brouard  5702:        }
1.251     brouard  5703:        if(first==1)
                   5704:          printf("Others in log...\n");
                   5705:        fprintf(ficlog,"\n");
                   5706:       } /* end loop age iage */
1.265     brouard  5707:       
1.251     brouard  5708:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  5709:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5710:        if(posproptt < 1.e-5){
1.265     brouard  5711:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  5712:        }else{
1.265     brouard  5713:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  5714:        }
1.226     brouard  5715:       }
1.251     brouard  5716:       fprintf(ficresphtm,"</tr>\n");
                   5717:       fprintf(ficresphtm,"</table>\n");
                   5718:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  5719:       if(posproptt < 1.e-5){
1.251     brouard  5720:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   5721:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  5722:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   5723:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  5724:        invalidvarcomb[j1]=1;
1.226     brouard  5725:       }else{
1.338     brouard  5726:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced (or no resultline).</p>",j1);
1.251     brouard  5727:        invalidvarcomb[j1]=0;
1.226     brouard  5728:       }
1.251     brouard  5729:       fprintf(ficresphtmfr,"</table>\n");
                   5730:       fprintf(ficlog,"\n");
                   5731:       if(j!=0){
                   5732:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  5733:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5734:          for(k=1; k <=(nlstate+ndeath); k++){
                   5735:            if (k != i) {
1.265     brouard  5736:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  5737:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  5738:                  if(j1==1){ /* All dummy covariates to zero */
                   5739:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   5740:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  5741:                    printf("%d%d ",i,k);
                   5742:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5743:                    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]));
                   5744:                    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]));
                   5745:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  5746:                  }
1.253     brouard  5747:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   5748:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   5749:                    x[iage]= (double)iage;
                   5750:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  5751:                    /* 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  5752:                  }
1.268     brouard  5753:                  /* Some are not finite, but linreg will ignore these ages */
                   5754:                  no=0;
1.253     brouard  5755:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  5756:                  pstart[s1]=b;
                   5757:                  pstart[s1-1]=a;
1.252     brouard  5758:                }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 */ 
                   5759:                  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]);
                   5760:                  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  5761:                  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  5762:                  printf("%d%d ",i,k);
                   5763:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5764:                  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  5765:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   5766:                  ;
                   5767:                }
                   5768:                /* printf("%12.7f )", param[i][jj][k]); */
                   5769:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5770:                s1++; 
1.251     brouard  5771:              } /* end jj */
                   5772:            } /* end k!= i */
                   5773:          } /* end k */
1.265     brouard  5774:        } /* end i, s1 */
1.251     brouard  5775:       } /* end j !=0 */
                   5776:     } /* end selected combination of covariate j1 */
                   5777:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   5778:       printf("#Freqsummary: Starting values for the constants:\n");
                   5779:       fprintf(ficlog,"\n");
1.265     brouard  5780:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5781:        for(k=1; k <=(nlstate+ndeath); k++){
                   5782:          if (k != i) {
                   5783:            printf("%d%d ",i,k);
                   5784:            fprintf(ficlog,"%d%d ",i,k);
                   5785:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  5786:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  5787:              if(jj==1){ /* Age has to be done */
1.265     brouard  5788:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   5789:                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]));
                   5790:                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  5791:              }
                   5792:              /* printf("%12.7f )", param[i][jj][k]); */
                   5793:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5794:              s1++; 
1.250     brouard  5795:            }
1.251     brouard  5796:            printf("\n");
                   5797:            fprintf(ficlog,"\n");
1.250     brouard  5798:          }
                   5799:        }
1.284     brouard  5800:       } /* end of state i */
1.251     brouard  5801:       printf("#Freqsummary\n");
                   5802:       fprintf(ficlog,"\n");
1.265     brouard  5803:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   5804:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   5805:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   5806:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5807:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5808:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   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]); */
1.251     brouard  5811:          /* } */
                   5812:        }
1.265     brouard  5813:       } /* end loop s1 */
1.251     brouard  5814:       
                   5815:       printf("\n");
                   5816:       fprintf(ficlog,"\n");
                   5817:     } /* end j=0 */
1.249     brouard  5818:   } /* end j */
1.252     brouard  5819: 
1.253     brouard  5820:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  5821:     for(i=1, jk=1; i <=nlstate; i++){
                   5822:       for(j=1; j <=nlstate+ndeath; j++){
                   5823:        if(j!=i){
                   5824:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5825:          printf("%1d%1d",i,j);
                   5826:          fprintf(ficparo,"%1d%1d",i,j);
                   5827:          for(k=1; k<=ncovmodel;k++){
                   5828:            /*    printf(" %lf",param[i][j][k]); */
                   5829:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   5830:            p[jk]=pstart[jk];
                   5831:            printf(" %f ",pstart[jk]);
                   5832:            fprintf(ficparo," %f ",pstart[jk]);
                   5833:            jk++;
                   5834:          }
                   5835:          printf("\n");
                   5836:          fprintf(ficparo,"\n");
                   5837:        }
                   5838:       }
                   5839:     }
                   5840:   } /* end mle=-2 */
1.226     brouard  5841:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  5842:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  5843:   
1.226     brouard  5844:   fclose(ficresp);
                   5845:   fclose(ficresphtm);
                   5846:   fclose(ficresphtmfr);
1.283     brouard  5847:   free_vector(idq,1,nqfveff);
1.226     brouard  5848:   free_vector(meanq,1,nqfveff);
1.284     brouard  5849:   free_vector(stdq,1,nqfveff);
1.226     brouard  5850:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  5851:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   5852:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  5853:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5854:   free_vector(pospropt,1,nlstate);
                   5855:   free_vector(posprop,1,nlstate);
1.251     brouard  5856:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5857:   free_vector(pp,1,nlstate);
                   5858:   /* End of freqsummary */
                   5859: }
1.126     brouard  5860: 
1.268     brouard  5861: /* Simple linear regression */
                   5862: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   5863: 
                   5864:   /* y=a+bx regression */
                   5865:   double   sumx = 0.0;                        /* sum of x                      */
                   5866:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   5867:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   5868:   double   sumy = 0.0;                        /* sum of y                      */
                   5869:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   5870:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   5871:   double yhat;
                   5872:   
                   5873:   double denom=0;
                   5874:   int i;
                   5875:   int ne=*no;
                   5876:   
                   5877:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5878:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5879:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5880:       continue;
                   5881:     }
                   5882:     ne=ne+1;
                   5883:     sumx  += x[i];       
                   5884:     sumx2 += x[i]*x[i];  
                   5885:     sumxy += x[i] * y[i];
                   5886:     sumy  += y[i];      
                   5887:     sumy2 += y[i]*y[i]; 
                   5888:     denom = (ne * sumx2 - sumx*sumx);
                   5889:     /* 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); */
                   5890:   } 
                   5891:   
                   5892:   denom = (ne * sumx2 - sumx*sumx);
                   5893:   if (denom == 0) {
                   5894:     // vertical, slope m is infinity
                   5895:     *b = INFINITY;
                   5896:     *a = 0;
                   5897:     if (r) *r = 0;
                   5898:     return 1;
                   5899:   }
                   5900:   
                   5901:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   5902:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   5903:   if (r!=NULL) {
                   5904:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   5905:       sqrt((sumx2 - sumx*sumx/ne) *
                   5906:           (sumy2 - sumy*sumy/ne));
                   5907:   }
                   5908:   *no=ne;
                   5909:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5910:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5911:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5912:       continue;
                   5913:     }
                   5914:     ne=ne+1;
                   5915:     yhat = y[i] - *a -*b* x[i];
                   5916:     sume2  += yhat * yhat ;       
                   5917:     
                   5918:     denom = (ne * sumx2 - sumx*sumx);
                   5919:     /* 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); */
                   5920:   } 
                   5921:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   5922:   *sa= *sb * sqrt(sumx2/ne);
                   5923:   
                   5924:   return 0; 
                   5925: }
                   5926: 
1.126     brouard  5927: /************ Prevalence ********************/
1.227     brouard  5928: 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)
                   5929: {  
                   5930:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   5931:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   5932:      We still use firstpass and lastpass as another selection.
                   5933:   */
1.126     brouard  5934:  
1.227     brouard  5935:   int i, m, jk, j1, bool, z1,j, iv;
                   5936:   int mi; /* Effective wave */
                   5937:   int iage;
                   5938:   double agebegin, ageend;
                   5939: 
                   5940:   double **prop;
                   5941:   double posprop; 
                   5942:   double  y2; /* in fractional years */
                   5943:   int iagemin, iagemax;
                   5944:   int first; /** to stop verbosity which is redirected to log file */
                   5945: 
                   5946:   iagemin= (int) agemin;
                   5947:   iagemax= (int) agemax;
                   5948:   /*pp=vector(1,nlstate);*/
1.251     brouard  5949:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  5950:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   5951:   j1=0;
1.222     brouard  5952:   
1.227     brouard  5953:   /*j=cptcoveff;*/
                   5954:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  5955:   
1.288     brouard  5956:   first=0;
1.335     brouard  5957:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of simple dummy covariates */
1.227     brouard  5958:     for (i=1; i<=nlstate; i++)  
1.251     brouard  5959:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  5960:        prop[i][iage]=0.0;
                   5961:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   5962:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   5963:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   5964:     
                   5965:     for (i=1; i<=imx; i++) { /* Each individual */
                   5966:       bool=1;
                   5967:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   5968:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   5969:        m=mw[mi][i];
                   5970:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   5971:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   5972:        for (z1=1; z1<=cptcoveff; z1++){
                   5973:          if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  5974:            iv= Tvar[Tmodelind[z1]];/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
1.332     brouard  5975:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality */
1.227     brouard  5976:              bool=0;
                   5977:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
1.332     brouard  5978:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) {
1.227     brouard  5979:              bool=0;
                   5980:            }
                   5981:        }
                   5982:        if(bool==1){ /* Otherwise we skip that wave/person */
                   5983:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   5984:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   5985:          if(m >=firstpass && m <=lastpass){
                   5986:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   5987:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   5988:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   5989:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  5990:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  5991:                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); 
                   5992:                exit(1);
                   5993:              }
                   5994:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   5995:                /*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]]);*/
                   5996:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   5997:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   5998:              } /* end valid statuses */ 
                   5999:            } /* end selection of dates */
                   6000:          } /* end selection of waves */
                   6001:        } /* end bool */
                   6002:       } /* end wave */
                   6003:     } /* end individual */
                   6004:     for(i=iagemin; i <= iagemax+3; i++){  
                   6005:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   6006:        posprop += prop[jk][i]; 
                   6007:       } 
                   6008:       
                   6009:       for(jk=1; jk <=nlstate ; jk++){      
                   6010:        if( i <=  iagemax){ 
                   6011:          if(posprop>=1.e-5){ 
                   6012:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   6013:          } else{
1.288     brouard  6014:            if(!first){
                   6015:              first=1;
1.266     brouard  6016:              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]);
                   6017:            }else{
1.288     brouard  6018:              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  6019:            }
                   6020:          }
                   6021:        } 
                   6022:       }/* end jk */ 
                   6023:     }/* end i */ 
1.222     brouard  6024:      /*} *//* end i1 */
1.227     brouard  6025:   } /* end j1 */
1.222     brouard  6026:   
1.227     brouard  6027:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   6028:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  6029:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  6030: }  /* End of prevalence */
1.126     brouard  6031: 
                   6032: /************* Waves Concatenation ***************/
                   6033: 
                   6034: 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)
                   6035: {
1.298     brouard  6036:   /* 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  6037:      Death is a valid wave (if date is known).
                   6038:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   6039:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  6040:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  6041:   */
1.126     brouard  6042: 
1.224     brouard  6043:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  6044:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   6045:      double sum=0., jmean=0.;*/
1.224     brouard  6046:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  6047:   int j, k=0,jk, ju, jl;
                   6048:   double sum=0.;
                   6049:   first=0;
1.214     brouard  6050:   firstwo=0;
1.217     brouard  6051:   firsthree=0;
1.218     brouard  6052:   firstfour=0;
1.164     brouard  6053:   jmin=100000;
1.126     brouard  6054:   jmax=-1;
                   6055:   jmean=0.;
1.224     brouard  6056: 
                   6057: /* Treating live states */
1.214     brouard  6058:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  6059:     mi=0;  /* First valid wave */
1.227     brouard  6060:     mli=0; /* Last valid wave */
1.309     brouard  6061:     m=firstpass;  /* Loop on waves */
                   6062:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
1.227     brouard  6063:       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 */
                   6064:        mli=m-1;/* mw[++mi][i]=m-1; */
                   6065:       }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  6066:        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  6067:        mli=m;
1.224     brouard  6068:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   6069:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  6070:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  6071:       }
1.309     brouard  6072:       else{ /* m = lastpass, eventual special issue with warning */
1.224     brouard  6073: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  6074:        break;
1.224     brouard  6075: #else
1.317     brouard  6076:        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  6077:          if(firsthree == 0){
1.302     brouard  6078:            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  6079:            firsthree=1;
1.317     brouard  6080:          }else if(firsthree >=1 && firsthree < 10){
                   6081:            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);
                   6082:            firsthree++;
                   6083:          }else if(firsthree == 10){
                   6084:            printf("Information, too many Information flags: no more reported to log either\n");
                   6085:            fprintf(ficlog,"Information, too many Information flags: no more reported to log either\n");
                   6086:            firsthree++;
                   6087:          }else{
                   6088:            firsthree++;
1.227     brouard  6089:          }
1.309     brouard  6090:          mw[++mi][i]=m; /* Valid transition with unknown status */
1.227     brouard  6091:          mli=m;
                   6092:        }
                   6093:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   6094:          nbwarn++;
1.309     brouard  6095:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
1.227     brouard  6096:            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);
                   6097:            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);
                   6098:          }
                   6099:          break;
                   6100:        }
                   6101:        break;
1.224     brouard  6102: #endif
1.227     brouard  6103:       }/* End m >= lastpass */
1.126     brouard  6104:     }/* end while */
1.224     brouard  6105: 
1.227     brouard  6106:     /* 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  6107:     /* After last pass */
1.224     brouard  6108: /* Treating death states */
1.214     brouard  6109:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  6110:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   6111:       /* } */
1.126     brouard  6112:       mi++;    /* Death is another wave */
                   6113:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  6114:       /* Only death is a correct wave */
1.126     brouard  6115:       mw[mi][i]=m;
1.257     brouard  6116:     } /* else not in a death state */
1.224     brouard  6117: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  6118:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  6119:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.309     brouard  6120:        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  6121:          nbwarn++;
                   6122:          if(firstfiv==0){
1.309     brouard  6123:            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  6124:            firstfiv=1;
                   6125:          }else{
1.309     brouard  6126:            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  6127:          }
1.309     brouard  6128:            s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
                   6129:        }else{ /* Month of Death occured afer last wave month, potential bias */
1.227     brouard  6130:          nberr++;
                   6131:          if(firstwo==0){
1.309     brouard  6132:            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  6133:            firstwo=1;
                   6134:          }
1.309     brouard  6135:          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  6136:        }
1.257     brouard  6137:       }else{ /* if date of interview is unknown */
1.227     brouard  6138:        /* death is known but not confirmed by death status at any wave */
                   6139:        if(firstfour==0){
1.309     brouard  6140:          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  6141:          firstfour=1;
                   6142:        }
1.309     brouard  6143:        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  6144:       }
1.224     brouard  6145:     } /* end if date of death is known */
                   6146: #endif
1.309     brouard  6147:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
                   6148:     /* wav[i]=mw[mi][i];   */
1.126     brouard  6149:     if(mi==0){
                   6150:       nbwarn++;
                   6151:       if(first==0){
1.227     brouard  6152:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   6153:        first=1;
1.126     brouard  6154:       }
                   6155:       if(first==1){
1.227     brouard  6156:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  6157:       }
                   6158:     } /* end mi==0 */
                   6159:   } /* End individuals */
1.214     brouard  6160:   /* wav and mw are no more changed */
1.223     brouard  6161:        
1.317     brouard  6162:   printf("Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   6163:   fprintf(ficlog,"Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   6164: 
                   6165: 
1.126     brouard  6166:   for(i=1; i<=imx; i++){
                   6167:     for(mi=1; mi<wav[i];mi++){
                   6168:       if (stepm <=0)
1.227     brouard  6169:        dh[mi][i]=1;
1.126     brouard  6170:       else{
1.260     brouard  6171:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  6172:          if (agedc[i] < 2*AGESUP) {
                   6173:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   6174:            if(j==0) j=1;  /* Survives at least one month after exam */
                   6175:            else if(j<0){
                   6176:              nberr++;
                   6177:              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]);
                   6178:              j=1; /* Temporary Dangerous patch */
                   6179:              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);
                   6180:              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]);
                   6181:              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);
                   6182:            }
                   6183:            k=k+1;
                   6184:            if (j >= jmax){
                   6185:              jmax=j;
                   6186:              ijmax=i;
                   6187:            }
                   6188:            if (j <= jmin){
                   6189:              jmin=j;
                   6190:              ijmin=i;
                   6191:            }
                   6192:            sum=sum+j;
                   6193:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   6194:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   6195:          }
                   6196:        }
                   6197:        else{
                   6198:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  6199: /*       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  6200:                                        
1.227     brouard  6201:          k=k+1;
                   6202:          if (j >= jmax) {
                   6203:            jmax=j;
                   6204:            ijmax=i;
                   6205:          }
                   6206:          else if (j <= jmin){
                   6207:            jmin=j;
                   6208:            ijmin=i;
                   6209:          }
                   6210:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   6211:          /*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]);*/
                   6212:          if(j<0){
                   6213:            nberr++;
                   6214:            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]);
                   6215:            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]);
                   6216:          }
                   6217:          sum=sum+j;
                   6218:        }
                   6219:        jk= j/stepm;
                   6220:        jl= j -jk*stepm;
                   6221:        ju= j -(jk+1)*stepm;
                   6222:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   6223:          if(jl==0){
                   6224:            dh[mi][i]=jk;
                   6225:            bh[mi][i]=0;
                   6226:          }else{ /* We want a negative bias in order to only have interpolation ie
                   6227:                  * to avoid the price of an extra matrix product in likelihood */
                   6228:            dh[mi][i]=jk+1;
                   6229:            bh[mi][i]=ju;
                   6230:          }
                   6231:        }else{
                   6232:          if(jl <= -ju){
                   6233:            dh[mi][i]=jk;
                   6234:            bh[mi][i]=jl;       /* bias is positive if real duration
                   6235:                                 * is higher than the multiple of stepm and negative otherwise.
                   6236:                                 */
                   6237:          }
                   6238:          else{
                   6239:            dh[mi][i]=jk+1;
                   6240:            bh[mi][i]=ju;
                   6241:          }
                   6242:          if(dh[mi][i]==0){
                   6243:            dh[mi][i]=1; /* At least one step */
                   6244:            bh[mi][i]=ju; /* At least one step */
                   6245:            /*  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);*/
                   6246:          }
                   6247:        } /* end if mle */
1.126     brouard  6248:       }
                   6249:     } /* end wave */
                   6250:   }
                   6251:   jmean=sum/k;
                   6252:   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  6253:   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  6254: }
1.126     brouard  6255: 
                   6256: /*********** Tricode ****************************/
1.220     brouard  6257:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  6258:  {
                   6259:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   6260:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   6261:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   6262:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   6263:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   6264:     */
1.130     brouard  6265: 
1.242     brouard  6266:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   6267:    int modmaxcovj=0; /* Modality max of covariates j */
                   6268:    int cptcode=0; /* Modality max of covariates j */
                   6269:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  6270: 
                   6271: 
1.242     brouard  6272:    /* cptcoveff=0;  */
                   6273:    /* *cptcov=0; */
1.126     brouard  6274:  
1.242     brouard  6275:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  6276:    for (k=1; k <= maxncov; k++)
                   6277:      for(j=1; j<=2; j++)
                   6278:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  6279: 
1.242     brouard  6280:    /* Loop on covariates without age and products and no quantitative variable */
1.335     brouard  6281:    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  6282:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
1.343     brouard  6283:      /* printf("Testing k=%d, cptcovt=%d\n",k, cptcovt); */
1.339     brouard  6284:      if(Dummy[k]==0 && Typevar[k] !=1 && Typevar[k] != 2){ /* Dummy covariate and not age product nor fixed product */ 
1.242     brouard  6285:        switch(Fixed[k]) {
                   6286:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.311     brouard  6287:         modmaxcovj=0;
                   6288:         modmincovj=0;
1.242     brouard  6289:         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  6290:           /* 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  6291:           ij=(int)(covar[Tvar[k]][i]);
                   6292:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   6293:            * If product of Vn*Vm, still boolean *:
                   6294:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   6295:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   6296:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   6297:              modality of the nth covariate of individual i. */
                   6298:           if (ij > modmaxcovj)
                   6299:             modmaxcovj=ij; 
                   6300:           else if (ij < modmincovj) 
                   6301:             modmincovj=ij; 
1.287     brouard  6302:           if (ij <0 || ij >1 ){
1.311     brouard  6303:             printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6304:             fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6305:             fflush(ficlog);
                   6306:             exit(1);
1.287     brouard  6307:           }
                   6308:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  6309:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   6310:             exit(1);
                   6311:           }else
                   6312:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   6313:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   6314:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   6315:           /* getting the maximum value of the modality of the covariate
                   6316:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   6317:              female ies 1, then modmaxcovj=1.
                   6318:           */
                   6319:         } /* end for loop on individuals i */
                   6320:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6321:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6322:         cptcode=modmaxcovj;
                   6323:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   6324:         /*for (i=0; i<=cptcode; i++) {*/
                   6325:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   6326:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6327:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6328:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   6329:             if( j != -1){
                   6330:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   6331:                                  covariate for which somebody answered excluding 
                   6332:                                  undefined. Usually 2: 0 and 1. */
                   6333:             }
                   6334:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   6335:                                     covariate for which somebody answered including 
                   6336:                                     undefined. Usually 3: -1, 0 and 1. */
                   6337:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   6338:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   6339:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  6340:                        
1.242     brouard  6341:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   6342:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   6343:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   6344:         /* modmincovj=3; modmaxcovj = 7; */
                   6345:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   6346:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   6347:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   6348:         /* nbcode[Tvar[j]][ij]=k; */
                   6349:         /* nbcode[Tvar[j]][1]=0; */
                   6350:         /* nbcode[Tvar[j]][2]=1; */
                   6351:         /* nbcode[Tvar[j]][3]=2; */
                   6352:         /* To be continued (not working yet). */
                   6353:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  6354: 
                   6355:         /* 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*/
                   6356:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   6357:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   6358:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   6359:         /*, could be restored in the future */
                   6360:         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  6361:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   6362:             break;
                   6363:           }
                   6364:           ij++;
1.287     brouard  6365:           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  6366:           cptcode = ij; /* New max modality for covar j */
                   6367:         } /* end of loop on modality i=-1 to 1 or more */
                   6368:         break;
                   6369:        case 1: /* Testing on varying covariate, could be simple and
                   6370:                * should look at waves or product of fixed *
                   6371:                * varying. No time to test -1, assuming 0 and 1 only */
                   6372:         ij=0;
                   6373:         for(i=0; i<=1;i++){
                   6374:           nbcode[Tvar[k]][++ij]=i;
                   6375:         }
                   6376:         break;
                   6377:        default:
                   6378:         break;
                   6379:        } /* end switch */
                   6380:      } /* end dummy test */
1.342     brouard  6381:      if(Dummy[k]==1 && Typevar[k] !=1 && Fixed ==0){ /* Fixed Quantitative covariate and not age product */ 
1.311     brouard  6382:        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  6383:         if(Tvar[k]<=0 || Tvar[k]>=NCOVMAX){
                   6384:           printf("Error k=%d \n",k);
                   6385:           exit(1);
                   6386:         }
1.311     brouard  6387:         if(isnan(covar[Tvar[k]][i])){
                   6388:           printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6389:           fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6390:           fflush(ficlog);
                   6391:           exit(1);
                   6392:          }
                   6393:        }
1.335     brouard  6394:      } /* end Quanti */
1.287     brouard  6395:    } /* 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  6396:   
                   6397:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   6398:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   6399:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   6400:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   6401:      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 */ 
                   6402:      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 */
                   6403:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   6404:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   6405:   
                   6406:    ij=0;
                   6407:    /* 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  6408:    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 */
                   6409:      /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
1.242     brouard  6410:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   6411:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
1.335     brouard  6412:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy simple and non empty in the model */
                   6413:        /* Typevar[k] =0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for product */
                   6414:        /* 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  6415:        /* If product not in single variable we don't print results */
                   6416:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
1.335     brouard  6417:        ++ij;/*    V5 + V4 + V3 + V4*V3 + V5*age + V2 +  V1*V2 + V1*age + V1, *//* V5 quanti, V2 quanti, V4, V3, V1 dummies */
                   6418:        /* k=       1    2   3     4       5       6      7       8        9  */
                   6419:        /* Tvar[k]= 5    4    3    6       5       2      7       1        1  */
                   6420:        /* ij            1    2                                            3  */  
                   6421:        /* Tvaraff[ij]=  4    3                                            1  */
                   6422:        /* Tmodelind[ij]=2    3                                            9  */
                   6423:        /* TmodelInvind[ij]=2 1                                            1  */
1.242     brouard  6424:        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*/
                   6425:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   6426:        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 */
                   6427:        if(Fixed[k]!=0)
                   6428:         anyvaryingduminmodel=1;
                   6429:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   6430:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6431:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   6432:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   6433:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   6434:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6435:      } 
                   6436:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   6437:    /* ij--; */
                   6438:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
1.335     brouard  6439:    *cptcov=ij; /* cptcov= Number of total real effective simple dummies (fixed or time  arying) effective (used as cptcoveff in other functions)
1.242     brouard  6440:                * because they can be excluded from the model and real
                   6441:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   6442:    for(j=ij+1; j<= cptcovt; j++){
                   6443:      Tvaraff[j]=0;
                   6444:      Tmodelind[j]=0;
                   6445:    }
                   6446:    for(j=ntveff+1; j<= cptcovt; j++){
                   6447:      TmodelInvind[j]=0;
                   6448:    }
                   6449:    /* To be sorted */
                   6450:    ;
                   6451:  }
1.126     brouard  6452: 
1.145     brouard  6453: 
1.126     brouard  6454: /*********** Health Expectancies ****************/
                   6455: 
1.235     brouard  6456:  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  6457: 
                   6458: {
                   6459:   /* Health expectancies, no variances */
1.329     brouard  6460:   /* cij is the combination in the list of combination of dummy covariates */
                   6461:   /* strstart is a string of time at start of computing */
1.164     brouard  6462:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  6463:   int nhstepma, nstepma; /* Decreasing with age */
                   6464:   double age, agelim, hf;
                   6465:   double ***p3mat;
                   6466:   double eip;
                   6467: 
1.238     brouard  6468:   /* pstamp(ficreseij); */
1.126     brouard  6469:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   6470:   fprintf(ficreseij,"# Age");
                   6471:   for(i=1; i<=nlstate;i++){
                   6472:     for(j=1; j<=nlstate;j++){
                   6473:       fprintf(ficreseij," e%1d%1d ",i,j);
                   6474:     }
                   6475:     fprintf(ficreseij," e%1d. ",i);
                   6476:   }
                   6477:   fprintf(ficreseij,"\n");
                   6478: 
                   6479:   
                   6480:   if(estepm < stepm){
                   6481:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6482:   }
                   6483:   else  hstepm=estepm;   
                   6484:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6485:    * This is mainly to measure the difference between two models: for example
                   6486:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6487:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6488:    * progression in between and thus overestimating or underestimating according
                   6489:    * to the curvature of the survival function. If, for the same date, we 
                   6490:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6491:    * to compare the new estimate of Life expectancy with the same linear 
                   6492:    * hypothesis. A more precise result, taking into account a more precise
                   6493:    * curvature will be obtained if estepm is as small as stepm. */
                   6494: 
                   6495:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6496:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6497:      nhstepm is the number of hstepm from age to agelim 
                   6498:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  6499:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  6500:      and note for a fixed period like estepm months */
                   6501:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6502:      survival function given by stepm (the optimization length). Unfortunately it
                   6503:      means that if the survival funtion is printed only each two years of age and if
                   6504:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6505:      results. So we changed our mind and took the option of the best precision.
                   6506:   */
                   6507:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6508: 
                   6509:   agelim=AGESUP;
                   6510:   /* If stepm=6 months */
                   6511:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   6512:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   6513:     
                   6514: /* nhstepm age range expressed in number of stepm */
                   6515:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6516:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6517:   /* if (stepm >= YEARM) hstepm=1;*/
                   6518:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6519:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6520: 
                   6521:   for (age=bage; age<=fage; age ++){ 
                   6522:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6523:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6524:     /* if (stepm >= YEARM) hstepm=1;*/
                   6525:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   6526: 
                   6527:     /* If stepm=6 months */
                   6528:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6529:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
1.330     brouard  6530:     /* 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  6531:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  6532:     
                   6533:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6534:     
                   6535:     printf("%d|",(int)age);fflush(stdout);
                   6536:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6537:     
                   6538:     /* Computing expectancies */
                   6539:     for(i=1; i<=nlstate;i++)
                   6540:       for(j=1; j<=nlstate;j++)
                   6541:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6542:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   6543:          
                   6544:          /* 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]);*/
                   6545: 
                   6546:        }
                   6547: 
                   6548:     fprintf(ficreseij,"%3.0f",age );
                   6549:     for(i=1; i<=nlstate;i++){
                   6550:       eip=0;
                   6551:       for(j=1; j<=nlstate;j++){
                   6552:        eip +=eij[i][j][(int)age];
                   6553:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   6554:       }
                   6555:       fprintf(ficreseij,"%9.4f", eip );
                   6556:     }
                   6557:     fprintf(ficreseij,"\n");
                   6558:     
                   6559:   }
                   6560:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6561:   printf("\n");
                   6562:   fprintf(ficlog,"\n");
                   6563:   
                   6564: }
                   6565: 
1.235     brouard  6566:  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  6567: 
                   6568: {
                   6569:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  6570:      to initial status i, ei. .
1.126     brouard  6571:   */
1.336     brouard  6572:   /* Very time consuming function, but already optimized with precov */
1.126     brouard  6573:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   6574:   int nhstepma, nstepma; /* Decreasing with age */
                   6575:   double age, agelim, hf;
                   6576:   double ***p3matp, ***p3matm, ***varhe;
                   6577:   double **dnewm,**doldm;
                   6578:   double *xp, *xm;
                   6579:   double **gp, **gm;
                   6580:   double ***gradg, ***trgradg;
                   6581:   int theta;
                   6582: 
                   6583:   double eip, vip;
                   6584: 
                   6585:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   6586:   xp=vector(1,npar);
                   6587:   xm=vector(1,npar);
                   6588:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   6589:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   6590:   
                   6591:   pstamp(ficresstdeij);
                   6592:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   6593:   fprintf(ficresstdeij,"# Age");
                   6594:   for(i=1; i<=nlstate;i++){
                   6595:     for(j=1; j<=nlstate;j++)
                   6596:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   6597:     fprintf(ficresstdeij," e%1d. ",i);
                   6598:   }
                   6599:   fprintf(ficresstdeij,"\n");
                   6600: 
                   6601:   pstamp(ficrescveij);
                   6602:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   6603:   fprintf(ficrescveij,"# Age");
                   6604:   for(i=1; i<=nlstate;i++)
                   6605:     for(j=1; j<=nlstate;j++){
                   6606:       cptj= (j-1)*nlstate+i;
                   6607:       for(i2=1; i2<=nlstate;i2++)
                   6608:        for(j2=1; j2<=nlstate;j2++){
                   6609:          cptj2= (j2-1)*nlstate+i2;
                   6610:          if(cptj2 <= cptj)
                   6611:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   6612:        }
                   6613:     }
                   6614:   fprintf(ficrescveij,"\n");
                   6615:   
                   6616:   if(estepm < stepm){
                   6617:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6618:   }
                   6619:   else  hstepm=estepm;   
                   6620:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6621:    * This is mainly to measure the difference between two models: for example
                   6622:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6623:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6624:    * progression in between and thus overestimating or underestimating according
                   6625:    * to the curvature of the survival function. If, for the same date, we 
                   6626:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6627:    * to compare the new estimate of Life expectancy with the same linear 
                   6628:    * hypothesis. A more precise result, taking into account a more precise
                   6629:    * curvature will be obtained if estepm is as small as stepm. */
                   6630: 
                   6631:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6632:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6633:      nhstepm is the number of hstepm from age to agelim 
                   6634:      nstepm is the number of stepm from age to agelin. 
                   6635:      Look at hpijx to understand the reason of that which relies in memory size
                   6636:      and note for a fixed period like estepm months */
                   6637:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6638:      survival function given by stepm (the optimization length). Unfortunately it
                   6639:      means that if the survival funtion is printed only each two years of age and if
                   6640:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6641:      results. So we changed our mind and took the option of the best precision.
                   6642:   */
                   6643:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6644: 
                   6645:   /* If stepm=6 months */
                   6646:   /* nhstepm age range expressed in number of stepm */
                   6647:   agelim=AGESUP;
                   6648:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   6649:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6650:   /* if (stepm >= YEARM) hstepm=1;*/
                   6651:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6652:   
                   6653:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6654:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6655:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   6656:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   6657:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   6658:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   6659: 
                   6660:   for (age=bage; age<=fage; age ++){ 
                   6661:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6662:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6663:     /* if (stepm >= YEARM) hstepm=1;*/
                   6664:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  6665:                
1.126     brouard  6666:     /* If stepm=6 months */
                   6667:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6668:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   6669:     
                   6670:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  6671:                
1.126     brouard  6672:     /* Computing  Variances of health expectancies */
                   6673:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   6674:        decrease memory allocation */
                   6675:     for(theta=1; theta <=npar; theta++){
                   6676:       for(i=1; i<=npar; i++){ 
1.222     brouard  6677:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6678:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  6679:       }
1.235     brouard  6680:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   6681:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  6682:                        
1.126     brouard  6683:       for(j=1; j<= nlstate; j++){
1.222     brouard  6684:        for(i=1; i<=nlstate; i++){
                   6685:          for(h=0; h<=nhstepm-1; h++){
                   6686:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   6687:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   6688:          }
                   6689:        }
1.126     brouard  6690:       }
1.218     brouard  6691:                        
1.126     brouard  6692:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  6693:        for(h=0; h<=nhstepm-1; h++){
                   6694:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   6695:        }
1.126     brouard  6696:     }/* End theta */
                   6697:     
                   6698:     
                   6699:     for(h=0; h<=nhstepm-1; h++)
                   6700:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  6701:        for(theta=1; theta <=npar; theta++)
                   6702:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  6703:     
1.218     brouard  6704:                
1.222     brouard  6705:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  6706:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  6707:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  6708:                
1.222     brouard  6709:     printf("%d|",(int)age);fflush(stdout);
                   6710:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6711:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  6712:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  6713:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   6714:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   6715:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   6716:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   6717:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  6718:       }
                   6719:     }
1.320     brouard  6720:     /* if((int)age ==50){ */
                   6721:     /*   printf(" age=%d cij=%d nres=%d varhe[%d][%d]=%f ",(int)age, cij, nres, 1,2,varhe[1][2]); */
                   6722:     /* } */
1.126     brouard  6723:     /* Computing expectancies */
1.235     brouard  6724:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  6725:     for(i=1; i<=nlstate;i++)
                   6726:       for(j=1; j<=nlstate;j++)
1.222     brouard  6727:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6728:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  6729:                                        
1.222     brouard  6730:          /* 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  6731:                                        
1.222     brouard  6732:        }
1.269     brouard  6733: 
                   6734:     /* Standard deviation of expectancies ij */                
1.126     brouard  6735:     fprintf(ficresstdeij,"%3.0f",age );
                   6736:     for(i=1; i<=nlstate;i++){
                   6737:       eip=0.;
                   6738:       vip=0.;
                   6739:       for(j=1; j<=nlstate;j++){
1.222     brouard  6740:        eip += eij[i][j][(int)age];
                   6741:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   6742:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   6743:        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  6744:       }
                   6745:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   6746:     }
                   6747:     fprintf(ficresstdeij,"\n");
1.218     brouard  6748:                
1.269     brouard  6749:     /* Variance of expectancies ij */          
1.126     brouard  6750:     fprintf(ficrescveij,"%3.0f",age );
                   6751:     for(i=1; i<=nlstate;i++)
                   6752:       for(j=1; j<=nlstate;j++){
1.222     brouard  6753:        cptj= (j-1)*nlstate+i;
                   6754:        for(i2=1; i2<=nlstate;i2++)
                   6755:          for(j2=1; j2<=nlstate;j2++){
                   6756:            cptj2= (j2-1)*nlstate+i2;
                   6757:            if(cptj2 <= cptj)
                   6758:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   6759:          }
1.126     brouard  6760:       }
                   6761:     fprintf(ficrescveij,"\n");
1.218     brouard  6762:                
1.126     brouard  6763:   }
                   6764:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   6765:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   6766:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   6767:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   6768:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6769:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6770:   printf("\n");
                   6771:   fprintf(ficlog,"\n");
1.218     brouard  6772:        
1.126     brouard  6773:   free_vector(xm,1,npar);
                   6774:   free_vector(xp,1,npar);
                   6775:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   6776:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   6777:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   6778: }
1.218     brouard  6779:  
1.126     brouard  6780: /************ Variance ******************/
1.235     brouard  6781:  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  6782:  {
1.279     brouard  6783:    /** Variance of health expectancies 
                   6784:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   6785:     * double **newm;
                   6786:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   6787:     */
1.218     brouard  6788:   
                   6789:    /* int movingaverage(); */
                   6790:    double **dnewm,**doldm;
                   6791:    double **dnewmp,**doldmp;
                   6792:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  6793:    int first=0;
1.218     brouard  6794:    int k;
                   6795:    double *xp;
1.279     brouard  6796:    double **gp, **gm;  /**< for var eij */
                   6797:    double ***gradg, ***trgradg; /**< for var eij */
                   6798:    double **gradgp, **trgradgp; /**< for var p point j */
                   6799:    double *gpp, *gmp; /**< for var p point j */
                   6800:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
1.218     brouard  6801:    double ***p3mat;
                   6802:    double age,agelim, hf;
                   6803:    /* double ***mobaverage; */
                   6804:    int theta;
                   6805:    char digit[4];
                   6806:    char digitp[25];
                   6807: 
                   6808:    char fileresprobmorprev[FILENAMELENGTH];
                   6809: 
                   6810:    if(popbased==1){
                   6811:      if(mobilav!=0)
                   6812:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   6813:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   6814:    }
                   6815:    else 
                   6816:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  6817: 
1.218     brouard  6818:    /* if (mobilav!=0) { */
                   6819:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6820:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   6821:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   6822:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   6823:    /*   } */
                   6824:    /* } */
                   6825: 
                   6826:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   6827:    sprintf(digit,"%-d",ij);
                   6828:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   6829:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   6830:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   6831:    strcat(fileresprobmorprev,fileresu);
                   6832:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   6833:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   6834:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   6835:    }
                   6836:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6837:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6838:    pstamp(ficresprobmorprev);
                   6839:    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  6840:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
1.337     brouard  6841: 
                   6842:    /* We use TinvDoQresult[nres][resultmodel[nres][j] we sort according to the equation model and the resultline: it is a choice */
                   6843:    /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ /\* To be done*\/ */
                   6844:    /*   fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   6845:    /* } */
                   6846:    for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */ /* To be done*/
1.344     brouard  6847:      /* fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); */
1.337     brouard  6848:      fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  6849:    }
1.337     brouard  6850:    /* for(j=1;j<=cptcoveff;j++)  */
                   6851:    /*   fprintf(ficresprobmorprev," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,TnsdVar[Tvaraff[j]])]); */
1.238     brouard  6852:    fprintf(ficresprobmorprev,"\n");
                   6853: 
1.218     brouard  6854:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   6855:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6856:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   6857:      for(i=1; i<=nlstate;i++)
                   6858:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   6859:    }  
                   6860:    fprintf(ficresprobmorprev,"\n");
                   6861:   
                   6862:    fprintf(ficgp,"\n# Routine varevsij");
                   6863:    fprintf(ficgp,"\nunset title \n");
                   6864:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   6865:    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");
                   6866:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  6867: 
1.218     brouard  6868:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6869:    pstamp(ficresvij);
                   6870:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   6871:    if(popbased==1)
                   6872:      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);
                   6873:    else
                   6874:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   6875:    fprintf(ficresvij,"# Age");
                   6876:    for(i=1; i<=nlstate;i++)
                   6877:      for(j=1; j<=nlstate;j++)
                   6878:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   6879:    fprintf(ficresvij,"\n");
                   6880: 
                   6881:    xp=vector(1,npar);
                   6882:    dnewm=matrix(1,nlstate,1,npar);
                   6883:    doldm=matrix(1,nlstate,1,nlstate);
                   6884:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   6885:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6886: 
                   6887:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   6888:    gpp=vector(nlstate+1,nlstate+ndeath);
                   6889:    gmp=vector(nlstate+1,nlstate+ndeath);
                   6890:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  6891:   
1.218     brouard  6892:    if(estepm < stepm){
                   6893:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   6894:    }
                   6895:    else  hstepm=estepm;   
                   6896:    /* For example we decided to compute the life expectancy with the smallest unit */
                   6897:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6898:       nhstepm is the number of hstepm from age to agelim 
                   6899:       nstepm is the number of stepm from age to agelim. 
                   6900:       Look at function hpijx to understand why because of memory size limitations, 
                   6901:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   6902:       survival function given by stepm (the optimization length). Unfortunately it
                   6903:       means that if the survival funtion is printed every two years of age and if
                   6904:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6905:       results. So we changed our mind and took the option of the best precision.
                   6906:    */
                   6907:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6908:    agelim = AGESUP;
                   6909:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6910:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6911:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6912:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6913:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   6914:      gp=matrix(0,nhstepm,1,nlstate);
                   6915:      gm=matrix(0,nhstepm,1,nlstate);
                   6916:                
                   6917:                
                   6918:      for(theta=1; theta <=npar; theta++){
                   6919:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   6920:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6921:        }
1.279     brouard  6922:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   6923:        * returns into prlim .
1.288     brouard  6924:        */
1.242     brouard  6925:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  6926: 
                   6927:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  6928:        if (popbased==1) {
                   6929:         if(mobilav ==0){
                   6930:           for(i=1; i<=nlstate;i++)
                   6931:             prlim[i][i]=probs[(int)age][i][ij];
                   6932:         }else{ /* mobilav */ 
                   6933:           for(i=1; i<=nlstate;i++)
                   6934:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6935:         }
                   6936:        }
1.295     brouard  6937:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  6938:        */                      
                   6939:        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  6940:        /**< 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  6941:        * at horizon h in state j including mortality.
                   6942:        */
1.218     brouard  6943:        for(j=1; j<= nlstate; j++){
                   6944:         for(h=0; h<=nhstepm; h++){
                   6945:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   6946:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6947:         }
                   6948:        }
1.279     brouard  6949:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  6950:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  6951:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  6952:        */
                   6953:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6954:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   6955:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  6956:        }
                   6957:        
                   6958:        /* Again with minus shift */
1.218     brouard  6959:                        
                   6960:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   6961:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6962: 
1.242     brouard  6963:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  6964:                        
                   6965:        if (popbased==1) {
                   6966:         if(mobilav ==0){
                   6967:           for(i=1; i<=nlstate;i++)
                   6968:             prlim[i][i]=probs[(int)age][i][ij];
                   6969:         }else{ /* mobilav */ 
                   6970:           for(i=1; i<=nlstate;i++)
                   6971:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6972:         }
                   6973:        }
                   6974:                        
1.235     brouard  6975:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  6976:                        
                   6977:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   6978:         for(h=0; h<=nhstepm; h++){
                   6979:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   6980:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6981:         }
                   6982:        }
                   6983:        /* This for computing probability of death (h=1 means
                   6984:          computed over hstepm matrices product = hstepm*stepm months) 
                   6985:          as a weighted average of prlim.
                   6986:        */
                   6987:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6988:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   6989:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   6990:        }    
1.279     brouard  6991:        /* end shifting computations */
                   6992: 
                   6993:        /**< Computing gradient matrix at horizon h 
                   6994:        */
1.218     brouard  6995:        for(j=1; j<= nlstate; j++) /* vareij */
                   6996:         for(h=0; h<=nhstepm; h++){
                   6997:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   6998:         }
1.279     brouard  6999:        /**< Gradient of overall mortality p.3 (or p.j) 
                   7000:        */
                   7001:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
1.218     brouard  7002:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   7003:        }
                   7004:                        
                   7005:      } /* End theta */
1.279     brouard  7006:      
                   7007:      /* We got the gradient matrix for each theta and state j */               
1.218     brouard  7008:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   7009:                
                   7010:      for(h=0; h<=nhstepm; h++) /* veij */
                   7011:        for(j=1; j<=nlstate;j++)
                   7012:         for(theta=1; theta <=npar; theta++)
                   7013:           trgradg[h][j][theta]=gradg[h][theta][j];
                   7014:                
                   7015:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   7016:        for(theta=1; theta <=npar; theta++)
                   7017:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  7018:      /**< as well as its transposed matrix 
                   7019:       */               
1.218     brouard  7020:                
                   7021:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   7022:      for(i=1;i<=nlstate;i++)
                   7023:        for(j=1;j<=nlstate;j++)
                   7024:         vareij[i][j][(int)age] =0.;
1.279     brouard  7025: 
                   7026:      /* Computing trgradg by matcov by gradg at age and summing over h
                   7027:       * and k (nhstepm) formula 15 of article
                   7028:       * Lievre-Brouard-Heathcote
                   7029:       */
                   7030:      
1.218     brouard  7031:      for(h=0;h<=nhstepm;h++){
                   7032:        for(k=0;k<=nhstepm;k++){
                   7033:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   7034:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   7035:         for(i=1;i<=nlstate;i++)
                   7036:           for(j=1;j<=nlstate;j++)
                   7037:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   7038:        }
                   7039:      }
                   7040:                
1.279     brouard  7041:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
                   7042:       * p.j overall mortality formula 49 but computed directly because
                   7043:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   7044:       * wix is independent of theta.
                   7045:       */
1.218     brouard  7046:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   7047:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   7048:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   7049:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   7050:         varppt[j][i]=doldmp[j][i];
                   7051:      /* end ppptj */
                   7052:      /*  x centered again */
                   7053:                
1.242     brouard  7054:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  7055:                
                   7056:      if (popbased==1) {
                   7057:        if(mobilav ==0){
                   7058:         for(i=1; i<=nlstate;i++)
                   7059:           prlim[i][i]=probs[(int)age][i][ij];
                   7060:        }else{ /* mobilav */ 
                   7061:         for(i=1; i<=nlstate;i++)
                   7062:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   7063:        }
                   7064:      }
                   7065:                
                   7066:      /* This for computing probability of death (h=1 means
                   7067:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   7068:        as a weighted average of prlim.
                   7069:      */
1.235     brouard  7070:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  7071:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   7072:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   7073:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   7074:      }    
                   7075:      /* end probability of death */
                   7076:                
                   7077:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   7078:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   7079:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   7080:        for(i=1; i<=nlstate;i++){
                   7081:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   7082:        }
                   7083:      } 
                   7084:      fprintf(ficresprobmorprev,"\n");
                   7085:                
                   7086:      fprintf(ficresvij,"%.0f ",age );
                   7087:      for(i=1; i<=nlstate;i++)
                   7088:        for(j=1; j<=nlstate;j++){
                   7089:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   7090:        }
                   7091:      fprintf(ficresvij,"\n");
                   7092:      free_matrix(gp,0,nhstepm,1,nlstate);
                   7093:      free_matrix(gm,0,nhstepm,1,nlstate);
                   7094:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   7095:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   7096:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7097:    } /* End age */
                   7098:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   7099:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   7100:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   7101:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   7102:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   7103:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   7104:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   7105:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   7106:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   7107:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   7108:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   7109:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   7110:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   7111:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   7112:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   7113:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   7114:    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);
                   7115:    /*  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  7116:     */
1.218     brouard  7117:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   7118:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  7119: 
1.218     brouard  7120:    free_vector(xp,1,npar);
                   7121:    free_matrix(doldm,1,nlstate,1,nlstate);
                   7122:    free_matrix(dnewm,1,nlstate,1,npar);
                   7123:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7124:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   7125:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7126:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7127:    fclose(ficresprobmorprev);
                   7128:    fflush(ficgp);
                   7129:    fflush(fichtm); 
                   7130:  }  /* end varevsij */
1.126     brouard  7131: 
                   7132: /************ Variance of prevlim ******************/
1.269     brouard  7133:  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  7134: {
1.205     brouard  7135:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  7136:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  7137: 
1.268     brouard  7138:   double **dnewmpar,**doldm;
1.126     brouard  7139:   int i, j, nhstepm, hstepm;
                   7140:   double *xp;
                   7141:   double *gp, *gm;
                   7142:   double **gradg, **trgradg;
1.208     brouard  7143:   double **mgm, **mgp;
1.126     brouard  7144:   double age,agelim;
                   7145:   int theta;
                   7146:   
                   7147:   pstamp(ficresvpl);
1.288     brouard  7148:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  7149:   fprintf(ficresvpl,"# Age ");
                   7150:   if(nresult >=1)
                   7151:     fprintf(ficresvpl," Result# ");
1.126     brouard  7152:   for(i=1; i<=nlstate;i++)
                   7153:       fprintf(ficresvpl," %1d-%1d",i,i);
                   7154:   fprintf(ficresvpl,"\n");
                   7155: 
                   7156:   xp=vector(1,npar);
1.268     brouard  7157:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  7158:   doldm=matrix(1,nlstate,1,nlstate);
                   7159:   
                   7160:   hstepm=1*YEARM; /* Every year of age */
                   7161:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   7162:   agelim = AGESUP;
                   7163:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   7164:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7165:     if (stepm >= YEARM) hstepm=1;
                   7166:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7167:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  7168:     mgp=matrix(1,npar,1,nlstate);
                   7169:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  7170:     gp=vector(1,nlstate);
                   7171:     gm=vector(1,nlstate);
                   7172: 
                   7173:     for(theta=1; theta <=npar; theta++){
                   7174:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   7175:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7176:       }
1.288     brouard  7177:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   7178:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   7179:       /* else */
                   7180:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  7181:       for(i=1;i<=nlstate;i++){
1.126     brouard  7182:        gp[i] = prlim[i][i];
1.208     brouard  7183:        mgp[theta][i] = prlim[i][i];
                   7184:       }
1.126     brouard  7185:       for(i=1; i<=npar; i++) /* Computes gradient */
                   7186:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  7187:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   7188:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   7189:       /* else */
                   7190:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  7191:       for(i=1;i<=nlstate;i++){
1.126     brouard  7192:        gm[i] = prlim[i][i];
1.208     brouard  7193:        mgm[theta][i] = prlim[i][i];
                   7194:       }
1.126     brouard  7195:       for(i=1;i<=nlstate;i++)
                   7196:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  7197:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  7198:     } /* End theta */
                   7199: 
                   7200:     trgradg =matrix(1,nlstate,1,npar);
                   7201: 
                   7202:     for(j=1; j<=nlstate;j++)
                   7203:       for(theta=1; theta <=npar; theta++)
                   7204:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  7205:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7206:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7207:     /*   for(j=1; j<=nlstate;j++){ */
                   7208:     /*         printf(" %d ",j); */
                   7209:     /*         for(theta=1; theta <=npar; theta++) */
                   7210:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7211:     /*         printf("\n "); */
                   7212:     /*   } */
                   7213:     /* } */
                   7214:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7215:     /*   printf("\n gradg %d ",(int)age); */
                   7216:     /*   for(j=1; j<=nlstate;j++){ */
                   7217:     /*         printf("%d ",j); */
                   7218:     /*         for(theta=1; theta <=npar; theta++) */
                   7219:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7220:     /*         printf("\n "); */
                   7221:     /*   } */
                   7222:     /* } */
1.126     brouard  7223: 
                   7224:     for(i=1;i<=nlstate;i++)
                   7225:       varpl[i][(int)age] =0.;
1.209     brouard  7226:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  7227:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7228:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  7229:     }else{
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:     }
1.126     brouard  7233:     for(i=1;i<=nlstate;i++)
                   7234:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7235: 
                   7236:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  7237:     if(nresult >=1)
                   7238:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  7239:     for(i=1; i<=nlstate;i++){
1.126     brouard  7240:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  7241:       /* for(j=1;j<=nlstate;j++) */
                   7242:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   7243:     }
1.126     brouard  7244:     fprintf(ficresvpl,"\n");
                   7245:     free_vector(gp,1,nlstate);
                   7246:     free_vector(gm,1,nlstate);
1.208     brouard  7247:     free_matrix(mgm,1,npar,1,nlstate);
                   7248:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  7249:     free_matrix(gradg,1,npar,1,nlstate);
                   7250:     free_matrix(trgradg,1,nlstate,1,npar);
                   7251:   } /* End age */
                   7252: 
                   7253:   free_vector(xp,1,npar);
                   7254:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  7255:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   7256: 
                   7257: }
                   7258: 
                   7259: 
                   7260: /************ Variance of backprevalence limit ******************/
1.269     brouard  7261:  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  7262: {
                   7263:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   7264:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   7265: 
                   7266:   double **dnewmpar,**doldm;
                   7267:   int i, j, nhstepm, hstepm;
                   7268:   double *xp;
                   7269:   double *gp, *gm;
                   7270:   double **gradg, **trgradg;
                   7271:   double **mgm, **mgp;
                   7272:   double age,agelim;
                   7273:   int theta;
                   7274:   
                   7275:   pstamp(ficresvbl);
                   7276:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   7277:   fprintf(ficresvbl,"# Age ");
                   7278:   if(nresult >=1)
                   7279:     fprintf(ficresvbl," Result# ");
                   7280:   for(i=1; i<=nlstate;i++)
                   7281:       fprintf(ficresvbl," %1d-%1d",i,i);
                   7282:   fprintf(ficresvbl,"\n");
                   7283: 
                   7284:   xp=vector(1,npar);
                   7285:   dnewmpar=matrix(1,nlstate,1,npar);
                   7286:   doldm=matrix(1,nlstate,1,nlstate);
                   7287:   
                   7288:   hstepm=1*YEARM; /* Every year of age */
                   7289:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   7290:   agelim = AGEINF;
                   7291:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   7292:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7293:     if (stepm >= YEARM) hstepm=1;
                   7294:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7295:     gradg=matrix(1,npar,1,nlstate);
                   7296:     mgp=matrix(1,npar,1,nlstate);
                   7297:     mgm=matrix(1,npar,1,nlstate);
                   7298:     gp=vector(1,nlstate);
                   7299:     gm=vector(1,nlstate);
                   7300: 
                   7301:     for(theta=1; theta <=npar; theta++){
                   7302:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   7303:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7304:       }
                   7305:       if(mobilavproj > 0 )
                   7306:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7307:       else
                   7308:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7309:       for(i=1;i<=nlstate;i++){
                   7310:        gp[i] = bprlim[i][i];
                   7311:        mgp[theta][i] = bprlim[i][i];
                   7312:       }
                   7313:      for(i=1; i<=npar; i++) /* Computes gradient */
                   7314:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   7315:        if(mobilavproj > 0 )
                   7316:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7317:        else
                   7318:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7319:       for(i=1;i<=nlstate;i++){
                   7320:        gm[i] = bprlim[i][i];
                   7321:        mgm[theta][i] = bprlim[i][i];
                   7322:       }
                   7323:       for(i=1;i<=nlstate;i++)
                   7324:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   7325:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   7326:     } /* End theta */
                   7327: 
                   7328:     trgradg =matrix(1,nlstate,1,npar);
                   7329: 
                   7330:     for(j=1; j<=nlstate;j++)
                   7331:       for(theta=1; theta <=npar; theta++)
                   7332:        trgradg[j][theta]=gradg[theta][j];
                   7333:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7334:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7335:     /*   for(j=1; j<=nlstate;j++){ */
                   7336:     /*         printf(" %d ",j); */
                   7337:     /*         for(theta=1; theta <=npar; theta++) */
                   7338:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7339:     /*         printf("\n "); */
                   7340:     /*   } */
                   7341:     /* } */
                   7342:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7343:     /*   printf("\n gradg %d ",(int)age); */
                   7344:     /*   for(j=1; j<=nlstate;j++){ */
                   7345:     /*         printf("%d ",j); */
                   7346:     /*         for(theta=1; theta <=npar; theta++) */
                   7347:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7348:     /*         printf("\n "); */
                   7349:     /*   } */
                   7350:     /* } */
                   7351: 
                   7352:     for(i=1;i<=nlstate;i++)
                   7353:       varbpl[i][(int)age] =0.;
                   7354:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   7355:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7356:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7357:     }else{
                   7358:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7359:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7360:     }
                   7361:     for(i=1;i<=nlstate;i++)
                   7362:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7363: 
                   7364:     fprintf(ficresvbl,"%.0f ",age );
                   7365:     if(nresult >=1)
                   7366:       fprintf(ficresvbl,"%d ",nres );
                   7367:     for(i=1; i<=nlstate;i++)
                   7368:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   7369:     fprintf(ficresvbl,"\n");
                   7370:     free_vector(gp,1,nlstate);
                   7371:     free_vector(gm,1,nlstate);
                   7372:     free_matrix(mgm,1,npar,1,nlstate);
                   7373:     free_matrix(mgp,1,npar,1,nlstate);
                   7374:     free_matrix(gradg,1,npar,1,nlstate);
                   7375:     free_matrix(trgradg,1,nlstate,1,npar);
                   7376:   } /* End age */
                   7377: 
                   7378:   free_vector(xp,1,npar);
                   7379:   free_matrix(doldm,1,nlstate,1,npar);
                   7380:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  7381: 
                   7382: }
                   7383: 
                   7384: /************ Variance of one-step probabilities  ******************/
                   7385: 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  7386:  {
                   7387:    int i, j=0,  k1, l1, tj;
                   7388:    int k2, l2, j1,  z1;
                   7389:    int k=0, l;
                   7390:    int first=1, first1, first2;
1.326     brouard  7391:    int nres=0; /* New */
1.222     brouard  7392:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   7393:    double **dnewm,**doldm;
                   7394:    double *xp;
                   7395:    double *gp, *gm;
                   7396:    double **gradg, **trgradg;
                   7397:    double **mu;
                   7398:    double age, cov[NCOVMAX+1];
                   7399:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   7400:    int theta;
                   7401:    char fileresprob[FILENAMELENGTH];
                   7402:    char fileresprobcov[FILENAMELENGTH];
                   7403:    char fileresprobcor[FILENAMELENGTH];
                   7404:    double ***varpij;
                   7405: 
                   7406:    strcpy(fileresprob,"PROB_"); 
                   7407:    strcat(fileresprob,fileres);
                   7408:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   7409:      printf("Problem with resultfile: %s\n", fileresprob);
                   7410:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   7411:    }
                   7412:    strcpy(fileresprobcov,"PROBCOV_"); 
                   7413:    strcat(fileresprobcov,fileresu);
                   7414:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   7415:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   7416:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   7417:    }
                   7418:    strcpy(fileresprobcor,"PROBCOR_"); 
                   7419:    strcat(fileresprobcor,fileresu);
                   7420:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   7421:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   7422:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   7423:    }
                   7424:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7425:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7426:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7427:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7428:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7429:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7430:    pstamp(ficresprob);
                   7431:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   7432:    fprintf(ficresprob,"# Age");
                   7433:    pstamp(ficresprobcov);
                   7434:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   7435:    fprintf(ficresprobcov,"# Age");
                   7436:    pstamp(ficresprobcor);
                   7437:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   7438:    fprintf(ficresprobcor,"# Age");
1.126     brouard  7439: 
                   7440: 
1.222     brouard  7441:    for(i=1; i<=nlstate;i++)
                   7442:      for(j=1; j<=(nlstate+ndeath);j++){
                   7443:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   7444:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   7445:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   7446:      }  
                   7447:    /* fprintf(ficresprob,"\n");
                   7448:       fprintf(ficresprobcov,"\n");
                   7449:       fprintf(ficresprobcor,"\n");
                   7450:    */
                   7451:    xp=vector(1,npar);
                   7452:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7453:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7454:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   7455:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   7456:    first=1;
                   7457:    fprintf(ficgp,"\n# Routine varprob");
                   7458:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   7459:    fprintf(fichtm,"\n");
                   7460: 
1.288     brouard  7461:    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  7462:    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);
                   7463:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  7464: and drawn. It helps understanding how is the covariance between two incidences.\
                   7465:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  7466:    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  7467: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   7468: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   7469: standard deviations wide on each axis. <br>\
                   7470:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   7471:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   7472: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   7473: 
1.222     brouard  7474:    cov[1]=1;
                   7475:    /* tj=cptcoveff; */
1.225     brouard  7476:    tj = (int) pow(2,cptcoveff);
1.222     brouard  7477:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   7478:    j1=0;
1.332     brouard  7479: 
                   7480:    for(nres=1;nres <=nresult; nres++){ /* For each resultline */
                   7481:    for(j1=1; j1<=tj;j1++){ /* For any combination of dummy covariates, fixed and varying */
1.342     brouard  7482:      /* 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  7483:      if(tj != 1 && TKresult[nres]!= j1)
                   7484:        continue;
                   7485: 
                   7486:    /* for(j1=1; j1<=tj;j1++){  /\* For each valid combination of covariates or only once*\/ */
                   7487:      /* for(nres=1;nres <=1; nres++){ /\* For each resultline *\/ */
                   7488:      /* /\* for(nres=1;nres <=nresult; nres++){ /\\* For each resultline *\\/ *\/ */
1.222     brouard  7489:      if  (cptcovn>0) {
1.334     brouard  7490:        fprintf(ficresprob, "\n#********** Variable ");
                   7491:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   7492:        fprintf(ficgp, "\n#********** Variable ");
                   7493:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   7494:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   7495: 
                   7496:        /* Including quantitative variables of the resultline to be done */
                   7497:        for (z1=1; z1<=cptcovs; z1++){ /* Loop on each variable of this resultline  */
1.343     brouard  7498:         /* printf("Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model); */
1.338     brouard  7499:         fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model);
                   7500:         /* 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  7501:         if(Dummy[modelresult[nres][z1]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to z1 in resultline  */
                   7502:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed referenced to model equation */
                   7503:             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  */
                   7504:             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  */
                   7505:             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  */
                   7506:             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  */
                   7507:             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  */
                   7508:             fprintf(ficresprob,"fixed ");
                   7509:             fprintf(ficresprobcov,"fixed ");
                   7510:             fprintf(ficgp,"fixed ");
                   7511:             fprintf(fichtmcov,"fixed ");
                   7512:             fprintf(ficresprobcor,"fixed ");
                   7513:           }else{
                   7514:             fprintf(ficresprob,"varyi ");
                   7515:             fprintf(ficresprobcov,"varyi ");
                   7516:             fprintf(ficgp,"varyi ");
                   7517:             fprintf(fichtmcov,"varyi ");
                   7518:             fprintf(ficresprobcor,"varyi ");
                   7519:           }
                   7520:         }else if(Dummy[modelresult[nres][z1]]==1){ /* Quanti variable */
                   7521:           /* For each selected (single) quantitative value */
1.337     brouard  7522:           fprintf(ficresprob," V%d=%lg ",Tvqresult[nres][z1],Tqresult[nres][z1]);
1.334     brouard  7523:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed */
                   7524:             fprintf(ficresprob,"fixed ");
                   7525:             fprintf(ficresprobcov,"fixed ");
                   7526:             fprintf(ficgp,"fixed ");
                   7527:             fprintf(fichtmcov,"fixed ");
                   7528:             fprintf(ficresprobcor,"fixed ");
                   7529:           }else{
                   7530:             fprintf(ficresprob,"varyi ");
                   7531:             fprintf(ficresprobcov,"varyi ");
                   7532:             fprintf(ficgp,"varyi ");
                   7533:             fprintf(fichtmcov,"varyi ");
                   7534:             fprintf(ficresprobcor,"varyi ");
                   7535:           }
                   7536:         }else{
                   7537:           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 */
                   7538:           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 */
                   7539:           exit(1);
                   7540:         }
                   7541:        } /* End loop on variable of this resultline */
                   7542:        /* for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]); */
1.222     brouard  7543:        fprintf(ficresprob, "**********\n#\n");
                   7544:        fprintf(ficresprobcov, "**********\n#\n");
                   7545:        fprintf(ficgp, "**********\n#\n");
                   7546:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   7547:        fprintf(ficresprobcor, "**********\n#");    
                   7548:        if(invalidvarcomb[j1]){
                   7549:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   7550:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   7551:         continue;
                   7552:        }
                   7553:      }
                   7554:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   7555:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7556:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   7557:      gm=vector(1,(nlstate)*(nlstate+ndeath));
1.334     brouard  7558:      for (age=bage; age<=fage; age ++){ /* Fo each age we feed the model equation with covariates, using precov as in hpxij() ? */
1.222     brouard  7559:        cov[2]=age;
                   7560:        if(nagesqr==1)
                   7561:         cov[3]= age*age;
1.334     brouard  7562:        /* New code end of combination but for each resultline */
                   7563:        for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   7564:         if(Typevar[k1]==1){ /* A product with age */
                   7565:           cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.326     brouard  7566:         }else{
1.334     brouard  7567:           cov[2+nagesqr+k1]=precov[nres][k1];
1.326     brouard  7568:         }
1.334     brouard  7569:        }/* End of loop on model equation */
                   7570: /* Old code */
                   7571:        /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   7572:        /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)]; *\/ */
                   7573:        /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   7574:        /*       /\* Here comes the value of the covariate 'j1' after renumbering k with single dummy covariates *\/ */
                   7575:        /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(j1,TnsdVar[TvarsD[k]])]; */
                   7576:        /*       /\*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*\//\* j1 1 2 3 4 */
                   7577:        /*                                                                  * 1  1 1 1 1 */
                   7578:        /*                                                                  * 2  2 1 1 1 */
                   7579:        /*                                                                  * 3  1 2 1 1 */
                   7580:        /*                                                                  *\/ */
                   7581:        /*       /\* nbcode[1][1]=0 nbcode[1][2]=1;*\/ */
                   7582:        /* } */
                   7583:        /* /\* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   7584:        /* /\* ) p nbcode[Tvar[Tage[k]]][(1 & (ij-1) >> (k-1))+1] *\/ */
                   7585:        /* /\*for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; *\/ */
                   7586:        /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   7587:        /*       if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   7588:        /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(j1,TnsdVar[Tvar[Tage[k]]])]*cov[2]; */
                   7589:        /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7590:        /*       } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   7591:        /*         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]); */
                   7592:        /*         /\* cov[2+nagesqr+Tage[k]]=meanq[k]/idq[k]*cov[2];/\\* Using the mean of quantitative variable Tvar[Tage[k]] /\\* Tqresult[nres][k]; *\\/ *\/ */
                   7593:        /*         /\* exit(1); *\/ */
                   7594:        /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   7595:        /*       } */
                   7596:        /*       /\* cov[2+Tage[k]+nagesqr]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7597:        /* } */
                   7598:        /* for (k=1; k<=cptcovprod;k++){/\* For product without age *\/ */
                   7599:        /*       if(Dummy[Tvard[k][1]]==0){ */
                   7600:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7601:        /*           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]])]; */
                   7602:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7603:        /*         }else{ /\* Should we use the mean of the quantitative variables? *\/ */
                   7604:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,TnsdVar[Tvard[k][1]])] * Tqresult[nres][resultmodel[nres][k]]; */
                   7605:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   7606:        /*         } */
                   7607:        /*       }else{ */
                   7608:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7609:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(j1,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][TnsdVar[Tvard[k][1]]]; */
                   7610:        /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   7611:        /*         }else{ */
                   7612:        /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][TnsdVar[Tvard[k][1]]]*  Tqinvresult[nres][TnsdVar[Tvard[k][2]]]; */
                   7613:        /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   7614:        /*         } */
                   7615:        /*       } */
                   7616:        /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7617:        /* } */                 
1.326     brouard  7618: /* For each age and combination of dummy covariates we slightly move the parameters of delti in order to get the gradient*/                    
1.222     brouard  7619:        for(theta=1; theta <=npar; theta++){
                   7620:         for(i=1; i<=npar; i++)
                   7621:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  7622:                                
1.222     brouard  7623:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  7624:                                
1.222     brouard  7625:         k=0;
                   7626:         for(i=1; i<= (nlstate); i++){
                   7627:           for(j=1; j<=(nlstate+ndeath);j++){
                   7628:             k=k+1;
                   7629:             gp[k]=pmmij[i][j];
                   7630:           }
                   7631:         }
1.220     brouard  7632:                                
1.222     brouard  7633:         for(i=1; i<=npar; i++)
                   7634:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  7635:                                
1.222     brouard  7636:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   7637:         k=0;
                   7638:         for(i=1; i<=(nlstate); i++){
                   7639:           for(j=1; j<=(nlstate+ndeath);j++){
                   7640:             k=k+1;
                   7641:             gm[k]=pmmij[i][j];
                   7642:           }
                   7643:         }
1.220     brouard  7644:                                
1.222     brouard  7645:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   7646:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   7647:        }
1.126     brouard  7648: 
1.222     brouard  7649:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   7650:         for(theta=1; theta <=npar; theta++)
                   7651:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  7652:                        
1.222     brouard  7653:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   7654:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  7655:                        
1.222     brouard  7656:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  7657:                        
1.222     brouard  7658:        k=0;
                   7659:        for(i=1; i<=(nlstate); i++){
                   7660:         for(j=1; j<=(nlstate+ndeath);j++){
                   7661:           k=k+1;
                   7662:           mu[k][(int) age]=pmmij[i][j];
                   7663:         }
                   7664:        }
                   7665:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   7666:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   7667:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  7668:                        
1.222     brouard  7669:        /*printf("\n%d ",(int)age);
                   7670:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7671:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7672:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7673:         }*/
1.220     brouard  7674:                        
1.222     brouard  7675:        fprintf(ficresprob,"\n%d ",(int)age);
                   7676:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   7677:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  7678:                        
1.222     brouard  7679:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   7680:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   7681:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7682:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   7683:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   7684:        }
                   7685:        i=0;
                   7686:        for (k=1; k<=(nlstate);k++){
                   7687:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   7688:           i++;
                   7689:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   7690:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   7691:           for (j=1; j<=i;j++){
                   7692:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   7693:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   7694:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   7695:           }
                   7696:         }
                   7697:        }/* end of loop for state */
                   7698:      } /* end of loop for age */
                   7699:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7700:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7701:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7702:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7703:     
                   7704:      /* Confidence intervalle of pij  */
                   7705:      /*
                   7706:        fprintf(ficgp,"\nunset parametric;unset label");
                   7707:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   7708:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   7709:        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);
                   7710:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   7711:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   7712:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   7713:      */
                   7714:                
                   7715:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   7716:      first1=1;first2=2;
                   7717:      for (k2=1; k2<=(nlstate);k2++){
                   7718:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   7719:         if(l2==k2) continue;
                   7720:         j=(k2-1)*(nlstate+ndeath)+l2;
                   7721:         for (k1=1; k1<=(nlstate);k1++){
                   7722:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   7723:             if(l1==k1) continue;
                   7724:             i=(k1-1)*(nlstate+ndeath)+l1;
                   7725:             if(i<=j) continue;
                   7726:             for (age=bage; age<=fage; age ++){ 
                   7727:               if ((int)age %5==0){
                   7728:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   7729:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7730:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7731:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   7732:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   7733:                 c12=cv12/sqrt(v1*v2);
                   7734:                 /* Computing eigen value of matrix of covariance */
                   7735:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7736:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7737:                 if ((lc2 <0) || (lc1 <0) ){
                   7738:                   if(first2==1){
                   7739:                     first1=0;
                   7740:                     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);
                   7741:                   }
                   7742:                   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);
                   7743:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   7744:                   /* lc2=fabs(lc2); */
                   7745:                 }
1.220     brouard  7746:                                                                
1.222     brouard  7747:                 /* Eigen vectors */
1.280     brouard  7748:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   7749:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7750:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7751:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   7752:                 }else
                   7753:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  7754:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   7755:                 v21=(lc1-v1)/cv12*v11;
                   7756:                 v12=-v21;
                   7757:                 v22=v11;
                   7758:                 tnalp=v21/v11;
                   7759:                 if(first1==1){
                   7760:                   first1=0;
                   7761:                   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);
                   7762:                 }
                   7763:                 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);
                   7764:                 /*printf(fignu*/
                   7765:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   7766:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   7767:                 if(first==1){
                   7768:                   first=0;
                   7769:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   7770:                   fprintf(ficgp,"\nset parametric;unset label");
                   7771:                   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);
                   7772:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  7773:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  7774:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  7775: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  7776:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   7777:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7778:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7779:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   7780:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7781:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7782:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7783:                   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  7784:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   7785:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  7786:                 }else{
                   7787:                   first=0;
                   7788:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   7789:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7790:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7791:                   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  7792:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   7793:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  7794:                 }/* if first */
                   7795:               } /* age mod 5 */
                   7796:             } /* end loop age */
                   7797:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7798:             first=1;
                   7799:           } /*l12 */
                   7800:         } /* k12 */
                   7801:        } /*l1 */
                   7802:      }/* k1 */
1.332     brouard  7803:    }  /* loop on combination of covariates j1 */
1.326     brouard  7804:    } /* loop on nres */
1.222     brouard  7805:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   7806:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   7807:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7808:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   7809:    free_vector(xp,1,npar);
                   7810:    fclose(ficresprob);
                   7811:    fclose(ficresprobcov);
                   7812:    fclose(ficresprobcor);
                   7813:    fflush(ficgp);
                   7814:    fflush(fichtmcov);
                   7815:  }
1.126     brouard  7816: 
                   7817: 
                   7818: /******************* Printing html file ***********/
1.201     brouard  7819: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  7820:                  int lastpass, int stepm, int weightopt, char model[],\
                   7821:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  7822:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   7823:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   7824:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.237     brouard  7825:   int jj1, k1, i1, cpt, k4, nres;
1.319     brouard  7826:   /* In fact some results are already printed in fichtm which is open */
1.126     brouard  7827:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   7828:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   7829: </ul>");
1.319     brouard  7830: /*    fprintf(fichtm,"<ul><li> model=1+age+%s\n \ */
                   7831: /* </ul>", model); */
1.214     brouard  7832:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   7833:    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",
                   7834:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
1.332     brouard  7835:    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  7836:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   7837:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  7838:    fprintf(fichtm,"\
                   7839:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  7840:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  7841:    fprintf(fichtm,"\
1.217     brouard  7842:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   7843:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   7844:    fprintf(fichtm,"\
1.288     brouard  7845:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7846:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  7847:    fprintf(fichtm,"\
1.288     brouard  7848:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  7849:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   7850:    fprintf(fichtm,"\
1.211     brouard  7851:  - (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  7852:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7853:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  7854:    if(prevfcast==1){
                   7855:      fprintf(fichtm,"\
                   7856:  - Prevalence projections by age and states:                           \
1.201     brouard  7857:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  7858:    }
1.126     brouard  7859: 
                   7860: 
1.225     brouard  7861:    m=pow(2,cptcoveff);
1.222     brouard  7862:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7863: 
1.317     brouard  7864:    fprintf(fichtm," \n<ul><li><b>Graphs (first order)</b></li><p>");
1.264     brouard  7865: 
                   7866:    jj1=0;
                   7867: 
                   7868:    fprintf(fichtm," \n<ul>");
1.337     brouard  7869:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   7870:      /* k1=nres; */
1.338     brouard  7871:      k1=TKresult[nres];
                   7872:      if(TKresult[nres]==0)k1=1; /* To be checked for no result */
1.337     brouard  7873:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   7874:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   7875:    /*     continue; */
1.264     brouard  7876:      jj1++;
                   7877:      if (cptcovn > 0) {
                   7878:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
1.337     brouard  7879:        for (cpt=1; cpt<=cptcovs;cpt++){ /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   7880:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  7881:        }
1.337     brouard  7882:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   7883:        /*       fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   7884:        /* } */
                   7885:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   7886:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   7887:        /* } */
1.264     brouard  7888:        fprintf(fichtm,"\">");
                   7889:        
                   7890:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   7891:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  7892:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   7893:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  7894:        }
1.337     brouard  7895:        /* fprintf(fichtm,"************ Results for covariates"); */
                   7896:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   7897:        /*       fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   7898:        /* } */
                   7899:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   7900:        /*       fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   7901:        /* } */
1.264     brouard  7902:        if(invalidvarcomb[k1]){
                   7903:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   7904:         continue;
                   7905:        }
                   7906:        fprintf(fichtm,"</a></li>");
                   7907:      } /* cptcovn >0 */
                   7908:    }
1.317     brouard  7909:    fprintf(fichtm," \n</ul>");
1.264     brouard  7910: 
1.222     brouard  7911:    jj1=0;
1.237     brouard  7912: 
1.337     brouard  7913:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   7914:      /* k1=nres; */
1.338     brouard  7915:      k1=TKresult[nres];
                   7916:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  7917:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   7918:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   7919:    /*     continue; */
1.220     brouard  7920: 
1.222     brouard  7921:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7922:      jj1++;
                   7923:      if (cptcovn > 0) {
1.264     brouard  7924:        fprintf(fichtm,"\n<p><a name=\"rescov");
1.337     brouard  7925:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   7926:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  7927:        }
1.337     brouard  7928:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   7929:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   7930:        /* } */
1.264     brouard  7931:        fprintf(fichtm,"\"</a>");
                   7932:  
1.222     brouard  7933:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  7934:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   7935:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   7936:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  7937:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   7938:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  7939:        }
1.230     brouard  7940:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.338     brouard  7941:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.222     brouard  7942:        if(invalidvarcomb[k1]){
                   7943:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   7944:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   7945:         continue;
                   7946:        }
                   7947:      }
                   7948:      /* aij, bij */
1.259     brouard  7949:      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  7950: <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  7951:      /* Pij */
1.241     brouard  7952:      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> \
                   7953: <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  7954:      /* Quasi-incidences */
                   7955:      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  7956:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  7957:  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  7958: 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> \
                   7959: <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  7960:      /* Survival functions (period) in state j */
                   7961:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  7962:        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);
                   7963:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   7964:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.222     brouard  7965:      }
                   7966:      /* State specific survival functions (period) */
                   7967:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  7968:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
                   7969:  And probability to be observed in various states (up to %d) being in state %d at different ages.      \
1.329     brouard  7970:  <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);
                   7971:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   7972:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.222     brouard  7973:      }
1.288     brouard  7974:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  7975:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  7976:        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  7977:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
1.329     brouard  7978:       fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.222     brouard  7979:      }
1.296     brouard  7980:      if(prevbcast==1){
1.288     brouard  7981:        /* Backward prevalence in each health state */
1.222     brouard  7982:        for(cpt=1; cpt<=nlstate;cpt++){
1.338     brouard  7983:         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);
                   7984:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJB_"),subdirf2(optionfilefiname,"PIJB_"));
                   7985:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.222     brouard  7986:        }
1.217     brouard  7987:      }
1.222     brouard  7988:      if(prevfcast==1){
1.288     brouard  7989:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  7990:        for(cpt=1; cpt<=nlstate;cpt++){
1.314     brouard  7991:         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);
                   7992:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
                   7993:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
                   7994:                 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  7995:        }
                   7996:      }
1.296     brouard  7997:      if(prevbcast==1){
1.268     brouard  7998:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   7999:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  8000:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
                   8001:  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 \
                   8002:  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  8003: 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);
                   8004:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
                   8005:         fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
1.268     brouard  8006:        }
                   8007:      }
1.220     brouard  8008:         
1.222     brouard  8009:      for(cpt=1; cpt<=nlstate;cpt++) {
1.314     brouard  8010:        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);
                   8011:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
                   8012:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
1.222     brouard  8013:      }
                   8014:      /* } /\* end i1 *\/ */
1.337     brouard  8015:    }/* End k1=nres */
1.222     brouard  8016:    fprintf(fichtm,"</ul>");
1.126     brouard  8017: 
1.222     brouard  8018:    fprintf(fichtm,"\
1.126     brouard  8019: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  8020:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  8021:  - 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  8022: But because parameters are usually highly correlated (a higher incidence of disability \
                   8023: and a higher incidence of recovery can give very close observed transition) it might \
                   8024: be very useful to look not only at linear confidence intervals estimated from the \
                   8025: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   8026: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   8027: covariance matrix of the one-step probabilities. \
                   8028: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  8029: 
1.222     brouard  8030:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   8031:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   8032:    fprintf(fichtm,"\
1.126     brouard  8033:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  8034:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  8035: 
1.222     brouard  8036:    fprintf(fichtm,"\
1.126     brouard  8037:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  8038:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   8039:    fprintf(fichtm,"\
1.126     brouard  8040:  - 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): \
                   8041:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  8042:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  8043:    fprintf(fichtm,"\
1.126     brouard  8044:  - (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): \
                   8045:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  8046:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  8047:    fprintf(fichtm,"\
1.288     brouard  8048:  - 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  8049:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   8050:    fprintf(fichtm,"\
1.128     brouard  8051:  - 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  8052:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   8053:    fprintf(fichtm,"\
1.288     brouard  8054:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  8055:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  8056: 
                   8057: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   8058: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   8059: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   8060: /*     <br>",fileres,fileres,fileres,fileres); */
                   8061: /*  else  */
1.338     brouard  8062: /*    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  8063:    fflush(fichtm);
1.126     brouard  8064: 
1.225     brouard  8065:    m=pow(2,cptcoveff);
1.222     brouard  8066:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  8067: 
1.317     brouard  8068:    fprintf(fichtm," <ul><li><b>Graphs (second order)</b></li><p>");
                   8069: 
                   8070:   jj1=0;
                   8071: 
                   8072:    fprintf(fichtm," \n<ul>");
1.337     brouard  8073:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8074:      /* k1=nres; */
1.338     brouard  8075:      k1=TKresult[nres];
1.337     brouard  8076:      /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   8077:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8078:      /*   continue; */
1.317     brouard  8079:      jj1++;
                   8080:      if (cptcovn > 0) {
                   8081:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescovsecond");
1.337     brouard  8082:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8083:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8084:        }
                   8085:        fprintf(fichtm,"\">");
                   8086:        
                   8087:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   8088:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  8089:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8090:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8091:        }
                   8092:        if(invalidvarcomb[k1]){
                   8093:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   8094:         continue;
                   8095:        }
                   8096:        fprintf(fichtm,"</a></li>");
                   8097:      } /* cptcovn >0 */
1.337     brouard  8098:    } /* End nres */
1.317     brouard  8099:    fprintf(fichtm," \n</ul>");
                   8100: 
1.222     brouard  8101:    jj1=0;
1.237     brouard  8102: 
1.241     brouard  8103:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8104:      /* k1=nres; */
1.338     brouard  8105:      k1=TKresult[nres];
                   8106:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8107:      /* for(k1=1; k1<=m;k1++){ */
                   8108:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8109:      /*   continue; */
1.222     brouard  8110:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   8111:      jj1++;
1.126     brouard  8112:      if (cptcovn > 0) {
1.317     brouard  8113:        fprintf(fichtm,"\n<p><a name=\"rescovsecond");
1.337     brouard  8114:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8115:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8116:        }
                   8117:        fprintf(fichtm,"\"</a>");
                   8118:        
1.126     brouard  8119:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  8120:        for (cpt=1; cpt<=cptcovs;cpt++){  /**< cptcoveff number of variables */
                   8121:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8122:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  8123:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
1.317     brouard  8124:        }
1.237     brouard  8125: 
1.338     brouard  8126:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.220     brouard  8127: 
1.222     brouard  8128:        if(invalidvarcomb[k1]){
                   8129:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   8130:         continue;
                   8131:        }
1.337     brouard  8132:      } /* If cptcovn >0 */
1.126     brouard  8133:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  8134:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.314     brouard  8135: 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);
                   8136:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   8137:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
1.126     brouard  8138:      }
                   8139:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.314     brouard  8140: health expectancies in each live states (1 to %d). If popbased=1 the smooth (due to the model) \
1.128     brouard  8141: true period expectancies (those weighted with period prevalences are also\
                   8142:  drawn in addition to the population based expectancies computed using\
1.314     brouard  8143:  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);
                   8144:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
                   8145:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  8146:      /* } /\* end i1 *\/ */
1.241     brouard  8147:   }/* End nres */
1.222     brouard  8148:    fprintf(fichtm,"</ul>");
                   8149:    fflush(fichtm);
1.126     brouard  8150: }
                   8151: 
                   8152: /******************* Gnuplot file **************/
1.296     brouard  8153: 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  8154: 
                   8155:   char dirfileres[132],optfileres[132];
1.264     brouard  8156:   char gplotcondition[132], gplotlabel[132];
1.343     brouard  8157:   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  8158:   int lv=0, vlv=0, kl=0;
1.130     brouard  8159:   int ng=0;
1.201     brouard  8160:   int vpopbased;
1.223     brouard  8161:   int ioffset; /* variable offset for columns */
1.270     brouard  8162:   int iyearc=1; /* variable column for year of projection  */
                   8163:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  8164:   int nres=0; /* Index of resultline */
1.266     brouard  8165:   int istart=1; /* For starting graphs in projections */
1.219     brouard  8166: 
1.126     brouard  8167: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   8168: /*     printf("Problem with file %s",optionfilegnuplot); */
                   8169: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   8170: /*   } */
                   8171: 
                   8172:   /*#ifdef windows */
                   8173:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  8174:   /*#endif */
1.225     brouard  8175:   m=pow(2,cptcoveff);
1.126     brouard  8176: 
1.274     brouard  8177:   /* diagram of the model */
                   8178:   fprintf(ficgp,"\n#Diagram of the model \n");
                   8179:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   8180:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   8181:   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);
                   8182: 
1.343     brouard  8183:   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  8184:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   8185:   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);
                   8186:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   8187:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   8188:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   8189:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   8190: 
1.202     brouard  8191:   /* Contribution to likelihood */
                   8192:   /* Plot the probability implied in the likelihood */
1.223     brouard  8193:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   8194:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   8195:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   8196:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  8197: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  8198:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   8199: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  8200:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   8201:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8202:   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));
                   8203:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8204:   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));
                   8205:   for (i=1; i<= nlstate ; i ++) {
                   8206:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   8207:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   8208:     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);
                   8209:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   8210:       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);
                   8211:     }
                   8212:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8213:   }
                   8214:   /* 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 */               
                   8215:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   8216:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   8217:   fprintf(ficgp,"\nset out;unset log\n");
                   8218:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  8219: 
1.343     brouard  8220:   /* Plot the probability implied in the likelihood by covariate value */
                   8221:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
                   8222:   /* if(debugILK==1){ */
                   8223:   for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
                   8224:     kvar=Tvar[TvarFind[kf]]; /* variable */
                   8225:     k=18+Tvar[TvarFind[kf]];/*offset because there are 18 columns in the ILK_ file */
                   8226:     for (i=1; i<= nlstate ; i ++) {
                   8227:       fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   8228:       fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
                   8229:       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);
                   8230:       for (j=2; j<= nlstate+ndeath ; j ++) {
                   8231:        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);
                   8232:       }
                   8233:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8234:     }
                   8235:   } /* End of each covariate dummy */
                   8236:   for(ncovv=1, iposold=0, kk=0; ncovv <= ncovvt ; ncovv++){
                   8237:     /* Other example        V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   8238:      *     kmodel       =     1   2     3     4         5        6        7       8        9
                   8239:      *  varying                   1     2                                 3       4        5
                   8240:      *  ncovv                     1     2                                3 4     5 6      7 8
                   8241:      * TvarVV[ncovv]             V3     5                                1 3     3 5      1 5
                   8242:      * TvarVVind[ncovv]=kmodel    2     3                                7 7     8 8      9 9
                   8243:      * TvarFind[kmodel]       1   0     0     0         0        0        0       0        0
                   8244:      * kdata     ncovcol=[V1 V2] nqv=0 ntv=[V3 V4] nqtv=V5
                   8245:      * Dummy[kmodel]          0   0     1     2         2        3        1       1        1
                   8246:      */
                   8247:     ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   8248:     kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   8249:     /* 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]); */
                   8250:     if(ipos!=iposold){ /* Not a product or first of a product */
                   8251:       /* printf(" %d",ipos); */
                   8252:       /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   8253:       /* printf(" DebugILK ficgp suite ipos=%d != iposold=%d\n", ipos, iposold); */
                   8254:       kk++; /* Position of the ncovv column in ILK_ */
                   8255:       k=18+ncovf+kk; /*offset because there are 18 columns in the ILK_ file plus ncovf fixed covariate */
                   8256:       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)  */
                   8257:        for (i=1; i<= nlstate ; i ++) {
                   8258:          fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   8259:          fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
                   8260: 
                   8261:          if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
                   8262:            /* printf("DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
                   8263:            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);
                   8264:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   8265:              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);
                   8266:            }
                   8267:          }else{
                   8268:            /* printf("DebugILK gnuplotversion=%g <5.2\n",gnuplotversion); */
                   8269:            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);
                   8270:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   8271:              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);
                   8272:            }
                   8273:          }
                   8274:          fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8275:        }
                   8276:       }/* End if dummy varying */
                   8277:     }else{ /*Product */
                   8278:       /* printf("*"); */
                   8279:       /* fprintf(ficresilk,"*"); */
                   8280:     }
                   8281:     iposold=ipos;
                   8282:   } /* For each time varying covariate */
                   8283:   /* } /\* debugILK==1 *\/ */
                   8284:   /* 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 */               
                   8285:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   8286:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   8287:   fprintf(ficgp,"\nset out;unset log\n");
                   8288:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
                   8289: 
                   8290: 
                   8291:   
1.126     brouard  8292:   strcpy(dirfileres,optionfilefiname);
                   8293:   strcpy(optfileres,"vpl");
1.223     brouard  8294:   /* 1eme*/
1.238     brouard  8295:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
1.337     brouard  8296:     /* for (k1=1; k1<= m ; k1 ++){ /\* For each valid combination of covariate *\/ */
1.236     brouard  8297:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8298:        k1=TKresult[nres];
1.338     brouard  8299:        if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.238     brouard  8300:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.337     brouard  8301:        /* if(m != 1 && TKresult[nres]!= k1) */
                   8302:        /*   continue; */
1.238     brouard  8303:        /* We are interested in selected combination by the resultline */
1.246     brouard  8304:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  8305:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  8306:        strcpy(gplotlabel,"(");
1.337     brouard  8307:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8308:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8309:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8310: 
                   8311:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate k get corresponding value lv for combination k1 *\/ */
                   8312:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the value of the covariate corresponding to k1 combination *\\/ *\/ */
                   8313:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8314:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8315:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8316:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8317:        /*   vlv= nbcode[Tvaraff[k]][lv]; /\* vlv is the value of the covariate lv, 0 or 1 *\/ */
                   8318:        /*   /\* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv *\/ */
                   8319:        /*   /\* printf(" V%d=%d ",Tvaraff[k],vlv); *\/ */
                   8320:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8321:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8322:        /* } */
                   8323:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8324:        /*   /\* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); *\/ */
                   8325:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8326:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.264     brouard  8327:        }
                   8328:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  8329:        /* printf("\n#\n"); */
1.238     brouard  8330:        fprintf(ficgp,"\n#\n");
                   8331:        if(invalidvarcomb[k1]){
1.260     brouard  8332:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  8333:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8334:          continue;
                   8335:        }
1.235     brouard  8336:       
1.241     brouard  8337:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   8338:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  8339:        /* 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  8340:        fprintf(ficgp,"set title \"Alive state %d %s model=1+age+%s\" font \"Helvetica,12\"\n",cpt,gplotlabel,model);
1.260     brouard  8341:        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);
                   8342:        /* 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); */
                   8343:       /* k1-1 error should be nres-1*/
1.238     brouard  8344:        for (i=1; i<= nlstate ; i ++) {
                   8345:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8346:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   8347:        }
1.288     brouard  8348:        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  8349:        for (i=1; i<= nlstate ; i ++) {
                   8350:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8351:          else fprintf(ficgp," %%*lf (%%*lf)");
                   8352:        } 
1.260     brouard  8353:        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  8354:        for (i=1; i<= nlstate ; i ++) {
                   8355:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8356:          else fprintf(ficgp," %%*lf (%%*lf)");
                   8357:        }  
1.265     brouard  8358:        /* 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)); */
                   8359:        
                   8360:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   8361:         if(cptcoveff ==0){
1.271     brouard  8362:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  8363:        }else{
                   8364:          kl=0;
                   8365:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  8366:            /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8367:            lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.265     brouard  8368:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8369:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8370:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8371:            vlv= nbcode[Tvaraff[k]][lv];
                   8372:            kl++;
                   8373:            /* 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 *\/ */
                   8374:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8375:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8376:            /* ''  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*/
                   8377:            if(k==cptcoveff){
                   8378:              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], \
                   8379:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   8380:            }else{
                   8381:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   8382:              kl++;
                   8383:            }
                   8384:          } /* end covariate */
                   8385:        } /* end if no covariate */
                   8386: 
1.296     brouard  8387:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  8388:          /* 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  8389:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  8390:          if(cptcoveff ==0){
1.245     brouard  8391:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  8392:          }else{
                   8393:            kl=0;
                   8394:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  8395:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8396:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.238     brouard  8397:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8398:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8399:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8400:              /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8401:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.223     brouard  8402:              kl++;
1.238     brouard  8403:              /* 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 *\/ */
                   8404:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8405:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8406:              /* ''  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*/
                   8407:              if(k==cptcoveff){
1.245     brouard  8408:                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  8409:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  8410:              }else{
1.332     brouard  8411:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]);
1.238     brouard  8412:                kl++;
                   8413:              }
                   8414:            } /* end covariate */
                   8415:          } /* end if no covariate */
1.296     brouard  8416:          if(prevbcast == 1){
1.268     brouard  8417:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   8418:            /* k1-1 error should be nres-1*/
                   8419:            for (i=1; i<= nlstate ; i ++) {
                   8420:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8421:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   8422:            }
1.271     brouard  8423:            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  8424:            for (i=1; i<= nlstate ; i ++) {
                   8425:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8426:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8427:            } 
1.276     brouard  8428:            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  8429:            for (i=1; i<= nlstate ; i ++) {
                   8430:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8431:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8432:            } 
1.274     brouard  8433:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  8434:          } /* end if backprojcast */
1.296     brouard  8435:        } /* end if prevbcast */
1.276     brouard  8436:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   8437:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  8438:       } /* nres */
1.337     brouard  8439:     /* } /\* k1 *\/ */
1.201     brouard  8440:   } /* cpt */
1.235     brouard  8441: 
                   8442:   
1.126     brouard  8443:   /*2 eme*/
1.337     brouard  8444:   /* for (k1=1; k1<= m ; k1 ++){   */
1.238     brouard  8445:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8446:       k1=TKresult[nres];
1.338     brouard  8447:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8448:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8449:       /*       continue; */
1.238     brouard  8450:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  8451:       strcpy(gplotlabel,"(");
1.337     brouard  8452:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8453:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8454:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8455:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8456:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8457:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8458:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8459:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8460:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8461:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8462:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8463:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8464:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8465:       /* } */
                   8466:       /* /\* for(k=1; k <= ncovds; k++){ *\/ */
                   8467:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8468:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8469:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8470:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  8471:       }
1.264     brouard  8472:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8473:       fprintf(ficgp,"\n#\n");
1.223     brouard  8474:       if(invalidvarcomb[k1]){
                   8475:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8476:        continue;
                   8477:       }
1.219     brouard  8478:                        
1.241     brouard  8479:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  8480:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  8481:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   8482:        if(vpopbased==0){
1.238     brouard  8483:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  8484:        }else
1.238     brouard  8485:          fprintf(ficgp,"\nreplot ");
                   8486:        for (i=1; i<= nlstate+1 ; i ++) {
                   8487:          k=2*i;
1.261     brouard  8488:          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  8489:          for (j=1; j<= nlstate+1 ; j ++) {
                   8490:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8491:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8492:          }   
                   8493:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   8494:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
1.261     brouard  8495:          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  8496:          for (j=1; j<= nlstate+1 ; j ++) {
                   8497:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8498:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8499:          }   
                   8500:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  8501:          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  8502:          for (j=1; j<= nlstate+1 ; j ++) {
                   8503:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8504:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8505:          }   
                   8506:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   8507:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   8508:        } /* state */
                   8509:       } /* vpopbased */
1.264     brouard  8510:       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  8511:     } /* end nres */
1.337     brouard  8512:   /* } /\* k1 end 2 eme*\/ */
1.238     brouard  8513:        
                   8514:        
                   8515:   /*3eme*/
1.337     brouard  8516:   /* for (k1=1; k1<= m ; k1 ++){ */
1.238     brouard  8517:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8518:       k1=TKresult[nres];
1.338     brouard  8519:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8520:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8521:       /*       continue; */
1.238     brouard  8522: 
1.332     brouard  8523:       for (cpt=1; cpt<= nlstate ; cpt ++) { /* Fragile no verification of covariate values */
1.261     brouard  8524:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  8525:        strcpy(gplotlabel,"(");
1.337     brouard  8526:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8527:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8528:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8529:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8530:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8531:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8532:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8533:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8534:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8535:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8536:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8537:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8538:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8539:        /* } */
                   8540:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8541:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   8542:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   8543:        }
1.264     brouard  8544:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8545:        fprintf(ficgp,"\n#\n");
                   8546:        if(invalidvarcomb[k1]){
                   8547:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8548:          continue;
                   8549:        }
                   8550:                        
                   8551:        /*       k=2+nlstate*(2*cpt-2); */
                   8552:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  8553:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  8554:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  8555:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  8556: 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  8557:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8558:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8559:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   8560:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8561:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8562:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  8563:                                
1.238     brouard  8564:        */
                   8565:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  8566:          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  8567:          /*    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  8568:                                
1.238     brouard  8569:        } 
1.261     brouard  8570:        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  8571:       }
1.264     brouard  8572:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  8573:     } /* end nres */
1.337     brouard  8574:   /* } /\* end kl 3eme *\/ */
1.126     brouard  8575:   
1.223     brouard  8576:   /* 4eme */
1.201     brouard  8577:   /* Survival functions (period) from state i in state j by initial state i */
1.337     brouard  8578:   /* for (k1=1; k1<=m; k1++){    /\* For each covariate and each value *\/ */
1.238     brouard  8579:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8580:       k1=TKresult[nres];
1.338     brouard  8581:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8582:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8583:       /*       continue; */
1.238     brouard  8584:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  8585:        strcpy(gplotlabel,"(");
1.337     brouard  8586:        fprintf(ficgp,"\n#\n#\n# Survival functions in state %d : 'LIJ_' files, cov=%d state=%d", cpt, k1, cpt);
                   8587:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8588:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8589:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8590:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8591:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8592:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8593:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8594:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8595:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8596:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8597:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8598:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8599:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8600:        /* } */
                   8601:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8602:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8603:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  8604:        }       
1.264     brouard  8605:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8606:        fprintf(ficgp,"\n#\n");
                   8607:        if(invalidvarcomb[k1]){
                   8608:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8609:          continue;
1.223     brouard  8610:        }
1.238     brouard  8611:       
1.241     brouard  8612:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  8613:        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  8614:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8615: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8616:        k=3;
                   8617:        for (i=1; i<= nlstate ; i ++){
                   8618:          if(i==1){
                   8619:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8620:          }else{
                   8621:            fprintf(ficgp,", '' ");
                   8622:          }
                   8623:          l=(nlstate+ndeath)*(i-1)+1;
                   8624:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8625:          for (j=2; j<= nlstate+ndeath ; j ++)
                   8626:            fprintf(ficgp,"+$%d",k+l+j-1);
                   8627:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   8628:        } /* nlstate */
1.264     brouard  8629:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8630:       } /* end cpt state*/ 
                   8631:     } /* end nres */
1.337     brouard  8632:   /* } /\* end covariate k1 *\/   */
1.238     brouard  8633: 
1.220     brouard  8634: /* 5eme */
1.201     brouard  8635:   /* Survival functions (period) from state i in state j by final state j */
1.337     brouard  8636:   /* for (k1=1; k1<= m ; k1++){ /\* For each covariate combination if any *\/ */
1.238     brouard  8637:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8638:       k1=TKresult[nres];
1.338     brouard  8639:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8640:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8641:       /*       continue; */
1.238     brouard  8642:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  8643:        strcpy(gplotlabel,"(");
1.238     brouard  8644:        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  8645:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8646:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8647:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8648:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8649:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8650:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8651:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8652:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8653:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8654:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8655:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8656:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8657:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8658:        /* } */
                   8659:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8660:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8661:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  8662:        }       
1.264     brouard  8663:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8664:        fprintf(ficgp,"\n#\n");
                   8665:        if(invalidvarcomb[k1]){
                   8666:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8667:          continue;
                   8668:        }
1.227     brouard  8669:       
1.241     brouard  8670:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  8671:        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  8672:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8673: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8674:        k=3;
                   8675:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8676:          if(j==1)
                   8677:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8678:          else
                   8679:            fprintf(ficgp,", '' ");
                   8680:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8681:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   8682:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   8683:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   8684:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   8685:        } /* nlstate */
                   8686:        fprintf(ficgp,", '' ");
                   8687:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   8688:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8689:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8690:          if(j < nlstate)
                   8691:            fprintf(ficgp,"$%d +",k+l);
                   8692:          else
                   8693:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   8694:        }
1.264     brouard  8695:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8696:       } /* end cpt state*/ 
1.337     brouard  8697:     /* } /\* end covariate *\/   */
1.238     brouard  8698:   } /* end nres */
1.227     brouard  8699:   
1.220     brouard  8700: /* 6eme */
1.202     brouard  8701:   /* CV preval stable (period) for each covariate */
1.337     brouard  8702:   /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8703:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8704:      k1=TKresult[nres];
1.338     brouard  8705:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8706:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8707:      /*  continue; */
1.255     brouard  8708:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  8709:       strcpy(gplotlabel,"(");      
1.288     brouard  8710:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8711:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8712:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8713:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8714:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8715:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8716:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8717:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8718:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8719:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8720:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8721:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8722:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8723:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8724:       /* } */
                   8725:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8726:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8727:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8728:       }        
1.264     brouard  8729:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8730:       fprintf(ficgp,"\n#\n");
1.223     brouard  8731:       if(invalidvarcomb[k1]){
1.227     brouard  8732:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8733:        continue;
1.223     brouard  8734:       }
1.227     brouard  8735:       
1.241     brouard  8736:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  8737:       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  8738:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8739: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  8740:       k=3; /* Offset */
1.255     brouard  8741:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  8742:        if(i==1)
                   8743:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8744:        else
                   8745:          fprintf(ficgp,", '' ");
1.255     brouard  8746:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  8747:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8748:        for (j=2; j<= nlstate ; j ++)
                   8749:          fprintf(ficgp,"+$%d",k+l+j-1);
                   8750:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  8751:       } /* nlstate */
1.264     brouard  8752:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  8753:     } /* end cpt state*/ 
                   8754:   } /* end covariate */  
1.227     brouard  8755:   
                   8756:   
1.220     brouard  8757: /* 7eme */
1.296     brouard  8758:   if(prevbcast == 1){
1.288     brouard  8759:     /* CV backward prevalence  for each covariate */
1.337     brouard  8760:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8761:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8762:       k1=TKresult[nres];
1.338     brouard  8763:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8764:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8765:       /*       continue; */
1.268     brouard  8766:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  8767:        strcpy(gplotlabel,"(");      
1.288     brouard  8768:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8769:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8770:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8771:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8772:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8773:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8774:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8775:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8776:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8777:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8778:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8779:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8780:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8781:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8782:        /* } */
                   8783:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8784:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8785:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8786:        }       
1.264     brouard  8787:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8788:        fprintf(ficgp,"\n#\n");
                   8789:        if(invalidvarcomb[k1]){
                   8790:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8791:          continue;
                   8792:        }
                   8793:        
1.241     brouard  8794:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  8795:        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  8796:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8797: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  8798:        k=3; /* Offset */
1.268     brouard  8799:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  8800:          if(i==1)
                   8801:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   8802:          else
                   8803:            fprintf(ficgp,", '' ");
                   8804:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  8805:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.324     brouard  8806:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   8807:          /* 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  8808:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  8809:          /* for (j=2; j<= nlstate ; j ++) */
                   8810:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   8811:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  8812:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  8813:        } /* nlstate */
1.264     brouard  8814:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  8815:       } /* end cpt state*/ 
                   8816:     } /* end covariate */  
1.296     brouard  8817:   } /* End if prevbcast */
1.218     brouard  8818:   
1.223     brouard  8819:   /* 8eme */
1.218     brouard  8820:   if(prevfcast==1){
1.288     brouard  8821:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  8822:     
1.337     brouard  8823:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8824:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8825:       k1=TKresult[nres];
1.338     brouard  8826:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8827:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8828:       /*       continue; */
1.211     brouard  8829:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  8830:        strcpy(gplotlabel,"(");      
1.288     brouard  8831:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8832:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8833:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8834:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8835:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   8836:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   8837:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8838:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8839:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8840:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8841:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8842:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8843:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8844:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8845:        /* } */
                   8846:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8847:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8848:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8849:        }       
1.264     brouard  8850:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8851:        fprintf(ficgp,"\n#\n");
                   8852:        if(invalidvarcomb[k1]){
                   8853:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8854:          continue;
                   8855:        }
                   8856:        
                   8857:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  8858:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  8859:        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  8860:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  8861: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  8862: 
                   8863:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   8864:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8865:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8866:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  8867:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8868:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8869:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8870:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  8871:          if(i==istart){
1.227     brouard  8872:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   8873:          }else{
                   8874:            fprintf(ficgp,",\\\n '' ");
                   8875:          }
                   8876:          if(cptcoveff ==0){ /* No covariate */
                   8877:            ioffset=2; /* Age is in 2 */
                   8878:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8879:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8880:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8881:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8882:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  8883:            if(i==nlstate+1){
1.270     brouard  8884:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  8885:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   8886:              fprintf(ficgp,",\\\n '' ");
                   8887:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  8888:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  8889:                     offyear,                           \
1.268     brouard  8890:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  8891:            }else
1.227     brouard  8892:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   8893:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8894:          }else{ /* more than 2 covariates */
1.270     brouard  8895:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   8896:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8897:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   8898:            iyearc=ioffset-1;
                   8899:            iagec=ioffset;
1.227     brouard  8900:            fprintf(ficgp," u %d:(",ioffset); 
                   8901:            kl=0;
                   8902:            strcpy(gplotcondition,"(");
                   8903:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
1.332     brouard  8904:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8905:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.227     brouard  8906:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8907:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8908:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8909:              /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   8910:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.227     brouard  8911:              kl++;
                   8912:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   8913:              kl++;
                   8914:              if(k <cptcoveff && cptcoveff>1)
                   8915:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   8916:            }
                   8917:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   8918:            /* 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 *\/ */
                   8919:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8920:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8921:            /* ''  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*/
                   8922:            if(i==nlstate+1){
1.270     brouard  8923:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   8924:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  8925:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  8926:              fprintf(ficgp," u %d:(",iagec); 
                   8927:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   8928:                      iyearc, iagec, offyear,                           \
                   8929:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  8930: /*  '' 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  8931:            }else{
                   8932:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   8933:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8934:            }
                   8935:          } /* end if covariate */
                   8936:        } /* nlstate */
1.264     brouard  8937:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  8938:       } /* end cpt state*/
                   8939:     } /* end covariate */
                   8940:   } /* End if prevfcast */
1.227     brouard  8941:   
1.296     brouard  8942:   if(prevbcast==1){
1.268     brouard  8943:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   8944:     
1.337     brouard  8945:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.268     brouard  8946:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8947:      k1=TKresult[nres];
1.338     brouard  8948:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8949:        /* if(m != 1 && TKresult[nres]!= k1) */
                   8950:        /*      continue; */
1.268     brouard  8951:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   8952:        strcpy(gplotlabel,"(");      
                   8953:        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  8954:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8955:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8956:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8957:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   8958:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   8959:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8960:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8961:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8962:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8963:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8964:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8965:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8966:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8967:        /* } */
                   8968:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8969:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8970:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.268     brouard  8971:        }       
                   8972:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   8973:        fprintf(ficgp,"\n#\n");
                   8974:        if(invalidvarcomb[k1]){
                   8975:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8976:          continue;
                   8977:        }
                   8978:        
                   8979:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   8980:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   8981:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   8982:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   8983: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8984: 
                   8985:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   8986:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8987:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8988:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   8989:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8990:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8991:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8992:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8993:          if(i==istart){
                   8994:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   8995:          }else{
                   8996:            fprintf(ficgp,",\\\n '' ");
                   8997:          }
                   8998:          if(cptcoveff ==0){ /* No covariate */
                   8999:            ioffset=2; /* Age is in 2 */
                   9000:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9001:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9002:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9003:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9004:            fprintf(ficgp," u %d:(", ioffset); 
                   9005:            if(i==nlstate+1){
1.270     brouard  9006:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  9007:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   9008:              fprintf(ficgp,",\\\n '' ");
                   9009:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  9010:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  9011:                     offbyear,                          \
                   9012:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   9013:            }else
                   9014:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   9015:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   9016:          }else{ /* more than 2 covariates */
1.270     brouard  9017:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   9018:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9019:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   9020:            iyearc=ioffset-1;
                   9021:            iagec=ioffset;
1.268     brouard  9022:            fprintf(ficgp," u %d:(",ioffset); 
                   9023:            kl=0;
                   9024:            strcpy(gplotcondition,"(");
1.337     brouard  9025:            for (k=1; k<=cptcovs; k++){    /* For each covariate k of the resultline, get corresponding value lv for combination k1 */
1.338     brouard  9026:              if(Dummy[modelresult[nres][k]]==0){  /* To be verified */
1.337     brouard  9027:                /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
                   9028:                /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9029:                /* lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9030:                lv=Tvresult[nres][k];
                   9031:                vlv=TinvDoQresult[nres][Tvresult[nres][k]];
                   9032:                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   9033:                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   9034:                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   9035:                /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   9036:                /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9037:                kl++;
                   9038:                /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
                   9039:                sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%lg " ,kl,Tvresult[nres][k], kl+1,TinvDoQresult[nres][Tvresult[nres][k]]);
                   9040:                kl++;
1.338     brouard  9041:                if(k <cptcovs && cptcovs>1)
1.337     brouard  9042:                  sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   9043:              }
1.268     brouard  9044:            }
                   9045:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   9046:            /* 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 *\/ */
                   9047:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   9048:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   9049:            /* ''  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*/
                   9050:            if(i==nlstate+1){
1.270     brouard  9051:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   9052:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  9053:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  9054:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  9055:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  9056:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   9057:                      iyearc,iagec,offbyear,                            \
                   9058:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  9059: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   9060:            }else{
                   9061:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   9062:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   9063:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   9064:            }
                   9065:          } /* end if covariate */
                   9066:        } /* nlstate */
                   9067:        fprintf(ficgp,"\nset out; unset label;\n");
                   9068:       } /* end cpt state*/
                   9069:     } /* end covariate */
1.296     brouard  9070:   } /* End if prevbcast */
1.268     brouard  9071:   
1.227     brouard  9072:   
1.238     brouard  9073:   /* 9eme writing MLE parameters */
                   9074:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  9075:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  9076:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  9077:     for(k=1; k <=(nlstate+ndeath); k++){
                   9078:       if (k != i) {
1.227     brouard  9079:        fprintf(ficgp,"#   current state %d\n",k);
                   9080:        for(j=1; j <=ncovmodel; j++){
                   9081:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   9082:          jk++; 
                   9083:        }
                   9084:        fprintf(ficgp,"\n");
1.126     brouard  9085:       }
                   9086:     }
1.223     brouard  9087:   }
1.187     brouard  9088:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  9089:   
1.145     brouard  9090:   /*goto avoid;*/
1.238     brouard  9091:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   9092:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  9093:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   9094:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   9095:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   9096:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   9097:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9098:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   9099:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9100:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   9101:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   9102:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9103:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   9104:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   9105:   fprintf(ficgp,"#\n");
1.223     brouard  9106:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  9107:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.338     brouard  9108:     fprintf(ficgp,"#model=1+age+%s \n",model);
1.238     brouard  9109:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.264     brouard  9110:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
1.337     brouard  9111:     /* for(k1=1; k1 <=m; k1++)  /\* For each combination of covariate *\/ */
1.237     brouard  9112:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  9113:      /* k1=nres; */
1.338     brouard  9114:       k1=TKresult[nres];
                   9115:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9116:       fprintf(ficgp,"\n\n# Resultline k1=%d ",k1);
1.264     brouard  9117:       strcpy(gplotlabel,"(");
1.276     brouard  9118:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.337     brouard  9119:       for (k=1; k<=cptcovs; k++){  /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   9120:        /* for each resultline nres, and position k, Tvresult[nres][k] gives the name of the variable and
                   9121:           TinvDoQresult[nres][Tvresult[nres][k]] gives its value double or integer) */
                   9122:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9123:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9124:       }
                   9125:       /* if(m != 1 && TKresult[nres]!= k1) */
                   9126:       /*       continue; */
                   9127:       /* fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1); */
                   9128:       /* strcpy(gplotlabel,"("); */
                   9129:       /* /\*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*\/ */
                   9130:       /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   9131:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   9132:       /*       lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9133:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9134:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9135:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9136:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9137:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9138:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9139:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9140:       /* } */
                   9141:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9142:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9143:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9144:       /* }      */
1.264     brouard  9145:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  9146:       fprintf(ficgp,"\n#\n");
1.264     brouard  9147:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  9148:       fprintf(ficgp,"\nset key outside ");
                   9149:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   9150:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  9151:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   9152:       if (ng==1){
                   9153:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   9154:        fprintf(ficgp,"\nunset log y");
                   9155:       }else if (ng==2){
                   9156:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   9157:        fprintf(ficgp,"\nset log y");
                   9158:       }else if (ng==3){
                   9159:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   9160:        fprintf(ficgp,"\nset log y");
                   9161:       }else
                   9162:        fprintf(ficgp,"\nunset title ");
                   9163:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   9164:       i=1;
                   9165:       for(k2=1; k2<=nlstate; k2++) {
                   9166:        k3=i;
                   9167:        for(k=1; k<=(nlstate+ndeath); k++) {
                   9168:          if (k != k2){
                   9169:            switch( ng) {
                   9170:            case 1:
                   9171:              if(nagesqr==0)
                   9172:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   9173:              else /* nagesqr =1 */
                   9174:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   9175:              break;
                   9176:            case 2: /* ng=2 */
                   9177:              if(nagesqr==0)
                   9178:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   9179:              else /* nagesqr =1 */
                   9180:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   9181:              break;
                   9182:            case 3:
                   9183:              if(nagesqr==0)
                   9184:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   9185:              else /* nagesqr =1 */
                   9186:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   9187:              break;
                   9188:            }
                   9189:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  9190:            ijp=1; /* product no age */
                   9191:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   9192:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  9193:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.329     brouard  9194:              switch(Typevar[j]){
                   9195:              case 1:
                   9196:                if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   9197:                  if(j==Tage[ij]) { /* Product by age  To be looked at!!*//* Bug valgrind */
                   9198:                    if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   9199:                      if(DummyV[j]==0){/* Bug valgrind */
                   9200:                        fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   9201:                      }else{ /* quantitative */
                   9202:                        fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   9203:                        /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9204:                      }
                   9205:                      ij++;
1.268     brouard  9206:                    }
1.237     brouard  9207:                  }
1.329     brouard  9208:                }
                   9209:                break;
                   9210:              case 2:
                   9211:                if(cptcovprod >0){
                   9212:                  if(j==Tprod[ijp]) { /* */ 
                   9213:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9214:                    if(ijp <=cptcovprod) { /* Product */
                   9215:                      if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   9216:                        if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   9217:                          /* 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)]); */
                   9218:                          fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9219:                        }else{ /* Vn is dummy and Vm is quanti */
                   9220:                          /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9221:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9222:                        }
                   9223:                      }else{ /* Vn*Vm Vn is quanti */
                   9224:                        if(DummyV[Tvard[ijp][2]]==0){
                   9225:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   9226:                        }else{ /* Both quanti */
                   9227:                          fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9228:                        }
1.268     brouard  9229:                      }
1.329     brouard  9230:                      ijp++;
1.237     brouard  9231:                    }
1.329     brouard  9232:                  } /* end Tprod */
                   9233:                }
                   9234:                break;
                   9235:              case 0:
                   9236:                /* simple covariate */
1.264     brouard  9237:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  9238:                if(Dummy[j]==0){
                   9239:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   9240:                }else{ /* quantitative */
                   9241:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  9242:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  9243:                }
1.329     brouard  9244:               /* end simple */
                   9245:                break;
                   9246:              default:
                   9247:                break;
                   9248:              } /* end switch */
1.237     brouard  9249:            } /* end j */
1.329     brouard  9250:          }else{ /* k=k2 */
                   9251:            if(ng !=1 ){ /* For logit formula of log p11 is more difficult to get */
                   9252:              fprintf(ficgp," (1.");i=i-ncovmodel;
                   9253:            }else
                   9254:              i=i-ncovmodel;
1.223     brouard  9255:          }
1.227     brouard  9256:          
1.223     brouard  9257:          if(ng != 1){
                   9258:            fprintf(ficgp,")/(1");
1.227     brouard  9259:            
1.264     brouard  9260:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  9261:              if(nagesqr==0)
1.264     brouard  9262:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  9263:              else /* nagesqr =1 */
1.264     brouard  9264:                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  9265:               
1.223     brouard  9266:              ij=1;
1.329     brouard  9267:              ijp=1;
                   9268:              /* for(j=3; j <=ncovmodel-nagesqr; j++){ */
                   9269:              for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
                   9270:                switch(Typevar[j]){
                   9271:                case 1:
                   9272:                  if(cptcovage >0){ 
                   9273:                    if(j==Tage[ij]) { /* Bug valgrind */
                   9274:                      if(ij <=cptcovage) { /* Bug valgrind */
                   9275:                        if(DummyV[j]==0){/* Bug valgrind */
                   9276:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]); */
                   9277:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,nbcode[Tvar[j]][codtabm(k1,j)]); */
                   9278:                          fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]);
                   9279:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);; */
                   9280:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9281:                        }else{ /* quantitative */
                   9282:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   9283:                          fprintf(ficgp,"+p%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   9284:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   9285:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9286:                        }
                   9287:                        ij++;
                   9288:                      }
                   9289:                    }
                   9290:                  }
                   9291:                  break;
                   9292:                case 2:
                   9293:                  if(cptcovprod >0){
                   9294:                    if(j==Tprod[ijp]) { /* */ 
                   9295:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9296:                      if(ijp <=cptcovprod) { /* Product */
                   9297:                        if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   9298:                          if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   9299:                            /* 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)]); */
                   9300:                            fprintf(ficgp,"+p%d*%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9301:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   9302:                          }else{ /* Vn is dummy and Vm is quanti */
                   9303:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9304:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9305:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9306:                          }
                   9307:                        }else{ /* Vn*Vm Vn is quanti */
                   9308:                          if(DummyV[Tvard[ijp][2]]==0){
                   9309:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   9310:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   9311:                          }else{ /* Both quanti */
                   9312:                            fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9313:                            /* fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9314:                          } 
                   9315:                        }
                   9316:                        ijp++;
                   9317:                      }
                   9318:                    } /* end Tprod */
                   9319:                  } /* end if */
                   9320:                  break;
                   9321:                case 0: 
                   9322:                  /* simple covariate */
                   9323:                  /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
                   9324:                  if(Dummy[j]==0){
                   9325:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   9326:                    fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]); /*  */
                   9327:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   9328:                  }else{ /* quantitative */
                   9329:                    fprintf(ficgp,"+p%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* */
                   9330:                    /* fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* *\/ */
                   9331:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9332:                  }
                   9333:                  /* end simple */
                   9334:                  /* fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);/\* Valgrind bug nbcode *\/ */
                   9335:                  break;
                   9336:                default:
                   9337:                  break;
                   9338:                } /* end switch */
1.223     brouard  9339:              }
                   9340:              fprintf(ficgp,")");
                   9341:            }
                   9342:            fprintf(ficgp,")");
                   9343:            if(ng ==2)
1.276     brouard  9344:              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  9345:            else /* ng= 3 */
1.276     brouard  9346:              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  9347:           }else{ /* end ng <> 1 */
1.223     brouard  9348:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  9349:              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  9350:          }
                   9351:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   9352:            fprintf(ficgp,",");
                   9353:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   9354:            fprintf(ficgp,",");
                   9355:          i=i+ncovmodel;
                   9356:        } /* end k */
                   9357:       } /* end k2 */
1.276     brouard  9358:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   9359:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.337     brouard  9360:     } /* end resultline */
1.223     brouard  9361:   } /* end ng */
                   9362:   /* avoid: */
                   9363:   fflush(ficgp); 
1.126     brouard  9364: }  /* end gnuplot */
                   9365: 
                   9366: 
                   9367: /*************** Moving average **************/
1.219     brouard  9368: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  9369:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  9370:    
1.222     brouard  9371:    int i, cpt, cptcod;
                   9372:    int modcovmax =1;
                   9373:    int mobilavrange, mob;
                   9374:    int iage=0;
1.288     brouard  9375:    int firstA1=0, firstA2=0;
1.222     brouard  9376: 
1.266     brouard  9377:    double sum=0., sumr=0.;
1.222     brouard  9378:    double age;
1.266     brouard  9379:    double *sumnewp, *sumnewm, *sumnewmr;
                   9380:    double *agemingood, *agemaxgood; 
                   9381:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  9382:   
                   9383:   
1.278     brouard  9384:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   9385:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  9386: 
                   9387:    sumnewp = vector(1,ncovcombmax);
                   9388:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  9389:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  9390:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  9391:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  9392:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  9393:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  9394: 
                   9395:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  9396:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  9397:      sumnewp[cptcod]=0.;
1.266     brouard  9398:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   9399:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  9400:    }
                   9401:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   9402:   
1.266     brouard  9403:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   9404:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  9405:      else mobilavrange=mobilav;
                   9406:      for (age=bage; age<=fage; age++)
                   9407:        for (i=1; i<=nlstate;i++)
                   9408:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   9409:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9410:      /* We keep the original values on the extreme ages bage, fage and for 
                   9411:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   9412:        we use a 5 terms etc. until the borders are no more concerned. 
                   9413:      */ 
                   9414:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   9415:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  9416:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   9417:           sumnewm[cptcod]=0.;
                   9418:           for (i=1; i<=nlstate;i++){
1.222     brouard  9419:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   9420:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   9421:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   9422:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   9423:             }
                   9424:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  9425:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9426:           } /* end i */
                   9427:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   9428:         } /* end cptcod */
1.222     brouard  9429:        }/* end age */
                   9430:      }/* end mob */
1.266     brouard  9431:    }else{
                   9432:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  9433:      return -1;
1.266     brouard  9434:    }
                   9435: 
                   9436:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  9437:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   9438:      if(invalidvarcomb[cptcod]){
                   9439:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   9440:        continue;
                   9441:      }
1.219     brouard  9442: 
1.266     brouard  9443:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   9444:        sumnewm[cptcod]=0.;
                   9445:        sumnewmr[cptcod]=0.;
                   9446:        for (i=1; i<=nlstate;i++){
                   9447:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9448:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9449:        }
                   9450:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9451:         agemingoodr[cptcod]=age;
                   9452:        }
                   9453:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9454:           agemingood[cptcod]=age;
                   9455:        }
                   9456:      } /* age */
                   9457:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  9458:        sumnewm[cptcod]=0.;
1.266     brouard  9459:        sumnewmr[cptcod]=0.;
1.222     brouard  9460:        for (i=1; i<=nlstate;i++){
                   9461:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9462:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9463:        }
                   9464:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9465:         agemaxgoodr[cptcod]=age;
1.222     brouard  9466:        }
                   9467:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  9468:         agemaxgood[cptcod]=age;
                   9469:        }
                   9470:      } /* age */
                   9471:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   9472:      /* but they will change */
1.288     brouard  9473:      firstA1=0;firstA2=0;
1.266     brouard  9474:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   9475:        sumnewm[cptcod]=0.;
                   9476:        sumnewmr[cptcod]=0.;
                   9477:        for (i=1; i<=nlstate;i++){
                   9478:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9479:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9480:        }
                   9481:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9482:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9483:           agemaxgoodr[cptcod]=age;  /* age min */
                   9484:           for (i=1; i<=nlstate;i++)
                   9485:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9486:         }else{ /* bad we change the value with the values of good ages */
                   9487:           for (i=1; i<=nlstate;i++){
                   9488:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   9489:           } /* i */
                   9490:         } /* end bad */
                   9491:        }else{
                   9492:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9493:           agemaxgood[cptcod]=age;
                   9494:         }else{ /* bad we change the value with the values of good ages */
                   9495:           for (i=1; i<=nlstate;i++){
                   9496:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   9497:           } /* i */
                   9498:         } /* end bad */
                   9499:        }/* end else */
                   9500:        sum=0.;sumr=0.;
                   9501:        for (i=1; i<=nlstate;i++){
                   9502:         sum+=mobaverage[(int)age][i][cptcod];
                   9503:         sumr+=probs[(int)age][i][cptcod];
                   9504:        }
                   9505:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  9506:         if(!firstA1){
                   9507:           firstA1=1;
                   9508:           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);
                   9509:         }
                   9510:         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  9511:        } /* end bad */
                   9512:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9513:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  9514:         if(!firstA2){
                   9515:           firstA2=1;
                   9516:           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);
                   9517:         }
                   9518:         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  9519:        } /* end bad */
                   9520:      }/* age */
1.266     brouard  9521: 
                   9522:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  9523:        sumnewm[cptcod]=0.;
1.266     brouard  9524:        sumnewmr[cptcod]=0.;
1.222     brouard  9525:        for (i=1; i<=nlstate;i++){
                   9526:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9527:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9528:        } 
                   9529:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9530:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   9531:           agemingoodr[cptcod]=age;
                   9532:           for (i=1; i<=nlstate;i++)
                   9533:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9534:         }else{ /* bad we change the value with the values of good ages */
                   9535:           for (i=1; i<=nlstate;i++){
                   9536:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   9537:           } /* i */
                   9538:         } /* end bad */
                   9539:        }else{
                   9540:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9541:           agemingood[cptcod]=age;
                   9542:         }else{ /* bad */
                   9543:           for (i=1; i<=nlstate;i++){
                   9544:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   9545:           } /* i */
                   9546:         } /* end bad */
                   9547:        }/* end else */
                   9548:        sum=0.;sumr=0.;
                   9549:        for (i=1; i<=nlstate;i++){
                   9550:         sum+=mobaverage[(int)age][i][cptcod];
                   9551:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  9552:        }
1.266     brouard  9553:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  9554:         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  9555:        } /* end bad */
                   9556:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9557:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  9558:         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  9559:        } /* end bad */
                   9560:      }/* age */
1.266     brouard  9561: 
1.222     brouard  9562:                
                   9563:      for (age=bage; age<=fage; age++){
1.235     brouard  9564:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  9565:        sumnewp[cptcod]=0.;
                   9566:        sumnewm[cptcod]=0.;
                   9567:        for (i=1; i<=nlstate;i++){
                   9568:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   9569:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9570:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   9571:        }
                   9572:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   9573:      }
                   9574:      /* printf("\n"); */
                   9575:      /* } */
1.266     brouard  9576: 
1.222     brouard  9577:      /* brutal averaging */
1.266     brouard  9578:      /* for (i=1; i<=nlstate;i++){ */
                   9579:      /*   for (age=1; age<=bage; age++){ */
                   9580:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   9581:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9582:      /*   }     */
                   9583:      /*   for (age=fage; age<=AGESUP; age++){ */
                   9584:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[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:      /* } /\* end i status *\/ */
                   9588:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   9589:      /*   for (age=1; age<=AGESUP; age++){ */
                   9590:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   9591:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   9592:      /*   } */
                   9593:      /* } */
1.222     brouard  9594:    }/* end cptcod */
1.266     brouard  9595:    free_vector(agemaxgoodr,1, ncovcombmax);
                   9596:    free_vector(agemaxgood,1, ncovcombmax);
                   9597:    free_vector(agemingood,1, ncovcombmax);
                   9598:    free_vector(agemingoodr,1, ncovcombmax);
                   9599:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  9600:    free_vector(sumnewm,1, ncovcombmax);
                   9601:    free_vector(sumnewp,1, ncovcombmax);
                   9602:    return 0;
                   9603:  }/* End movingaverage */
1.218     brouard  9604:  
1.126     brouard  9605: 
1.296     brouard  9606:  
1.126     brouard  9607: /************** Forecasting ******************/
1.296     brouard  9608: /* 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)*/
                   9609: 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){
                   9610:   /* dateintemean, mean date of interviews
                   9611:      dateprojd, year, month, day of starting projection 
                   9612:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  9613:      agemin, agemax range of age
                   9614:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   9615:   */
1.296     brouard  9616:   /* double anprojd, mprojd, jprojd; */
                   9617:   /* double anprojf, mprojf, jprojf; */
1.267     brouard  9618:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  9619:   double agec; /* generic age */
1.296     brouard  9620:   double agelim, ppij, yp,yp1,yp2;
1.126     brouard  9621:   double *popeffectif,*popcount;
                   9622:   double ***p3mat;
1.218     brouard  9623:   /* double ***mobaverage; */
1.126     brouard  9624:   char fileresf[FILENAMELENGTH];
                   9625: 
                   9626:   agelim=AGESUP;
1.211     brouard  9627:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9628:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9629:      We still use firstpass and lastpass as another selection.
                   9630:   */
1.214     brouard  9631:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9632:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  9633:  
1.201     brouard  9634:   strcpy(fileresf,"F_"); 
                   9635:   strcat(fileresf,fileresu);
1.126     brouard  9636:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   9637:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   9638:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   9639:   }
1.235     brouard  9640:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   9641:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  9642: 
1.225     brouard  9643:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  9644: 
                   9645: 
                   9646:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9647:   if (stepm<=12) stepsize=1;
                   9648:   if(estepm < stepm){
                   9649:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9650:   }
1.270     brouard  9651:   else{
                   9652:     hstepm=estepm;   
                   9653:   }
                   9654:   if(estepm > stepm){ /* Yes every two year */
                   9655:     stepsize=2;
                   9656:   }
1.296     brouard  9657:   hstepm=hstepm/stepm;
1.126     brouard  9658: 
1.296     brouard  9659:   
                   9660:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9661:   /*                              fractional in yp1 *\/ */
                   9662:   /* aintmean=yp; */
                   9663:   /* yp2=modf((yp1*12),&yp); */
                   9664:   /* mintmean=yp; */
                   9665:   /* yp1=modf((yp2*30.5),&yp); */
                   9666:   /* jintmean=yp; */
                   9667:   /* if(jintmean==0) jintmean=1; */
                   9668:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  9669: 
1.296     brouard  9670: 
                   9671:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   9672:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   9673:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.227     brouard  9674:   i1=pow(2,cptcoveff);
1.126     brouard  9675:   if (cptcovn < 1){i1=1;}
                   9676:   
1.296     brouard  9677:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  9678:   
                   9679:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  9680:   
1.126     brouard  9681: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  9682:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.332     brouard  9683:     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  9684:     if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  9685:       continue;
1.227     brouard  9686:     if(invalidvarcomb[k]){
                   9687:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   9688:       continue;
                   9689:     }
                   9690:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   9691:     for(j=1;j<=cptcoveff;j++) {
1.332     brouard  9692:       /* fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); */
                   9693:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.227     brouard  9694:     }
1.235     brouard  9695:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  9696:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.235     brouard  9697:     }
1.227     brouard  9698:     fprintf(ficresf," yearproj age");
                   9699:     for(j=1; j<=nlstate+ndeath;j++){ 
                   9700:       for(i=1; i<=nlstate;i++)               
                   9701:        fprintf(ficresf," p%d%d",i,j);
                   9702:       fprintf(ficresf," wp.%d",j);
                   9703:     }
1.296     brouard  9704:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  9705:       fprintf(ficresf,"\n");
1.296     brouard  9706:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  9707:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   9708:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  9709:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   9710:        nhstepm = nhstepm/hstepm; 
                   9711:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9712:        oldm=oldms;savm=savms;
1.268     brouard  9713:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  9714:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  9715:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  9716:        for (h=0; h<=nhstepm; h++){
                   9717:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  9718:            break;
                   9719:          }
                   9720:        }
                   9721:        fprintf(ficresf,"\n");
                   9722:        for(j=1;j<=cptcoveff;j++) 
1.332     brouard  9723:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Tvaraff not correct *\/ */
                   9724:          fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /* TnsdVar[Tvaraff]  correct */
1.296     brouard  9725:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  9726:        
                   9727:        for(j=1; j<=nlstate+ndeath;j++) {
                   9728:          ppij=0.;
                   9729:          for(i=1; i<=nlstate;i++) {
1.278     brouard  9730:            if (mobilav>=1)
                   9731:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   9732:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   9733:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   9734:            }
1.268     brouard  9735:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   9736:          } /* end i */
                   9737:          fprintf(ficresf," %.3f", ppij);
                   9738:        }/* end j */
1.227     brouard  9739:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9740:       } /* end agec */
1.266     brouard  9741:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   9742:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  9743:     } /* end yearp */
                   9744:   } /* end  k */
1.219     brouard  9745:        
1.126     brouard  9746:   fclose(ficresf);
1.215     brouard  9747:   printf("End of Computing forecasting \n");
                   9748:   fprintf(ficlog,"End of Computing forecasting\n");
                   9749: 
1.126     brouard  9750: }
                   9751: 
1.269     brouard  9752: /************** Back Forecasting ******************/
1.296     brouard  9753:  /* 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){ */
                   9754:  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){
                   9755:   /* back1, year, month, day of starting backprojection
1.267     brouard  9756:      agemin, agemax range of age
                   9757:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  9758:      anback2 year of end of backprojection (same day and month as back1).
                   9759:      prevacurrent and prev are prevalences.
1.267     brouard  9760:   */
                   9761:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   9762:   double agec; /* generic age */
1.302     brouard  9763:   double agelim, ppij, ppi, yp,yp1,yp2; /* ,jintmean,mintmean,aintmean;*/
1.267     brouard  9764:   double *popeffectif,*popcount;
                   9765:   double ***p3mat;
                   9766:   /* double ***mobaverage; */
                   9767:   char fileresfb[FILENAMELENGTH];
                   9768:  
1.268     brouard  9769:   agelim=AGEINF;
1.267     brouard  9770:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9771:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9772:      We still use firstpass and lastpass as another selection.
                   9773:   */
                   9774:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9775:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   9776: 
                   9777:   /*Do we need to compute prevalence again?*/
                   9778: 
                   9779:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   9780:   
                   9781:   strcpy(fileresfb,"FB_");
                   9782:   strcat(fileresfb,fileresu);
                   9783:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   9784:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   9785:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   9786:   }
                   9787:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   9788:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   9789:   
                   9790:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   9791:   
                   9792:    
                   9793:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9794:   if (stepm<=12) stepsize=1;
                   9795:   if(estepm < stepm){
                   9796:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9797:   }
1.270     brouard  9798:   else{
                   9799:     hstepm=estepm;   
                   9800:   }
                   9801:   if(estepm >= stepm){ /* Yes every two year */
                   9802:     stepsize=2;
                   9803:   }
1.267     brouard  9804:   
                   9805:   hstepm=hstepm/stepm;
1.296     brouard  9806:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9807:   /*                              fractional in yp1 *\/ */
                   9808:   /* aintmean=yp; */
                   9809:   /* yp2=modf((yp1*12),&yp); */
                   9810:   /* mintmean=yp; */
                   9811:   /* yp1=modf((yp2*30.5),&yp); */
                   9812:   /* jintmean=yp; */
                   9813:   /* if(jintmean==0) jintmean=1; */
                   9814:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  9815:   
                   9816:   i1=pow(2,cptcoveff);
                   9817:   if (cptcovn < 1){i1=1;}
                   9818:   
1.296     brouard  9819:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   9820:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  9821:   
                   9822:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   9823:   
                   9824:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9825:   for(k=1; k<=i1;k++){
                   9826:     if(i1 != 1 && TKresult[nres]!= k)
                   9827:       continue;
                   9828:     if(invalidvarcomb[k]){
                   9829:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   9830:       continue;
                   9831:     }
1.268     brouard  9832:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.267     brouard  9833:     for(j=1;j<=cptcoveff;j++) {
1.332     brouard  9834:       fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.267     brouard  9835:     }
                   9836:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   9837:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9838:     }
                   9839:     fprintf(ficresfb," yearbproj age");
                   9840:     for(j=1; j<=nlstate+ndeath;j++){
                   9841:       for(i=1; i<=nlstate;i++)
1.268     brouard  9842:        fprintf(ficresfb," b%d%d",i,j);
                   9843:       fprintf(ficresfb," b.%d",j);
1.267     brouard  9844:     }
1.296     brouard  9845:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  9846:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   9847:       fprintf(ficresfb,"\n");
1.296     brouard  9848:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  9849:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  9850:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   9851:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  9852:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  9853:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  9854:        nhstepm = nhstepm/hstepm;
                   9855:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9856:        oldm=oldms;savm=savms;
1.268     brouard  9857:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  9858:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  9859:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  9860:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   9861:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   9862:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  9863:        for (h=0; h<=nhstepm; h++){
1.268     brouard  9864:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   9865:            break;
                   9866:          }
                   9867:        }
                   9868:        fprintf(ficresfb,"\n");
                   9869:        for(j=1;j<=cptcoveff;j++)
1.332     brouard  9870:          fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.296     brouard  9871:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  9872:        for(i=1; i<=nlstate+ndeath;i++) {
                   9873:          ppij=0.;ppi=0.;
                   9874:          for(j=1; j<=nlstate;j++) {
                   9875:            /* if (mobilav==1) */
1.269     brouard  9876:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   9877:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   9878:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   9879:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  9880:              /* else { */
                   9881:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   9882:              /* } */
1.268     brouard  9883:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   9884:          } /* end j */
                   9885:          if(ppi <0.99){
                   9886:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   9887:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   9888:          }
                   9889:          fprintf(ficresfb," %.3f", ppij);
                   9890:        }/* end j */
1.267     brouard  9891:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9892:       } /* end agec */
                   9893:     } /* end yearp */
                   9894:   } /* end k */
1.217     brouard  9895:   
1.267     brouard  9896:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  9897:   
1.267     brouard  9898:   fclose(ficresfb);
                   9899:   printf("End of Computing Back forecasting \n");
                   9900:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  9901:        
1.267     brouard  9902: }
1.217     brouard  9903: 
1.269     brouard  9904: /* Variance of prevalence limit: varprlim */
                   9905:  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  9906:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  9907:  
                   9908:    char fileresvpl[FILENAMELENGTH];  
                   9909:    FILE *ficresvpl;
                   9910:    double **oldm, **savm;
                   9911:    double **varpl; /* Variances of prevalence limits by age */   
                   9912:    int i1, k, nres, j ;
                   9913:    
                   9914:     strcpy(fileresvpl,"VPL_");
                   9915:     strcat(fileresvpl,fileresu);
                   9916:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  9917:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  9918:       exit(0);
                   9919:     }
1.288     brouard  9920:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   9921:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  9922:     
                   9923:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   9924:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   9925:     
                   9926:     i1=pow(2,cptcoveff);
                   9927:     if (cptcovn < 1){i1=1;}
                   9928: 
1.337     brouard  9929:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9930:        k=TKresult[nres];
1.338     brouard  9931:        if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  9932:      /* for(k=1; k<=i1;k++){ /\* We find the combination equivalent to result line values of dummies *\/ */
1.269     brouard  9933:       if(i1 != 1 && TKresult[nres]!= k)
                   9934:        continue;
                   9935:       fprintf(ficresvpl,"\n#****** ");
                   9936:       printf("\n#****** ");
                   9937:       fprintf(ficlog,"\n#****** ");
1.337     brouard  9938:       for(j=1;j<=cptcovs;j++) {
                   9939:        fprintf(ficresvpl,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   9940:        fprintf(ficlog,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   9941:        printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   9942:        /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   9943:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.269     brouard  9944:       }
1.337     brouard  9945:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   9946:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9947:       /*       fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9948:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9949:       /* }      */
1.269     brouard  9950:       fprintf(ficresvpl,"******\n");
                   9951:       printf("******\n");
                   9952:       fprintf(ficlog,"******\n");
                   9953:       
                   9954:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9955:       oldm=oldms;savm=savms;
                   9956:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   9957:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   9958:       /*}*/
                   9959:     }
                   9960:     
                   9961:     fclose(ficresvpl);
1.288     brouard  9962:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   9963:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  9964: 
                   9965:  }
                   9966: /* Variance of back prevalence: varbprlim */
                   9967:  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){
                   9968:       /*------- Variance of back (stable) prevalence------*/
                   9969: 
                   9970:    char fileresvbl[FILENAMELENGTH];  
                   9971:    FILE  *ficresvbl;
                   9972: 
                   9973:    double **oldm, **savm;
                   9974:    double **varbpl; /* Variances of back prevalence limits by age */   
                   9975:    int i1, k, nres, j ;
                   9976: 
                   9977:    strcpy(fileresvbl,"VBL_");
                   9978:    strcat(fileresvbl,fileresu);
                   9979:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   9980:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   9981:      exit(0);
                   9982:    }
                   9983:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   9984:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   9985:    
                   9986:    
                   9987:    i1=pow(2,cptcoveff);
                   9988:    if (cptcovn < 1){i1=1;}
                   9989:    
1.337     brouard  9990:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9991:      k=TKresult[nres];
1.338     brouard  9992:      if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  9993:     /* for(k=1; k<=i1;k++){ */
                   9994:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   9995:     /*          continue; */
1.269     brouard  9996:        fprintf(ficresvbl,"\n#****** ");
                   9997:        printf("\n#****** ");
                   9998:        fprintf(ficlog,"\n#****** ");
1.337     brouard  9999:        for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */
1.338     brouard  10000:         printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   10001:         fprintf(ficresvbl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   10002:         fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
1.337     brouard  10003:        /* for(j=1;j<=cptcoveff;j++) { */
                   10004:        /*       fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10005:        /*       fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10006:        /*       printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10007:        /* } */
                   10008:        /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   10009:        /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10010:        /*       fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10011:        /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
1.269     brouard  10012:        }
                   10013:        fprintf(ficresvbl,"******\n");
                   10014:        printf("******\n");
                   10015:        fprintf(ficlog,"******\n");
                   10016:        
                   10017:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   10018:        oldm=oldms;savm=savms;
                   10019:        
                   10020:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   10021:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   10022:        /*}*/
                   10023:      }
                   10024:    
                   10025:    fclose(ficresvbl);
                   10026:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   10027:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   10028: 
                   10029:  } /* End of varbprlim */
                   10030: 
1.126     brouard  10031: /************** Forecasting *****not tested NB*************/
1.227     brouard  10032: /* 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  10033:   
1.227     brouard  10034: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   10035: /*   int *popage; */
                   10036: /*   double calagedatem, agelim, kk1, kk2; */
                   10037: /*   double *popeffectif,*popcount; */
                   10038: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   10039: /*   /\* double ***mobaverage; *\/ */
                   10040: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  10041: 
1.227     brouard  10042: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10043: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10044: /*   agelim=AGESUP; */
                   10045: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  10046:   
1.227     brouard  10047: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  10048:   
                   10049:   
1.227     brouard  10050: /*   strcpy(filerespop,"POP_");  */
                   10051: /*   strcat(filerespop,fileresu); */
                   10052: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   10053: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   10054: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   10055: /*   } */
                   10056: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   10057: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  10058: 
1.227     brouard  10059: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  10060: 
1.227     brouard  10061: /*   /\* if (mobilav!=0) { *\/ */
                   10062: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   10063: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   10064: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   10065: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   10066: /*   /\*   } *\/ */
                   10067: /*   /\* } *\/ */
1.126     brouard  10068: 
1.227     brouard  10069: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   10070: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  10071:   
1.227     brouard  10072: /*   agelim=AGESUP; */
1.126     brouard  10073:   
1.227     brouard  10074: /*   hstepm=1; */
                   10075: /*   hstepm=hstepm/stepm;  */
1.218     brouard  10076:        
1.227     brouard  10077: /*   if (popforecast==1) { */
                   10078: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   10079: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   10080: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   10081: /*     }  */
                   10082: /*     popage=ivector(0,AGESUP); */
                   10083: /*     popeffectif=vector(0,AGESUP); */
                   10084: /*     popcount=vector(0,AGESUP); */
1.126     brouard  10085:     
1.227     brouard  10086: /*     i=1;    */
                   10087: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  10088:     
1.227     brouard  10089: /*     imx=i; */
                   10090: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   10091: /*   } */
1.218     brouard  10092:   
1.227     brouard  10093: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   10094: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   10095: /*       k=k+1; */
                   10096: /*       fprintf(ficrespop,"\n#******"); */
                   10097: /*       for(j=1;j<=cptcoveff;j++) { */
                   10098: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   10099: /*       } */
                   10100: /*       fprintf(ficrespop,"******\n"); */
                   10101: /*       fprintf(ficrespop,"# Age"); */
                   10102: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   10103: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  10104:       
1.227     brouard  10105: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   10106: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  10107:        
1.227     brouard  10108: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   10109: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   10110: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  10111:          
1.227     brouard  10112: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10113: /*       oldm=oldms;savm=savms; */
                   10114: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  10115:          
1.227     brouard  10116: /*       for (h=0; h<=nhstepm; h++){ */
                   10117: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   10118: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   10119: /*         }  */
                   10120: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   10121: /*           kk1=0.;kk2=0; */
                   10122: /*           for(i=1; i<=nlstate;i++) {               */
                   10123: /*             if (mobilav==1)  */
                   10124: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   10125: /*             else { */
                   10126: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   10127: /*             } */
                   10128: /*           } */
                   10129: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   10130: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   10131: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   10132: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   10133: /*           } */
                   10134: /*         } */
                   10135: /*         for(i=1; i<=nlstate;i++){ */
                   10136: /*           kk1=0.; */
                   10137: /*           for(j=1; j<=nlstate;j++){ */
                   10138: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   10139: /*           } */
                   10140: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   10141: /*         } */
1.218     brouard  10142:            
1.227     brouard  10143: /*         if (h==(int)(calagedatem+12*cpt)) */
                   10144: /*           for(j=1; j<=nlstate;j++)  */
                   10145: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   10146: /*       } */
                   10147: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10148: /*     } */
                   10149: /*       } */
1.218     brouard  10150:       
1.227     brouard  10151: /*       /\******\/ */
1.218     brouard  10152:       
1.227     brouard  10153: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   10154: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   10155: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   10156: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   10157: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  10158:          
1.227     brouard  10159: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10160: /*       oldm=oldms;savm=savms; */
                   10161: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   10162: /*       for (h=0; h<=nhstepm; h++){ */
                   10163: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   10164: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   10165: /*         }  */
                   10166: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   10167: /*           kk1=0.;kk2=0; */
                   10168: /*           for(i=1; i<=nlstate;i++) {               */
                   10169: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   10170: /*           } */
                   10171: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   10172: /*         } */
                   10173: /*       } */
                   10174: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10175: /*     } */
                   10176: /*       } */
                   10177: /*     }  */
                   10178: /*   } */
1.218     brouard  10179:   
1.227     brouard  10180: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  10181:   
1.227     brouard  10182: /*   if (popforecast==1) { */
                   10183: /*     free_ivector(popage,0,AGESUP); */
                   10184: /*     free_vector(popeffectif,0,AGESUP); */
                   10185: /*     free_vector(popcount,0,AGESUP); */
                   10186: /*   } */
                   10187: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10188: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10189: /*   fclose(ficrespop); */
                   10190: /* } /\* End of popforecast *\/ */
1.218     brouard  10191:  
1.126     brouard  10192: int fileappend(FILE *fichier, char *optionfich)
                   10193: {
                   10194:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   10195:     printf("Problem with file: %s\n", optionfich);
                   10196:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   10197:     return (0);
                   10198:   }
                   10199:   fflush(fichier);
                   10200:   return (1);
                   10201: }
                   10202: 
                   10203: 
                   10204: /**************** function prwizard **********************/
                   10205: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   10206: {
                   10207: 
                   10208:   /* Wizard to print covariance matrix template */
                   10209: 
1.164     brouard  10210:   char ca[32], cb[32];
                   10211:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  10212:   int numlinepar;
                   10213: 
                   10214:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10215:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10216:   for(i=1; i <=nlstate; i++){
                   10217:     jj=0;
                   10218:     for(j=1; j <=nlstate+ndeath; j++){
                   10219:       if(j==i) continue;
                   10220:       jj++;
                   10221:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   10222:       printf("%1d%1d",i,j);
                   10223:       fprintf(ficparo,"%1d%1d",i,j);
                   10224:       for(k=1; k<=ncovmodel;k++){
                   10225:        /*        printf(" %lf",param[i][j][k]); */
                   10226:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   10227:        printf(" 0.");
                   10228:        fprintf(ficparo," 0.");
                   10229:       }
                   10230:       printf("\n");
                   10231:       fprintf(ficparo,"\n");
                   10232:     }
                   10233:   }
                   10234:   printf("# Scales (for hessian or gradient estimation)\n");
                   10235:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   10236:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   10237:   for(i=1; i <=nlstate; i++){
                   10238:     jj=0;
                   10239:     for(j=1; j <=nlstate+ndeath; j++){
                   10240:       if(j==i) continue;
                   10241:       jj++;
                   10242:       fprintf(ficparo,"%1d%1d",i,j);
                   10243:       printf("%1d%1d",i,j);
                   10244:       fflush(stdout);
                   10245:       for(k=1; k<=ncovmodel;k++){
                   10246:        /*      printf(" %le",delti3[i][j][k]); */
                   10247:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   10248:        printf(" 0.");
                   10249:        fprintf(ficparo," 0.");
                   10250:       }
                   10251:       numlinepar++;
                   10252:       printf("\n");
                   10253:       fprintf(ficparo,"\n");
                   10254:     }
                   10255:   }
                   10256:   printf("# Covariance matrix\n");
                   10257: /* # 121 Var(a12)\n\ */
                   10258: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10259: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   10260: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   10261: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   10262: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   10263: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   10264: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   10265:   fflush(stdout);
                   10266:   fprintf(ficparo,"# Covariance matrix\n");
                   10267:   /* # 121 Var(a12)\n\ */
                   10268:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10269:   /* #   ...\n\ */
                   10270:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   10271:   
                   10272:   for(itimes=1;itimes<=2;itimes++){
                   10273:     jj=0;
                   10274:     for(i=1; i <=nlstate; i++){
                   10275:       for(j=1; j <=nlstate+ndeath; j++){
                   10276:        if(j==i) continue;
                   10277:        for(k=1; k<=ncovmodel;k++){
                   10278:          jj++;
                   10279:          ca[0]= k+'a'-1;ca[1]='\0';
                   10280:          if(itimes==1){
                   10281:            printf("#%1d%1d%d",i,j,k);
                   10282:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   10283:          }else{
                   10284:            printf("%1d%1d%d",i,j,k);
                   10285:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   10286:            /*  printf(" %.5le",matcov[i][j]); */
                   10287:          }
                   10288:          ll=0;
                   10289:          for(li=1;li <=nlstate; li++){
                   10290:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   10291:              if(lj==li) continue;
                   10292:              for(lk=1;lk<=ncovmodel;lk++){
                   10293:                ll++;
                   10294:                if(ll<=jj){
                   10295:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   10296:                  if(ll<jj){
                   10297:                    if(itimes==1){
                   10298:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10299:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10300:                    }else{
                   10301:                      printf(" 0.");
                   10302:                      fprintf(ficparo," 0.");
                   10303:                    }
                   10304:                  }else{
                   10305:                    if(itimes==1){
                   10306:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   10307:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   10308:                    }else{
                   10309:                      printf(" 0.");
                   10310:                      fprintf(ficparo," 0.");
                   10311:                    }
                   10312:                  }
                   10313:                }
                   10314:              } /* end lk */
                   10315:            } /* end lj */
                   10316:          } /* end li */
                   10317:          printf("\n");
                   10318:          fprintf(ficparo,"\n");
                   10319:          numlinepar++;
                   10320:        } /* end k*/
                   10321:       } /*end j */
                   10322:     } /* end i */
                   10323:   } /* end itimes */
                   10324: 
                   10325: } /* end of prwizard */
                   10326: /******************* Gompertz Likelihood ******************************/
                   10327: double gompertz(double x[])
                   10328: { 
1.302     brouard  10329:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
1.126     brouard  10330:   int i,n=0; /* n is the size of the sample */
                   10331: 
1.220     brouard  10332:   for (i=1;i<=imx ; i++) {
1.126     brouard  10333:     sump=sump+weight[i];
                   10334:     /*    sump=sump+1;*/
                   10335:     num=num+1;
                   10336:   }
1.302     brouard  10337:   L=0.0;
                   10338:   /* agegomp=AGEGOMP; */
1.126     brouard  10339:   /* for (i=0; i<=imx; i++) 
                   10340:      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]);*/
                   10341: 
1.302     brouard  10342:   for (i=1;i<=imx ; i++) {
                   10343:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   10344:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   10345:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   10346:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   10347:      * +
                   10348:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   10349:      */
                   10350:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   10351:        if (cens[i] == 1){
                   10352:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   10353:        } else if (cens[i] == 0){
1.126     brouard  10354:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
1.302     brouard  10355:          +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   10356:       } else
                   10357:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
1.126     brouard  10358:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
1.302     brouard  10359:        L=L+A*weight[i];
1.126     brouard  10360:        /*      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  10361:      }
                   10362:   }
1.126     brouard  10363: 
1.302     brouard  10364:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
1.126     brouard  10365:  
                   10366:   return -2*L*num/sump;
                   10367: }
                   10368: 
1.136     brouard  10369: #ifdef GSL
                   10370: /******************* Gompertz_f Likelihood ******************************/
                   10371: double gompertz_f(const gsl_vector *v, void *params)
                   10372: { 
1.302     brouard  10373:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
1.136     brouard  10374:   double *x= (double *) v->data;
                   10375:   int i,n=0; /* n is the size of the sample */
                   10376: 
                   10377:   for (i=0;i<=imx-1 ; i++) {
                   10378:     sump=sump+weight[i];
                   10379:     /*    sump=sump+1;*/
                   10380:     num=num+1;
                   10381:   }
                   10382:  
                   10383:  
                   10384:   /* for (i=0; i<=imx; i++) 
                   10385:      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]);*/
                   10386:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   10387:   for (i=1;i<=imx ; i++)
                   10388:     {
                   10389:       if (cens[i] == 1 && wav[i]>1)
                   10390:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   10391:       
                   10392:       if (cens[i] == 0 && wav[i]>1)
                   10393:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   10394:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   10395:       
                   10396:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   10397:       if (wav[i] > 1 ) { /* ??? */
                   10398:        LL=LL+A*weight[i];
                   10399:        /*      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]);*/
                   10400:       }
                   10401:     }
                   10402: 
                   10403:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   10404:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   10405:  
                   10406:   return -2*LL*num/sump;
                   10407: }
                   10408: #endif
                   10409: 
1.126     brouard  10410: /******************* Printing html file ***********/
1.201     brouard  10411: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  10412:                  int lastpass, int stepm, int weightopt, char model[],\
                   10413:                  int imx,  double p[],double **matcov,double agemortsup){
                   10414:   int i,k;
                   10415: 
                   10416:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   10417:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   10418:   for (i=1;i<=2;i++) 
                   10419:     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  10420:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  10421:   fprintf(fichtm,"</ul>");
                   10422: 
                   10423: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   10424: 
                   10425:  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>");
                   10426: 
                   10427:  for (k=agegomp;k<(agemortsup-2);k++) 
                   10428:    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]);
                   10429: 
                   10430:  
                   10431:   fflush(fichtm);
                   10432: }
                   10433: 
                   10434: /******************* Gnuplot file **************/
1.201     brouard  10435: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  10436: 
                   10437:   char dirfileres[132],optfileres[132];
1.164     brouard  10438: 
1.126     brouard  10439:   int ng;
                   10440: 
                   10441: 
                   10442:   /*#ifdef windows */
                   10443:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   10444:     /*#endif */
                   10445: 
                   10446: 
                   10447:   strcpy(dirfileres,optionfilefiname);
                   10448:   strcpy(optfileres,"vpl");
1.199     brouard  10449:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  10450:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  10451:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  10452:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  10453:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   10454: 
                   10455: } 
                   10456: 
1.136     brouard  10457: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   10458: {
1.126     brouard  10459: 
1.136     brouard  10460:   /*-------- data file ----------*/
                   10461:   FILE *fic;
                   10462:   char dummy[]="                         ";
1.240     brouard  10463:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  10464:   int lstra;
1.136     brouard  10465:   int linei, month, year,iout;
1.302     brouard  10466:   int noffset=0; /* This is the offset if BOM data file */
1.136     brouard  10467:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  10468:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  10469:   char *stratrunc;
1.223     brouard  10470: 
1.240     brouard  10471:   DummyV=ivector(1,NCOVMAX); /* 1 to 3 */
                   10472:   FixedV=ivector(1,NCOVMAX); /* 1 to 3 */
1.328     brouard  10473:   for(v=1;v<NCOVMAX;v++){
                   10474:     DummyV[v]=0;
                   10475:     FixedV[v]=0;
                   10476:   }
1.126     brouard  10477: 
1.240     brouard  10478:   for(v=1; v <=ncovcol;v++){
                   10479:     DummyV[v]=0;
                   10480:     FixedV[v]=0;
                   10481:   }
                   10482:   for(v=ncovcol+1; v <=ncovcol+nqv;v++){
                   10483:     DummyV[v]=1;
                   10484:     FixedV[v]=0;
                   10485:   }
                   10486:   for(v=ncovcol+nqv+1; v <=ncovcol+nqv+ntv;v++){
                   10487:     DummyV[v]=0;
                   10488:     FixedV[v]=1;
                   10489:   }
                   10490:   for(v=ncovcol+nqv+ntv+1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   10491:     DummyV[v]=1;
                   10492:     FixedV[v]=1;
                   10493:   }
                   10494:   for(v=1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   10495:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   10496:     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]);
                   10497:   }
1.339     brouard  10498:   
                   10499:   ncovcolt=ncovcol+nqv+ntv+nqtv; /* total of covariates in the data, not in the model equation */
                   10500:   
1.136     brouard  10501:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  10502:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10503:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  10504:   }
1.126     brouard  10505: 
1.302     brouard  10506:     /* Is it a BOM UTF-8 Windows file? */
                   10507:   /* First data line */
                   10508:   linei=0;
                   10509:   while(fgets(line, MAXLINE, fic)) {
                   10510:     noffset=0;
                   10511:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   10512:     {
                   10513:       noffset=noffset+3;
                   10514:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   10515:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   10516:       fflush(ficlog); return 1;
                   10517:     }
                   10518:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   10519:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   10520:     {
                   10521:       noffset=noffset+2;
1.304     brouard  10522:       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);
                   10523:       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  10524:       fflush(ficlog); return 1;
                   10525:     }
                   10526:     else if( line[0] == 0 && line[1] == 0)
                   10527:     {
                   10528:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   10529:        noffset=noffset+4;
1.304     brouard  10530:        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);
                   10531:        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  10532:        fflush(ficlog); return 1;
                   10533:       }
                   10534:     } else{
                   10535:       ;/*printf(" Not a BOM file\n");*/
                   10536:     }
                   10537:         /* If line starts with a # it is a comment */
                   10538:     if (line[noffset] == '#') {
                   10539:       linei=linei+1;
                   10540:       break;
                   10541:     }else{
                   10542:       break;
                   10543:     }
                   10544:   }
                   10545:   fclose(fic);
                   10546:   if((fic=fopen(datafile,"r"))==NULL)    {
                   10547:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10548:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   10549:   }
                   10550:   /* Not a Bom file */
                   10551:   
1.136     brouard  10552:   i=1;
                   10553:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   10554:     linei=linei+1;
                   10555:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   10556:       if(line[j] == '\t')
                   10557:        line[j] = ' ';
                   10558:     }
                   10559:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   10560:       ;
                   10561:     };
                   10562:     line[j+1]=0;  /* Trims blanks at end of line */
                   10563:     if(line[0]=='#'){
                   10564:       fprintf(ficlog,"Comment line\n%s\n",line);
                   10565:       printf("Comment line\n%s\n",line);
                   10566:       continue;
                   10567:     }
                   10568:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  10569:     strcpy(line, linetmp);
1.223     brouard  10570:     
                   10571:     /* Loops on waves */
                   10572:     for (j=maxwav;j>=1;j--){
                   10573:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  10574:        cutv(stra, strb, line, ' '); 
                   10575:        if(strb[0]=='.') { /* Missing value */
                   10576:          lval=-1;
                   10577:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
1.341     brouard  10578:          cotvar[j][ncovcol+nqv+ntv+iv][i]=-1; /* For performance reasons */
1.238     brouard  10579:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   10580:            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);
                   10581:            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);
                   10582:            return 1;
                   10583:          }
                   10584:        }else{
                   10585:          errno=0;
                   10586:          /* what_kind_of_number(strb); */
                   10587:          dval=strtod(strb,&endptr); 
                   10588:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   10589:          /* if(strb != endptr && *endptr == '\0') */
                   10590:          /*    dval=dlval; */
                   10591:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10592:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10593:            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);
                   10594:            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);
                   10595:            return 1;
                   10596:          }
                   10597:          cotqvar[j][iv][i]=dval; 
1.341     brouard  10598:          cotvar[j][ncovcol+nqv+ntv+iv][i]=dval; /* because cotvar starts now at first ntv */ 
1.238     brouard  10599:        }
                   10600:        strcpy(line,stra);
1.223     brouard  10601:       }/* end loop ntqv */
1.225     brouard  10602:       
1.223     brouard  10603:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  10604:        cutv(stra, strb, line, ' '); 
                   10605:        if(strb[0]=='.') { /* Missing value */
                   10606:          lval=-1;
                   10607:        }else{
                   10608:          errno=0;
                   10609:          lval=strtol(strb,&endptr,10); 
                   10610:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   10611:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10612:            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);
                   10613:            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);
                   10614:            return 1;
                   10615:          }
                   10616:        }
                   10617:        if(lval <-1 || lval >1){
                   10618:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10619:  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  10620:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10621:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10622:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10623:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10624:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10625:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10626:  Exiting.\n",lval,linei, i,line,iv,j);
1.238     brouard  10627:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10628:  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  10629:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10630:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10631:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10632:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10633:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10634:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10635:  Exiting.\n",lval,linei, i,line,iv,j);fflush(ficlog);
1.238     brouard  10636:          return 1;
                   10637:        }
1.341     brouard  10638:        cotvar[j][ncovcol+nqv+iv][i]=(double)(lval);
1.238     brouard  10639:        strcpy(line,stra);
1.223     brouard  10640:       }/* end loop ntv */
1.225     brouard  10641:       
1.223     brouard  10642:       /* Statuses  at wave */
1.137     brouard  10643:       cutv(stra, strb, line, ' '); 
1.223     brouard  10644:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  10645:        lval=-1;
1.136     brouard  10646:       }else{
1.238     brouard  10647:        errno=0;
                   10648:        lval=strtol(strb,&endptr,10); 
                   10649:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   10650:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10651:          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);
                   10652:          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);
                   10653:          return 1;
                   10654:        }
1.136     brouard  10655:       }
1.225     brouard  10656:       
1.136     brouard  10657:       s[j][i]=lval;
1.225     brouard  10658:       
1.223     brouard  10659:       /* Date of Interview */
1.136     brouard  10660:       strcpy(line,stra);
                   10661:       cutv(stra, strb,line,' ');
1.169     brouard  10662:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10663:       }
1.169     brouard  10664:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  10665:        month=99;
                   10666:        year=9999;
1.136     brouard  10667:       }else{
1.225     brouard  10668:        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);
                   10669:        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);
                   10670:        return 1;
1.136     brouard  10671:       }
                   10672:       anint[j][i]= (double) year; 
1.302     brouard  10673:       mint[j][i]= (double)month;
                   10674:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   10675:       /*       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]); */
                   10676:       /*       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]); */
                   10677:       /* } */
1.136     brouard  10678:       strcpy(line,stra);
1.223     brouard  10679:     } /* End loop on waves */
1.225     brouard  10680:     
1.223     brouard  10681:     /* Date of death */
1.136     brouard  10682:     cutv(stra, strb,line,' '); 
1.169     brouard  10683:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10684:     }
1.169     brouard  10685:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  10686:       month=99;
                   10687:       year=9999;
                   10688:     }else{
1.141     brouard  10689:       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  10690:       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);
                   10691:       return 1;
1.136     brouard  10692:     }
                   10693:     andc[i]=(double) year; 
                   10694:     moisdc[i]=(double) month; 
                   10695:     strcpy(line,stra);
                   10696:     
1.223     brouard  10697:     /* Date of birth */
1.136     brouard  10698:     cutv(stra, strb,line,' '); 
1.169     brouard  10699:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10700:     }
1.169     brouard  10701:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  10702:       month=99;
                   10703:       year=9999;
                   10704:     }else{
1.141     brouard  10705:       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);
                   10706:       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  10707:       return 1;
1.136     brouard  10708:     }
                   10709:     if (year==9999) {
1.141     brouard  10710:       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);
                   10711:       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  10712:       return 1;
                   10713:       
1.136     brouard  10714:     }
                   10715:     annais[i]=(double)(year);
1.302     brouard  10716:     moisnais[i]=(double)(month);
                   10717:     for (j=1;j<=maxwav;j++){
                   10718:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   10719:        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]);
                   10720:        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]);
                   10721:       }
                   10722:     }
                   10723: 
1.136     brouard  10724:     strcpy(line,stra);
1.225     brouard  10725:     
1.223     brouard  10726:     /* Sample weight */
1.136     brouard  10727:     cutv(stra, strb,line,' '); 
                   10728:     errno=0;
                   10729:     dval=strtod(strb,&endptr); 
                   10730:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  10731:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   10732:       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  10733:       fflush(ficlog);
                   10734:       return 1;
                   10735:     }
                   10736:     weight[i]=dval; 
                   10737:     strcpy(line,stra);
1.225     brouard  10738:     
1.223     brouard  10739:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   10740:       cutv(stra, strb, line, ' '); 
                   10741:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  10742:        lval=-1;
1.311     brouard  10743:        coqvar[iv][i]=NAN; 
                   10744:        covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  10745:       }else{
1.225     brouard  10746:        errno=0;
                   10747:        /* what_kind_of_number(strb); */
                   10748:        dval=strtod(strb,&endptr);
                   10749:        /* if(strb != endptr && *endptr == '\0') */
                   10750:        /*   dval=dlval; */
                   10751:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10752:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10753:          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);
                   10754:          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);
                   10755:          return 1;
                   10756:        }
                   10757:        coqvar[iv][i]=dval; 
1.226     brouard  10758:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  10759:       }
                   10760:       strcpy(line,stra);
                   10761:     }/* end loop nqv */
1.136     brouard  10762:     
1.223     brouard  10763:     /* Covariate values */
1.136     brouard  10764:     for (j=ncovcol;j>=1;j--){
                   10765:       cutv(stra, strb,line,' '); 
1.223     brouard  10766:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  10767:        lval=-1;
1.136     brouard  10768:       }else{
1.225     brouard  10769:        errno=0;
                   10770:        lval=strtol(strb,&endptr,10); 
                   10771:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10772:          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);
                   10773:          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);
                   10774:          return 1;
                   10775:        }
1.136     brouard  10776:       }
                   10777:       if(lval <-1 || lval >1){
1.225     brouard  10778:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  10779:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   10780:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  10781:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10782:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10783:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  10784:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  10785:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  10786:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  10787:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  10788:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   10789:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  10790:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10791:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10792:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  10793:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  10794:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  10795:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  10796:        return 1;
1.136     brouard  10797:       }
                   10798:       covar[j][i]=(double)(lval);
                   10799:       strcpy(line,stra);
                   10800:     }  
                   10801:     lstra=strlen(stra);
1.225     brouard  10802:     
1.136     brouard  10803:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   10804:       stratrunc = &(stra[lstra-9]);
                   10805:       num[i]=atol(stratrunc);
                   10806:     }
                   10807:     else
                   10808:       num[i]=atol(stra);
                   10809:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   10810:       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;}*/
                   10811:     
                   10812:     i=i+1;
                   10813:   } /* End loop reading  data */
1.225     brouard  10814:   
1.136     brouard  10815:   *imax=i-1; /* Number of individuals */
                   10816:   fclose(fic);
1.225     brouard  10817:   
1.136     brouard  10818:   return (0);
1.164     brouard  10819:   /* endread: */
1.225     brouard  10820:   printf("Exiting readdata: ");
                   10821:   fclose(fic);
                   10822:   return (1);
1.223     brouard  10823: }
1.126     brouard  10824: 
1.234     brouard  10825: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  10826:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  10827:   while (*p2 == ' ')
1.234     brouard  10828:     p2++; 
                   10829:   /* while ((*p1++ = *p2++) !=0) */
                   10830:   /*   ; */
                   10831:   /* do */
                   10832:   /*   while (*p2 == ' ') */
                   10833:   /*     p2++; */
                   10834:   /* while (*p1++ == *p2++); */
                   10835:   *stri=p2; 
1.145     brouard  10836: }
                   10837: 
1.330     brouard  10838: int decoderesult( char resultline[], int nres)
1.230     brouard  10839: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   10840: {
1.235     brouard  10841:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  10842:   char resultsav[MAXLINE];
1.330     brouard  10843:   /* int resultmodel[MAXLINE]; */
1.334     brouard  10844:   /* int modelresult[MAXLINE]; */
1.230     brouard  10845:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   10846: 
1.234     brouard  10847:   removefirstspace(&resultline);
1.332     brouard  10848:   printf("decoderesult:%s\n",resultline);
1.230     brouard  10849: 
1.332     brouard  10850:   strcpy(resultsav,resultline);
1.342     brouard  10851:   /* printf("Decoderesult resultsav=\"%s\" resultline=\"%s\"\n", resultsav, resultline); */
1.230     brouard  10852:   if (strlen(resultsav) >1){
1.334     brouard  10853:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' in this resultline */
1.230     brouard  10854:   }
1.253     brouard  10855:   if(j == 0){ /* Resultline but no = */
                   10856:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   10857:     return (0);
                   10858:   }
1.234     brouard  10859:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
1.334     brouard  10860:     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);
                   10861:     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  10862:     /* return 1;*/
1.234     brouard  10863:   }
1.334     brouard  10864:   for(k=1; k<=j;k++){ /* Loop on any covariate of the RESULT LINE */
1.234     brouard  10865:     if(nbocc(resultsav,'=') >1){
1.318     brouard  10866:       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  10867:       /* 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  10868:       cutl(strc,strd,strb,'=');  /* strb:"V4=1" strc="1" strd="V4" */
1.332     brouard  10869:       /* If a blank, then strc="V4=" and strd='\0' */
                   10870:       if(strc[0]=='\0'){
                   10871:       printf("Error in resultline, probably a blank after the \"%s\", \"result:%s\", stra=\"%s\" resultsav=\"%s\"\n",strb,resultline, stra, resultsav);
                   10872:        fprintf(ficlog,"Error in resultline, probably a blank after the \"V%s=\", resultline=%s\n",strb,resultline);
                   10873:        return 1;
                   10874:       }
1.234     brouard  10875:     }else
                   10876:       cutl(strc,strd,resultsav,'=');
1.318     brouard  10877:     Tvalsel[k]=atof(strc); /* 1 */ /* Tvalsel of k is the float value of the kth covariate appearing in this result line */
1.234     brouard  10878:     
1.230     brouard  10879:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
1.318     brouard  10880:     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  10881:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   10882:     /* cptcovsel++;     */
                   10883:     if (nbocc(stra,'=') >0)
                   10884:       strcpy(resultsav,stra); /* and analyzes it */
                   10885:   }
1.235     brouard  10886:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  10887:   /* 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  10888:   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  10889:     if(Typevar[k1]==0){ /* Single covariate in model */
                   10890:       /* 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.234     brouard  10891:       match=0;
1.318     brouard  10892:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10893:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  10894:          modelresult[nres][k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.318     brouard  10895:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
1.234     brouard  10896:          break;
                   10897:        }
                   10898:       }
                   10899:       if(match == 0){
1.338     brouard  10900:        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]);
                   10901:        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  10902:        return 1;
1.234     brouard  10903:       }
1.332     brouard  10904:     }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*/
                   10905:       /* We feed resultmodel[k1]=k2; */
                   10906:       match=0;
                   10907:       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 */
                   10908:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  10909:          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  10910:          resultmodel[nres][k1]=k2; /* Added here */
1.342     brouard  10911:          /* printf("Decoderesult first modelresult[k2=%d]=%d (k1) V%d*AGE\n",k2,k1,Tvar[k1]); */
1.332     brouard  10912:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10913:          break;
                   10914:        }
                   10915:       }
                   10916:       if(match == 0){
1.338     brouard  10917:        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]);
                   10918:        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  10919:       return 1;
                   10920:       }
                   10921:     }else if(Typevar[k1]==2){ /* Product No age We want to get the position in the resultline of the product in the model line*/
                   10922:       /* resultmodel[nres][of such a Vn * Vm product k1] is not unique, so can't exist, we feed Tvard[k1][1] and [2] */ 
                   10923:       match=0;
1.342     brouard  10924:       /* 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  10925:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10926:        if(Tvardk[k1][1]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   10927:          /* modelresult[k2]=k1; */
1.342     brouard  10928:          /* printf("Decoderesult first Product modelresult[k2=%d]=%d (k1) V%d * \n",k2,k1,Tvarsel[k2]); */
1.332     brouard  10929:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10930:        }
                   10931:       }
                   10932:       if(match == 0){
1.338     brouard  10933:        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);
                   10934:        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  10935:        return 1;
                   10936:       }
                   10937:       match=0;
                   10938:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10939:        if(Tvardk[k1][2]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   10940:          /* modelresult[k2]=k1;*/
1.342     brouard  10941:          /* printf("Decoderesult second Product modelresult[k2=%d]=%d (k1) * V%d \n ",k2,k1,Tvarsel[k2]); */
1.332     brouard  10942:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10943:          break;
                   10944:        }
                   10945:       }
                   10946:       if(match == 0){
1.338     brouard  10947:        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);
                   10948:        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  10949:        return 1;
                   10950:       }
                   10951:     }/* End of testing */
1.333     brouard  10952:   }/* End loop cptcovt */
1.235     brouard  10953:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  10954:   /* Feeds resultmodel[nres][k1]=k2 for single covariate (k1) in the model equation */
1.334     brouard  10955:   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)
                   10956:                           * Loop on resultline variables: result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  10957:     match=0;
1.318     brouard  10958:     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  10959:       if(Typevar[k1]==0){ /* Single only */
1.237     brouard  10960:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4   */
1.330     brouard  10961:          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  10962:          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  10963:          ++match;
                   10964:        }
                   10965:       }
                   10966:     }
                   10967:     if(match == 0){
1.338     brouard  10968:       printf("Error in result line: variable V%d is missing in model; result: %s, model=1+age+%s\n",Tvarsel[k2], resultline, model);
                   10969:       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  10970:       return 1;
1.234     brouard  10971:     }else if(match > 1){
1.338     brouard  10972:       printf("Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
                   10973:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
1.310     brouard  10974:       return 1;
1.234     brouard  10975:     }
                   10976:   }
1.334     brouard  10977:   /* cptcovres=j /\* Number of variables in the resultline is equal to cptcovs and thus useless *\/     */
1.234     brouard  10978:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  10979:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.330     brouard  10980:   /* nres=1st result line: V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   10981:   /* 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*/
                   10982:   /* nres=2nd result line: V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.235     brouard  10983:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   10984:   /*    1 0 0 0 */
                   10985:   /*    2 1 0 0 */
                   10986:   /*    3 0 1 0 */ 
1.330     brouard  10987:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 (nres=2)*/
1.235     brouard  10988:   /*    5 0 0 1 */
1.330     brouard  10989:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 (nres=1)*/
1.235     brouard  10990:   /*    7 0 1 1 */
                   10991:   /*    8 1 1 1 */
1.237     brouard  10992:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   10993:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   10994:   /* V5*age V5 known which value for nres?  */
                   10995:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.334     brouard  10996:   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.
                   10997:                                                   * loop on position k1 in the MODEL LINE */
1.331     brouard  10998:     /* k counting number of combination of single dummies in the equation model */
                   10999:     /* k4 counting single dummies in the equation model */
                   11000:     /* k4q counting single quantitatives in the equation model */
1.344     brouard  11001:     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  11002:        /* 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  11003:       /* 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  11004:       /* Value in the (current nres) resultline of the variable at the k1th position in the model equation resultmodel[nres][k1]= k3 */
1.332     brouard  11005:       /* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline                        */
                   11006:       /*      k3 is the position in the nres result line of the k1th variable of the model equation                                  */
                   11007:       /* Tvarsel[k3]: Name of the variable at the k3th position in the result line.                                                  */
                   11008:       /* Tvalsel[k3]: Value of the variable at the k3th position in the result line.                                                 */
                   11009:       /* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline                   */
1.334     brouard  11010:       /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline                     */
1.332     brouard  11011:       /* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line                                        */
1.330     brouard  11012:       /* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line                                                      */
1.332     brouard  11013:       k3= resultmodel[nres][k1]; /* From position k1 in model get position k3 in result line */
                   11014:       /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   11015:       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  11016:       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  11017:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][Name]=Value; stores the value into the name of the variable. */
1.332     brouard  11018:       /* Tinvresult[nres][4]=1 */
1.334     brouard  11019:       /* Tresult[nres][k4+1]=Tvalsel[k3];/\* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) *\/ */
                   11020:       Tresult[nres][k3]=Tvalsel[k3];/* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) */
                   11021:       /* Tvresult[nres][k4+1]=(int)Tvarsel[k3];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   11022:       Tvresult[nres][k3]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
1.237     brouard  11023:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.334     brouard  11024:       precov[nres][k1]=Tvalsel[k3]; /* Value from resultline of the variable at the k1 position in the model */
1.342     brouard  11025:       /* 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  11026:       k4++;;
1.331     brouard  11027:     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Quantitative and single */
1.330     brouard  11028:       /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 */
1.332     brouard  11029:       /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline                                 */
1.330     brouard  11030:       /* Tqinvresult[nres][Name of a quantitative variable]= value of the variable in the result line                                                      */
1.332     brouard  11031:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 5 =k3q */
                   11032:       k2q=(int)Tvarsel[k3q]; /*  Name of variable at k3q th position in the resultline */
                   11033:       /* Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  11034:       /* Tqresult[nres][k4q+1]=Tvalsel[k3q]; /\* Tqresult[nres][1]=25.1 *\/ */
                   11035:       /* Tvresult[nres][k4q+1]=(int)Tvarsel[k3q];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   11036:       /* Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /\* Tvqresult[nres][1]=5 *\/ */
                   11037:       Tqresult[nres][k3q]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   11038:       Tvresult[nres][k3q]=(int)Tvarsel[k3q];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   11039:       Tvqresult[nres][k3q]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
1.237     brouard  11040:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.330     brouard  11041:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.332     brouard  11042:       precov[nres][k1]=Tvalsel[k3q];
1.342     brouard  11043:       /* 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  11044:       k4q++;;
1.331     brouard  11045:     }else if( Dummy[k1]==2 ){ /* For dummy with age product */
                   11046:       /* Tvar[k1]; */ /* Age variable */
1.332     brouard  11047:       /* Wrong we want the value of variable name Tvar[k1] */
                   11048:       
                   11049:       k3= resultmodel[nres][k1]; /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
1.331     brouard  11050:       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  11051:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][4]=1 */
1.332     brouard  11052:       precov[nres][k1]=Tvalsel[k3];
1.342     brouard  11053:       /* 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  11054:     }else if( Dummy[k1]==3 ){ /* For quant with age product */
1.332     brouard  11055:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 25.1=k3q */
1.331     brouard  11056:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  11057:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* TinvDoQresult[nres][5]=25.1 */
1.332     brouard  11058:       precov[nres][k1]=Tvalsel[k3q];
1.342     brouard  11059:       /* 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  11060:     }else if(Typevar[k1]==2 ){ /* For product quant or dummy (not with age) */
1.332     brouard  11061:       precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
1.342     brouard  11062:       /* 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  11063:     }else{
1.332     brouard  11064:       printf("Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
                   11065:       fprintf(ficlog,"Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
1.235     brouard  11066:     }
                   11067:   }
1.234     brouard  11068:   
1.334     brouard  11069:   TKresult[nres]=++k; /* Number of combinations of dummies for the nresult and the model =Tvalsel[k3]*pow(2,k4) + 1*/
1.230     brouard  11070:   return (0);
                   11071: }
1.235     brouard  11072: 
1.230     brouard  11073: int decodemodel( char model[], int lastobs)
                   11074:  /**< This routine decodes the model and returns:
1.224     brouard  11075:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   11076:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   11077:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   11078:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   11079:        * - cptcovage number of covariates with age*products =2
                   11080:        * - cptcovs number of simple covariates
1.339     brouard  11081:        * ncovcolt=ncovcol+nqv+ntv+nqtv total of covariates in the data, not in the model equation
1.224     brouard  11082:        * - 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  11083:        *     which is a new column after the 9 (ncovcol+nqv+ntv+nqtv) variables. 
1.319     brouard  11084:        * - if k is a product Vn*Vm, covar[k][i] is filled with correct values for each individual
1.224     brouard  11085:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   11086:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   11087:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   11088:        */
1.319     brouard  11089: /* 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  11090: {
1.238     brouard  11091:   int i, j, k, ks, v;
1.227     brouard  11092:   int  j1, k1, k2, k3, k4;
1.136     brouard  11093:   char modelsav[80];
1.145     brouard  11094:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  11095:   char *strpt;
1.136     brouard  11096: 
1.145     brouard  11097:   /*removespace(model);*/
1.136     brouard  11098:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  11099:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  11100:     if (strstr(model,"AGE") !=0){
1.192     brouard  11101:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   11102:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  11103:       return 1;
                   11104:     }
1.141     brouard  11105:     if (strstr(model,"v") !=0){
1.338     brouard  11106:       printf("Error. 'v' must be in upper case 'V' model=1+age+%s ",model);
                   11107:       fprintf(ficlog,"Error. 'v' must be in upper case model=1+age+%s ",model);fflush(ficlog);
1.141     brouard  11108:       return 1;
                   11109:     }
1.187     brouard  11110:     strcpy(modelsav,model); 
                   11111:     if ((strpt=strstr(model,"age*age")) !=0){
1.338     brouard  11112:       printf(" strpt=%s, model=1+age+%s\n",strpt, model);
1.187     brouard  11113:       if(strpt != model){
1.338     brouard  11114:        printf("Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  11115:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  11116:  corresponding column of parameters.\n",model);
1.338     brouard  11117:        fprintf(ficlog,"Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  11118:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  11119:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  11120:        return 1;
1.225     brouard  11121:       }
1.187     brouard  11122:       nagesqr=1;
                   11123:       if (strstr(model,"+age*age") !=0)
1.234     brouard  11124:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  11125:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  11126:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  11127:       else 
1.234     brouard  11128:        substrchaine(modelsav, model, "age*age");
1.187     brouard  11129:     }else
                   11130:       nagesqr=0;
                   11131:     if (strlen(modelsav) >1){
                   11132:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   11133:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224     brouard  11134:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  11135:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  11136:                     * cst, age and age*age 
                   11137:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   11138:       /* including age products which are counted in cptcovage.
                   11139:        * but the covariates which are products must be treated 
                   11140:        * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  11141:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   11142:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.225     brouard  11143:       
                   11144:       
1.187     brouard  11145:       /*   Design
                   11146:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   11147:        *  <          ncovcol=8                >
                   11148:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   11149:        *   k=  1    2      3       4     5       6      7        8
                   11150:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
1.345     brouard  11151:        *  covar[k,i], are for fixed covariates, value of kth covariate if not including age for individual i:
1.224     brouard  11152:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   11153:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  11154:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   11155:        *  Tage[++cptcovage]=k
1.345     brouard  11156:        *       if products, new covar are created after ncovcol + nqv (quanti fixed) with k1
1.187     brouard  11157:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   11158:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   11159:        *  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
                   11160:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   11161:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   11162:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
1.345     brouard  11163:        *  <          ncovcol=8  8 fixed covariate. Additional starts at 9 (V5*V6) and 10(V7*V8)              >
1.187     brouard  11164:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   11165:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
1.345     brouard  11166:        *     Tvard[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   11167:        * p Tvar[1]@12={2,   1,     3,      3,   9,     10,     8,       8}
1.187     brouard  11168:        * p Tprod[1]@2={                         6, 5}
                   11169:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   11170:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   11171:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1.319     brouard  11172:        *How to reorganize? Tvars(orted)
1.187     brouard  11173:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   11174:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   11175:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   11176:        * Struct []
                   11177:        */
1.225     brouard  11178:       
1.187     brouard  11179:       /* This loop fills the array Tvar from the string 'model'.*/
                   11180:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   11181:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   11182:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   11183:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   11184:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   11185:       /*       k=1 Tvar[1]=2 (from V2) */
                   11186:       /*       k=5 Tvar[5] */
                   11187:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  11188:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  11189:       /*       } */
1.198     brouard  11190:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  11191:       /*
                   11192:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  11193:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   11194:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   11195:       }
1.187     brouard  11196:       cptcovage=0;
1.319     brouard  11197:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model line */
                   11198:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' cutl from left to right
                   11199:                                         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" */
                   11200:        if (nbocc(modelsav,'+')==0)
                   11201:          strcpy(strb,modelsav); /* and analyzes it */
1.234     brouard  11202:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   11203:        /*scanf("%d",i);*/
1.319     brouard  11204:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V5*age+ V4+V3*age strb=V3*age */
                   11205:          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  11206:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   11207:            /* covar is not filled and then is empty */
                   11208:            cptcovprod--;
                   11209:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
1.319     brouard  11210:            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  11211:            Typevar[k]=1;  /* 1 for age product */
1.319     brouard  11212:            cptcovage++; /* Counts the number of covariates which include age as a product */
                   11213:            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  11214:            /*printf("stre=%s ", stre);*/
                   11215:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   11216:            cptcovprod--;
                   11217:            cutl(stre,strb,strc,'V');
                   11218:            Tvar[k]=atoi(stre);
                   11219:            Typevar[k]=1;  /* 1 for age product */
                   11220:            cptcovage++;
                   11221:            Tage[cptcovage]=k;
                   11222:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   11223:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   11224:            cptcovn++;
                   11225:            cptcovprodnoage++;k1++;
                   11226:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
1.339     brouard  11227:            Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* ncovcolt+k1; For model-covariate k tells which data-covariate to use but
1.234     brouard  11228:                                                because this model-covariate is a construction we invent a new column
                   11229:                                                which is after existing variables ncovcol+nqv+ntv+nqtv + k1
1.335     brouard  11230:                                                If already ncovcol=4 and model= V2 + V1 + V1*V4 + age*V3 + V3*V2
1.319     brouard  11231:                                                thus after V4 we invent V5 and V6 because age*V3 will be computed in 4
1.339     brouard  11232:                                                Tvar[3=V1*V4]=4+1=5 Tvar[5=V3*V2]=4 + 2= 6, Tvar[4=age*V3]=3 etc */
1.335     brouard  11233:            /* Please remark that the new variables are model dependent */
                   11234:            /* If we have 4 variable but the model uses only 3, like in
                   11235:             * model= V1 + age*V1 + V2 + V3 + age*V2 + age*V3 + V1*V2 + V1*V3
                   11236:             *  k=     1     2       3   4     5        6        7       8
                   11237:             * Tvar[k]=1     1       2   3     2        3       (5       6) (and not 4 5 because of V4 missing)
                   11238:             * Tage[kk]    [1]= 2           [2]=5      [3]=6                  kk=1 to cptcovage=3
                   11239:             * Tvar[Tage[kk]][1]=2          [2]=2      [3]=3
                   11240:             */
1.339     brouard  11241:            Typevar[k]=2;  /* 2 for product */
1.234     brouard  11242:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   11243:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
1.319     brouard  11244:            Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 */
1.234     brouard  11245:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
1.330     brouard  11246:            Tvardk[k][1] =atoi(strc); /* m 1 for V1*/
1.234     brouard  11247:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
1.330     brouard  11248:            Tvardk[k][2] =atoi(stre); /* n 4 for V4*/
1.234     brouard  11249:            k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   11250:            /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   11251:            /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
1.225     brouard  11252:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
1.234     brouard  11253:            /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
1.339     brouard  11254:            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 */
                   11255:              for (i=1; i<=lastobs;i++){/* For fixed product */
1.234     brouard  11256:              /* Computes the new covariate which is a product of
                   11257:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
1.339     brouard  11258:              covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   11259:              }
                   11260:            } /*End of FixedV */
1.234     brouard  11261:          } /* End age is not in the model */
                   11262:        } /* End if model includes a product */
1.319     brouard  11263:        else { /* not a product */
1.234     brouard  11264:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   11265:          /*  scanf("%d",i);*/
                   11266:          cutl(strd,strc,strb,'V');
                   11267:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   11268:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   11269:          Tvar[k]=atoi(strd);
                   11270:          Typevar[k]=0;  /* 0 for simple covariates */
                   11271:        }
                   11272:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  11273:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  11274:                                  scanf("%d",i);*/
1.187     brouard  11275:       } /* end of loop + on total covariates */
                   11276:     } /* end if strlen(modelsave == 0) age*age might exist */
                   11277:   } /* end if strlen(model == 0) */
1.136     brouard  11278:   
                   11279:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   11280:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  11281:   
1.136     brouard  11282:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  11283:      printf("cptcovprod=%d ", cptcovprod);
                   11284:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   11285:      scanf("%d ",i);*/
                   11286: 
                   11287: 
1.230     brouard  11288: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   11289:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  11290: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   11291:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   11292:    k =           1    2   3     4       5       6      7      8        9
                   11293:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
1.319     brouard  11294:    Typevar[k]=   0    0   0     2       1       0      2      1        0
1.227     brouard  11295:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   11296:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   11297:          Tmodelind[combination of covar]=k;
1.225     brouard  11298: */  
                   11299: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  11300:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  11301:   /* 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  11302:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.318     brouard  11303:   printf("Model=1+age+%s\n\
1.227     brouard  11304: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   11305: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   11306: 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  11307:   fprintf(ficlog,"Model=1+age+%s\n\
1.227     brouard  11308: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   11309: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   11310: 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  11311:   for(k=-1;k<=NCOVMAX; k++){ Fixed[k]=0; Dummy[k]=0;}
                   11312:   for(k=1;k<=NCOVMAX; k++){TvarFind[k]=0; TvarVind[k]=0;}
1.343     brouard  11313:   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  11314:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  11315:       Fixed[k]= 0;
                   11316:       Dummy[k]= 0;
1.225     brouard  11317:       ncoveff++;
1.232     brouard  11318:       ncovf++;
1.234     brouard  11319:       nsd++;
                   11320:       modell[k].maintype= FTYPE;
                   11321:       TvarsD[nsd]=Tvar[k];
                   11322:       TvarsDind[nsd]=k;
1.330     brouard  11323:       TnsdVar[Tvar[k]]=nsd;
1.234     brouard  11324:       TvarF[ncovf]=Tvar[k];
                   11325:       TvarFind[ncovf]=k;
                   11326:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   11327:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.339     brouard  11328:     /* }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /\* Product of fixed dummy (<=ncovcol) covariates For a fixed product k is higher than ncovcol *\/ */
                   11329:     }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  11330:       Fixed[k]= 0;
                   11331:       Dummy[k]= 0;
                   11332:       ncoveff++;
                   11333:       ncovf++;
                   11334:       modell[k].maintype= FTYPE;
                   11335:       TvarF[ncovf]=Tvar[k];
1.330     brouard  11336:       /* TnsdVar[Tvar[k]]=nsd; */ /* To be done */
1.234     brouard  11337:       TvarFind[ncovf]=k;
1.230     brouard  11338:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  11339:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.240     brouard  11340:     }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  11341:       Fixed[k]= 0;
                   11342:       Dummy[k]= 1;
1.230     brouard  11343:       nqfveff++;
1.234     brouard  11344:       modell[k].maintype= FTYPE;
                   11345:       modell[k].subtype= FQ;
                   11346:       nsq++;
1.334     brouard  11347:       TvarsQ[nsq]=Tvar[k]; /* Gives the variable name (extended to products) of first nsq simple quantitative covariates (fixed or time vary see below */
                   11348:       TvarsQind[nsq]=k;    /* Gives the position in the model equation of the first nsq simple quantitative covariates (fixed or time vary) */
1.232     brouard  11349:       ncovf++;
1.234     brouard  11350:       TvarF[ncovf]=Tvar[k];
                   11351:       TvarFind[ncovf]=k;
1.231     brouard  11352:       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  11353:       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  11354:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.339     brouard  11355:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11356:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11357:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11358:       ncovvt++;
                   11359:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11360:       TvarVVind[ncovvt]=k;    /*  TvarVVind[1]=2 (second position in the model equation  */
                   11361: 
1.227     brouard  11362:       Fixed[k]= 1;
                   11363:       Dummy[k]= 0;
1.225     brouard  11364:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  11365:       modell[k].maintype= VTYPE;
                   11366:       modell[k].subtype= VD;
                   11367:       nsd++;
                   11368:       TvarsD[nsd]=Tvar[k];
                   11369:       TvarsDind[nsd]=k;
1.330     brouard  11370:       TnsdVar[Tvar[k]]=nsd; /* To be verified */
1.234     brouard  11371:       ncovv++; /* Only simple time varying variables */
                   11372:       TvarV[ncovv]=Tvar[k];
1.242     brouard  11373:       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  11374:       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 */
                   11375:       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  11376:       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);
                   11377:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  11378:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.339     brouard  11379:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11380:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11381:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11382:       ncovvt++;
                   11383:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11384:       TvarVVind[ncovvt]=k;  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11385:       
1.234     brouard  11386:       Fixed[k]= 1;
                   11387:       Dummy[k]= 1;
                   11388:       nqtveff++;
                   11389:       modell[k].maintype= VTYPE;
                   11390:       modell[k].subtype= VQ;
                   11391:       ncovv++; /* Only simple time varying variables */
                   11392:       nsq++;
1.334     brouard  11393:       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) */
                   11394:       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  11395:       TvarV[ncovv]=Tvar[k];
1.242     brouard  11396:       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  11397:       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 */
                   11398:       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  11399:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   11400:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
1.342     brouard  11401:       /* 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); */
                   11402:       /* printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv); */
1.227     brouard  11403:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  11404:       ncova++;
                   11405:       TvarA[ncova]=Tvar[k];
                   11406:       TvarAind[ncova]=k;
1.231     brouard  11407:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  11408:        Fixed[k]= 2;
                   11409:        Dummy[k]= 2;
                   11410:        modell[k].maintype= ATYPE;
                   11411:        modell[k].subtype= APFD;
                   11412:        /* ncoveff++; */
1.227     brouard  11413:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  11414:        Fixed[k]= 2;
                   11415:        Dummy[k]= 3;
                   11416:        modell[k].maintype= ATYPE;
                   11417:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   11418:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  11419:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  11420:        Fixed[k]= 3;
                   11421:        Dummy[k]= 2;
                   11422:        modell[k].maintype= ATYPE;
                   11423:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   11424:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  11425:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  11426:        Fixed[k]= 3;
                   11427:        Dummy[k]= 3;
                   11428:        modell[k].maintype= ATYPE;
                   11429:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   11430:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  11431:       }
1.339     brouard  11432:     }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  */
                   11433:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11434:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11435:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11436:       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 */
                   11437:       ncovvt++;
                   11438:       TvarVV[ncovvt]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
                   11439:       TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   11440:       ncovvt++;
                   11441:       TvarVV[ncovvt]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
                   11442:       TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   11443: 
                   11444: 
                   11445:       if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   11446:        if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
1.240     brouard  11447:          Fixed[k]= 1;
                   11448:          Dummy[k]= 0;
                   11449:          modell[k].maintype= FTYPE;
                   11450:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
                   11451:          ncovf++; /* Fixed variables without age */
                   11452:          TvarF[ncovf]=Tvar[k];
                   11453:          TvarFind[ncovf]=k;
1.339     brouard  11454:        }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
                   11455:          Fixed[k]= 0;  /* Fixed product */
1.240     brouard  11456:          Dummy[k]= 1;
                   11457:          modell[k].maintype= FTYPE;
                   11458:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
                   11459:          ncovf++; /* Varying variables without age */
                   11460:          TvarF[ncovf]=Tvar[k];
                   11461:          TvarFind[ncovf]=k;
1.339     brouard  11462:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
1.240     brouard  11463:          Fixed[k]= 1;
                   11464:          Dummy[k]= 0;
                   11465:          modell[k].maintype= VTYPE;
                   11466:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
                   11467:          ncovv++; /* Varying variables without age */
1.339     brouard  11468:          TvarV[ncovv]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
                   11469:          TvarVind[ncovv]=k;/* TvarVind[1]=5 */ 
                   11470:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
1.240     brouard  11471:          Fixed[k]= 1;
                   11472:          Dummy[k]= 1;
                   11473:          modell[k].maintype= VTYPE;
                   11474:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
                   11475:          ncovv++; /* Varying variables without age */
                   11476:          TvarV[ncovv]=Tvar[k];
                   11477:          TvarVind[ncovv]=k;
                   11478:        }
1.339     brouard  11479:       }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   11480:        if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
                   11481:          Fixed[k]= 0;  /*  Fixed product */
1.240     brouard  11482:          Dummy[k]= 1;
                   11483:          modell[k].maintype= FTYPE;
                   11484:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
                   11485:          ncovf++; /* Fixed variables without age */
                   11486:          TvarF[ncovf]=Tvar[k];
                   11487:          TvarFind[ncovf]=k;
1.339     brouard  11488:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
1.240     brouard  11489:          Fixed[k]= 1;
                   11490:          Dummy[k]= 1;
                   11491:          modell[k].maintype= VTYPE;
                   11492:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
                   11493:          ncovv++; /* Varying variables without age */
                   11494:          TvarV[ncovv]=Tvar[k];
                   11495:          TvarVind[ncovv]=k;
1.339     brouard  11496:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
1.240     brouard  11497:          Fixed[k]= 1;
                   11498:          Dummy[k]= 1;
                   11499:          modell[k].maintype= VTYPE;
                   11500:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
                   11501:          ncovv++; /* Varying variables without age */
                   11502:          TvarV[ncovv]=Tvar[k];
                   11503:          TvarVind[ncovv]=k;
                   11504:          ncovv++; /* Varying variables without age */
                   11505:          TvarV[ncovv]=Tvar[k];
                   11506:          TvarVind[ncovv]=k;
                   11507:        }
1.339     brouard  11508:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
1.240     brouard  11509:        if(Tvard[k1][2] <=ncovcol){
                   11510:          Fixed[k]= 1;
                   11511:          Dummy[k]= 1;
                   11512:          modell[k].maintype= VTYPE;
                   11513:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
                   11514:          ncovv++; /* Varying variables without age */
                   11515:          TvarV[ncovv]=Tvar[k];
                   11516:          TvarVind[ncovv]=k;
                   11517:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   11518:          Fixed[k]= 1;
                   11519:          Dummy[k]= 1;
                   11520:          modell[k].maintype= VTYPE;
                   11521:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
                   11522:          ncovv++; /* Varying variables without age */
                   11523:          TvarV[ncovv]=Tvar[k];
                   11524:          TvarVind[ncovv]=k;
                   11525:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   11526:          Fixed[k]= 1;
                   11527:          Dummy[k]= 0;
                   11528:          modell[k].maintype= VTYPE;
                   11529:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
                   11530:          ncovv++; /* Varying variables without age */
                   11531:          TvarV[ncovv]=Tvar[k];
                   11532:          TvarVind[ncovv]=k;
                   11533:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   11534:          Fixed[k]= 1;
                   11535:          Dummy[k]= 1;
                   11536:          modell[k].maintype= VTYPE;
                   11537:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
                   11538:          ncovv++; /* Varying variables without age */
                   11539:          TvarV[ncovv]=Tvar[k];
                   11540:          TvarVind[ncovv]=k;
                   11541:        }
1.339     brouard  11542:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
1.240     brouard  11543:        if(Tvard[k1][2] <=ncovcol){
                   11544:          Fixed[k]= 1;
                   11545:          Dummy[k]= 1;
                   11546:          modell[k].maintype= VTYPE;
                   11547:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
                   11548:          ncovv++; /* Varying variables without age */
                   11549:          TvarV[ncovv]=Tvar[k];
                   11550:          TvarVind[ncovv]=k;
                   11551:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   11552:          Fixed[k]= 1;
                   11553:          Dummy[k]= 1;
                   11554:          modell[k].maintype= VTYPE;
                   11555:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
                   11556:          ncovv++; /* Varying variables without age */
                   11557:          TvarV[ncovv]=Tvar[k];
                   11558:          TvarVind[ncovv]=k;
                   11559:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   11560:          Fixed[k]= 1;
                   11561:          Dummy[k]= 1;
                   11562:          modell[k].maintype= VTYPE;
                   11563:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
                   11564:          ncovv++; /* Varying variables without age */
                   11565:          TvarV[ncovv]=Tvar[k];
                   11566:          TvarVind[ncovv]=k;
                   11567:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   11568:          Fixed[k]= 1;
                   11569:          Dummy[k]= 1;
                   11570:          modell[k].maintype= VTYPE;
                   11571:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
                   11572:          ncovv++; /* Varying variables without age */
                   11573:          TvarV[ncovv]=Tvar[k];
                   11574:          TvarVind[ncovv]=k;
                   11575:        }
1.227     brouard  11576:       }else{
1.240     brouard  11577:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   11578:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   11579:       } /*end k1*/
1.225     brouard  11580:     }else{
1.226     brouard  11581:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   11582:       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  11583:     }
1.342     brouard  11584:     /* 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]); */
                   11585:     /* printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype); */
1.227     brouard  11586:     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]);
                   11587:   }
                   11588:   /* Searching for doublons in the model */
                   11589:   for(k1=1; k1<= cptcovt;k1++){
                   11590:     for(k2=1; k2 <k1;k2++){
1.285     brouard  11591:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   11592:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  11593:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   11594:          if(Tvar[k1]==Tvar[k2]){
1.338     brouard  11595:            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]);
                   11596:            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  11597:            return(1);
                   11598:          }
                   11599:        }else if (Typevar[k1] ==2){
                   11600:          k3=Tposprod[k1];
                   11601:          k4=Tposprod[k2];
                   11602:          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  11603:            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]]);
                   11604:            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  11605:            return(1);
                   11606:          }
                   11607:        }
1.227     brouard  11608:       }
                   11609:     }
1.225     brouard  11610:   }
                   11611:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   11612:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  11613:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   11614:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.137     brouard  11615:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  11616:   /*endread:*/
1.225     brouard  11617:   printf("Exiting decodemodel: ");
                   11618:   return (1);
1.136     brouard  11619: }
                   11620: 
1.169     brouard  11621: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  11622: {/* Check ages at death */
1.136     brouard  11623:   int i, m;
1.218     brouard  11624:   int firstone=0;
                   11625:   
1.136     brouard  11626:   for (i=1; i<=imx; i++) {
                   11627:     for(m=2; (m<= maxwav); m++) {
                   11628:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   11629:        anint[m][i]=9999;
1.216     brouard  11630:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   11631:          s[m][i]=-1;
1.136     brouard  11632:       }
                   11633:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  11634:        *nberr = *nberr + 1;
1.218     brouard  11635:        if(firstone == 0){
                   11636:          firstone=1;
1.260     brouard  11637:        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  11638:        }
1.262     brouard  11639:        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  11640:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  11641:       }
                   11642:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  11643:        (*nberr)++;
1.259     brouard  11644:        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  11645:        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  11646:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  11647:       }
                   11648:     }
                   11649:   }
                   11650: 
                   11651:   for (i=1; i<=imx; i++)  {
                   11652:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   11653:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  11654:       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  11655:        if (s[m][i] >= nlstate+1) {
1.169     brouard  11656:          if(agedc[i]>0){
                   11657:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  11658:              agev[m][i]=agedc[i];
1.214     brouard  11659:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  11660:            }else {
1.136     brouard  11661:              if ((int)andc[i]!=9999){
                   11662:                nbwarn++;
                   11663:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   11664:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   11665:                agev[m][i]=-1;
                   11666:              }
                   11667:            }
1.169     brouard  11668:          } /* agedc > 0 */
1.214     brouard  11669:        } /* end if */
1.136     brouard  11670:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   11671:                                 years but with the precision of a month */
                   11672:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   11673:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   11674:            agev[m][i]=1;
                   11675:          else if(agev[m][i] < *agemin){ 
                   11676:            *agemin=agev[m][i];
                   11677:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   11678:          }
                   11679:          else if(agev[m][i] >*agemax){
                   11680:            *agemax=agev[m][i];
1.156     brouard  11681:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  11682:          }
                   11683:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   11684:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  11685:        } /* en if 9*/
1.136     brouard  11686:        else { /* =9 */
1.214     brouard  11687:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  11688:          agev[m][i]=1;
                   11689:          s[m][i]=-1;
                   11690:        }
                   11691:       }
1.214     brouard  11692:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  11693:        agev[m][i]=1;
1.214     brouard  11694:       else{
                   11695:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   11696:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   11697:        agev[m][i]=0;
                   11698:       }
                   11699:     } /* End for lastpass */
                   11700:   }
1.136     brouard  11701:     
                   11702:   for (i=1; i<=imx; i++)  {
                   11703:     for(m=firstpass; (m<=lastpass); m++){
                   11704:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  11705:        (*nberr)++;
1.136     brouard  11706:        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);     
                   11707:        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);     
                   11708:        return 1;
                   11709:       }
                   11710:     }
                   11711:   }
                   11712: 
                   11713:   /*for (i=1; i<=imx; i++){
                   11714:   for (m=firstpass; (m<lastpass); m++){
                   11715:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   11716: }
                   11717: 
                   11718: }*/
                   11719: 
                   11720: 
1.139     brouard  11721:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   11722:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  11723: 
                   11724:   return (0);
1.164     brouard  11725:  /* endread:*/
1.136     brouard  11726:     printf("Exiting calandcheckages: ");
                   11727:     return (1);
                   11728: }
                   11729: 
1.172     brouard  11730: #if defined(_MSC_VER)
                   11731: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   11732: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   11733: //#include "stdafx.h"
                   11734: //#include <stdio.h>
                   11735: //#include <tchar.h>
                   11736: //#include <windows.h>
                   11737: //#include <iostream>
                   11738: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   11739: 
                   11740: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   11741: 
                   11742: BOOL IsWow64()
                   11743: {
                   11744:        BOOL bIsWow64 = FALSE;
                   11745: 
                   11746:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   11747:        //  (HANDLE, PBOOL);
                   11748: 
                   11749:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   11750: 
                   11751:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   11752:        const char funcName[] = "IsWow64Process";
                   11753:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   11754:                GetProcAddress(module, funcName);
                   11755: 
                   11756:        if (NULL != fnIsWow64Process)
                   11757:        {
                   11758:                if (!fnIsWow64Process(GetCurrentProcess(),
                   11759:                        &bIsWow64))
                   11760:                        //throw std::exception("Unknown error");
                   11761:                        printf("Unknown error\n");
                   11762:        }
                   11763:        return bIsWow64 != FALSE;
                   11764: }
                   11765: #endif
1.177     brouard  11766: 
1.191     brouard  11767: void syscompilerinfo(int logged)
1.292     brouard  11768: {
                   11769: #include <stdint.h>
                   11770: 
                   11771:   /* #include "syscompilerinfo.h"*/
1.185     brouard  11772:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   11773:    /* /GS /W3 /Gy
                   11774:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   11775:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   11776:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  11777:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   11778:    */ 
                   11779:    /* 64 bits */
1.185     brouard  11780:    /*
                   11781:      /GS /W3 /Gy
                   11782:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   11783:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   11784:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   11785:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   11786:    /* Optimization are useless and O3 is slower than O2 */
                   11787:    /*
                   11788:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   11789:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   11790:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   11791:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   11792:    */
1.186     brouard  11793:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  11794:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   11795:       /PDB:"visual studio
                   11796:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   11797:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   11798:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   11799:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   11800:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   11801:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   11802:       uiAccess='false'"
                   11803:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   11804:       /NOLOGO /TLBID:1
                   11805:    */
1.292     brouard  11806: 
                   11807: 
1.177     brouard  11808: #if defined __INTEL_COMPILER
1.178     brouard  11809: #if defined(__GNUC__)
                   11810:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   11811: #endif
1.177     brouard  11812: #elif defined(__GNUC__) 
1.179     brouard  11813: #ifndef  __APPLE__
1.174     brouard  11814: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  11815: #endif
1.177     brouard  11816:    struct utsname sysInfo;
1.178     brouard  11817:    int cross = CROSS;
                   11818:    if (cross){
                   11819:           printf("Cross-");
1.191     brouard  11820:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  11821:    }
1.174     brouard  11822: #endif
                   11823: 
1.191     brouard  11824:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  11825: #if defined(__clang__)
1.191     brouard  11826:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  11827: #endif
                   11828: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  11829:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  11830: #endif
                   11831: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  11832:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  11833: #endif
                   11834: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  11835:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  11836: #endif
                   11837: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  11838:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  11839: #endif
                   11840: #if defined(_MSC_VER)
1.191     brouard  11841:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  11842: #endif
                   11843: #if defined(__PGI)
1.191     brouard  11844:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  11845: #endif
                   11846: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  11847:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  11848: #endif
1.191     brouard  11849:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  11850:    
1.167     brouard  11851: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   11852: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   11853:     // Windows (x64 and x86)
1.191     brouard  11854:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  11855: #elif __unix__ // all unices, not all compilers
                   11856:     // Unix
1.191     brouard  11857:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  11858: #elif __linux__
                   11859:     // linux
1.191     brouard  11860:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  11861: #elif __APPLE__
1.174     brouard  11862:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  11863:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  11864: #endif
                   11865: 
                   11866: /*  __MINGW32__          */
                   11867: /*  __CYGWIN__  */
                   11868: /* __MINGW64__  */
                   11869: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   11870: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   11871: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   11872: /* _WIN64  // Defined for applications for Win64. */
                   11873: /* _M_X64 // Defined for compilations that target x64 processors. */
                   11874: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  11875: 
1.167     brouard  11876: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  11877:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  11878: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  11879:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  11880: #else
1.191     brouard  11881:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  11882: #endif
                   11883: 
1.169     brouard  11884: #if defined(__GNUC__)
                   11885: # if defined(__GNUC_PATCHLEVEL__)
                   11886: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   11887:                             + __GNUC_MINOR__ * 100 \
                   11888:                             + __GNUC_PATCHLEVEL__)
                   11889: # else
                   11890: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   11891:                             + __GNUC_MINOR__ * 100)
                   11892: # endif
1.174     brouard  11893:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  11894:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  11895: 
                   11896:    if (uname(&sysInfo) != -1) {
                   11897:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  11898:         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  11899:    }
                   11900:    else
                   11901:       perror("uname() error");
1.179     brouard  11902:    //#ifndef __INTEL_COMPILER 
                   11903: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  11904:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  11905:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  11906: #endif
1.169     brouard  11907: #endif
1.172     brouard  11908: 
1.286     brouard  11909:    //   void main ()
1.172     brouard  11910:    //   {
1.169     brouard  11911: #if defined(_MSC_VER)
1.174     brouard  11912:    if (IsWow64()){
1.191     brouard  11913:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   11914:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  11915:    }
                   11916:    else{
1.191     brouard  11917:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   11918:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  11919:    }
1.172     brouard  11920:    //     printf("\nPress Enter to continue...");
                   11921:    //     getchar();
                   11922:    //   }
                   11923: 
1.169     brouard  11924: #endif
                   11925:    
1.167     brouard  11926: 
1.219     brouard  11927: }
1.136     brouard  11928: 
1.219     brouard  11929: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  11930:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.332     brouard  11931:   /* Computes the prevalence limit for each combination of the dummy covariates */
1.235     brouard  11932:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  11933:   /* double ftolpl = 1.e-10; */
1.180     brouard  11934:   double age, agebase, agelim;
1.203     brouard  11935:   double tot;
1.180     brouard  11936: 
1.202     brouard  11937:   strcpy(filerespl,"PL_");
                   11938:   strcat(filerespl,fileresu);
                   11939:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  11940:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   11941:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  11942:   }
1.288     brouard  11943:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   11944:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  11945:   pstamp(ficrespl);
1.288     brouard  11946:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  11947:   fprintf(ficrespl,"#Age ");
                   11948:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   11949:   fprintf(ficrespl,"\n");
1.180     brouard  11950:   
1.219     brouard  11951:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  11952: 
1.219     brouard  11953:   agebase=ageminpar;
                   11954:   agelim=agemaxpar;
1.180     brouard  11955: 
1.227     brouard  11956:   /* i1=pow(2,ncoveff); */
1.234     brouard  11957:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  11958:   if (cptcovn < 1){i1=1;}
1.180     brouard  11959: 
1.337     brouard  11960:   /* for(k=1; k<=i1;k++){ /\* For each combination k of dummy covariates in the model *\/ */
1.238     brouard  11961:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  11962:       k=TKresult[nres];
1.338     brouard  11963:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  11964:       /* if(i1 != 1 && TKresult[nres]!= k) /\* We found the combination k corresponding to the resultline value of dummies *\/ */
                   11965:       /*       continue; */
1.235     brouard  11966: 
1.238     brouard  11967:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11968:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   11969:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   11970:       /* k=k+1; */
                   11971:       /* to clean */
1.332     brouard  11972:       /*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*/
1.238     brouard  11973:       fprintf(ficrespl,"#******");
                   11974:       printf("#******");
                   11975:       fprintf(ficlog,"#******");
1.337     brouard  11976:       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  11977:        /* fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Here problem for varying dummy*\/ */
1.337     brouard  11978:        /* printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11979:        /* fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11980:        fprintf(ficrespl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11981:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11982:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11983:       }
                   11984:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   11985:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11986:       /*       fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11987:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11988:       /* } */
1.238     brouard  11989:       fprintf(ficrespl,"******\n");
                   11990:       printf("******\n");
                   11991:       fprintf(ficlog,"******\n");
                   11992:       if(invalidvarcomb[k]){
                   11993:        printf("\nCombination (%d) ignored because no case \n",k); 
                   11994:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   11995:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   11996:        continue;
                   11997:       }
1.219     brouard  11998: 
1.238     brouard  11999:       fprintf(ficrespl,"#Age ");
1.337     brouard  12000:       /* for(j=1;j<=cptcoveff;j++) { */
                   12001:       /*       fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12002:       /* } */
                   12003:       for(j=1;j<=cptcovs;j++) { /* New the quanti variable is added */
                   12004:        fprintf(ficrespl,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12005:       }
                   12006:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   12007:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  12008:     
1.238     brouard  12009:       for (age=agebase; age<=agelim; age++){
                   12010:        /* for (age=agebase; age<=agebase; age++){ */
1.337     brouard  12011:        /**< Computes the prevalence limit in each live state at age x and for covariate combination (k and) nres */
                   12012:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres); /* Nicely done */
1.238     brouard  12013:        fprintf(ficrespl,"%.0f ",age );
1.337     brouard  12014:        /* for(j=1;j<=cptcoveff;j++) */
                   12015:        /*   fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12016:        for(j=1;j<=cptcovs;j++)
                   12017:          fprintf(ficrespl,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12018:        tot=0.;
                   12019:        for(i=1; i<=nlstate;i++){
                   12020:          tot +=  prlim[i][i];
                   12021:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   12022:        }
                   12023:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   12024:       } /* Age */
                   12025:       /* was end of cptcod */
1.337     brouard  12026:     } /* nres */
                   12027:   /* } /\* for each combination *\/ */
1.219     brouard  12028:   return 0;
1.180     brouard  12029: }
                   12030: 
1.218     brouard  12031: 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  12032:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  12033:        
                   12034:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   12035:    * at any age between ageminpar and agemaxpar
                   12036:         */
1.235     brouard  12037:   int i, j, k, i1, nres=0 ;
1.217     brouard  12038:   /* double ftolpl = 1.e-10; */
                   12039:   double age, agebase, agelim;
                   12040:   double tot;
1.218     brouard  12041:   /* double ***mobaverage; */
                   12042:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  12043: 
                   12044:   strcpy(fileresplb,"PLB_");
                   12045:   strcat(fileresplb,fileresu);
                   12046:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  12047:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   12048:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  12049:   }
1.288     brouard  12050:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   12051:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  12052:   pstamp(ficresplb);
1.288     brouard  12053:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  12054:   fprintf(ficresplb,"#Age ");
                   12055:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   12056:   fprintf(ficresplb,"\n");
                   12057:   
1.218     brouard  12058:   
                   12059:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   12060:   
                   12061:   agebase=ageminpar;
                   12062:   agelim=agemaxpar;
                   12063:   
                   12064:   
1.227     brouard  12065:   i1=pow(2,cptcoveff);
1.218     brouard  12066:   if (cptcovn < 1){i1=1;}
1.227     brouard  12067:   
1.238     brouard  12068:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.338     brouard  12069:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   12070:       k=TKresult[nres];
                   12071:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   12072:      /* if(i1 != 1 && TKresult[nres]!= k) */
                   12073:      /*        continue; */
                   12074:      /* /\*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*\/ */
1.238     brouard  12075:       fprintf(ficresplb,"#******");
                   12076:       printf("#******");
                   12077:       fprintf(ficlog,"#******");
1.338     brouard  12078:       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) */
                   12079:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12080:        fprintf(ficresplb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12081:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12082:       }
1.338     brouard  12083:       /* for(j=1;j<=cptcoveff ;j++) {/\* all covariates *\/ */
                   12084:       /*       fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12085:       /*       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12086:       /*       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12087:       /* } */
                   12088:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   12089:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12090:       /*       fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12091:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12092:       /* } */
1.238     brouard  12093:       fprintf(ficresplb,"******\n");
                   12094:       printf("******\n");
                   12095:       fprintf(ficlog,"******\n");
                   12096:       if(invalidvarcomb[k]){
                   12097:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   12098:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   12099:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   12100:        continue;
                   12101:       }
1.218     brouard  12102:     
1.238     brouard  12103:       fprintf(ficresplb,"#Age ");
1.338     brouard  12104:       for(j=1;j<=cptcovs;j++) {
                   12105:        fprintf(ficresplb,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12106:       }
                   12107:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   12108:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  12109:     
                   12110:     
1.238     brouard  12111:       for (age=agebase; age<=agelim; age++){
                   12112:        /* for (age=agebase; age<=agebase; age++){ */
                   12113:        if(mobilavproj > 0){
                   12114:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   12115:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  12116:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  12117:        }else if (mobilavproj == 0){
                   12118:          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);
                   12119:          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);
                   12120:          exit(1);
                   12121:        }else{
                   12122:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  12123:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  12124:          /* printf("TOTOT\n"); */
                   12125:           /* exit(1); */
1.238     brouard  12126:        }
                   12127:        fprintf(ficresplb,"%.0f ",age );
1.338     brouard  12128:        for(j=1;j<=cptcovs;j++)
                   12129:          fprintf(ficresplb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12130:        tot=0.;
                   12131:        for(i=1; i<=nlstate;i++){
                   12132:          tot +=  bprlim[i][i];
                   12133:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   12134:        }
                   12135:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   12136:       } /* Age */
                   12137:       /* was end of cptcod */
1.255     brouard  12138:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.338     brouard  12139:     /* } /\* end of any combination *\/ */
1.238     brouard  12140:   } /* end of nres */  
1.218     brouard  12141:   /* hBijx(p, bage, fage); */
                   12142:   /* fclose(ficrespijb); */
                   12143:   
                   12144:   return 0;
1.217     brouard  12145: }
1.218     brouard  12146:  
1.180     brouard  12147: int hPijx(double *p, int bage, int fage){
                   12148:     /*------------- h Pij x at various ages ------------*/
1.336     brouard  12149:   /* to be optimized with precov */
1.180     brouard  12150:   int stepsize;
                   12151:   int agelim;
                   12152:   int hstepm;
                   12153:   int nhstepm;
1.235     brouard  12154:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  12155: 
                   12156:   double agedeb;
                   12157:   double ***p3mat;
                   12158: 
1.337     brouard  12159:   strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
                   12160:   if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   12161:     printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   12162:     fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   12163:   }
                   12164:   printf("Computing pij: result on file '%s' \n", filerespij);
                   12165:   fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   12166:   
                   12167:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   12168:   /*if (stepm<=24) stepsize=2;*/
                   12169:   
                   12170:   agelim=AGESUP;
                   12171:   hstepm=stepsize*YEARM; /* Every year of age */
                   12172:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   12173:   
                   12174:   /* hstepm=1;   aff par mois*/
                   12175:   pstamp(ficrespij);
                   12176:   fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   12177:   i1= pow(2,cptcoveff);
                   12178:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12179:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   12180:   /*   k=k+1;  */
                   12181:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   12182:     k=TKresult[nres];
1.338     brouard  12183:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12184:     /* for(k=1; k<=i1;k++){ */
                   12185:     /* if(i1 != 1 && TKresult[nres]!= k) */
                   12186:     /*         continue; */
                   12187:     fprintf(ficrespij,"\n#****** ");
                   12188:     for(j=1;j<=cptcovs;j++){
                   12189:       fprintf(ficrespij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12190:       /* fprintf(ficrespij,"@wV%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12191:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   12192:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12193:       /*       fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12194:     }
                   12195:     fprintf(ficrespij,"******\n");
                   12196:     
                   12197:     for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   12198:       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   12199:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   12200:       
                   12201:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   12202:       
                   12203:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12204:       oldm=oldms;savm=savms;
                   12205:       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
                   12206:       fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   12207:       for(i=1; i<=nlstate;i++)
                   12208:        for(j=1; j<=nlstate+ndeath;j++)
                   12209:          fprintf(ficrespij," %1d-%1d",i,j);
                   12210:       fprintf(ficrespij,"\n");
                   12211:       for (h=0; h<=nhstepm; h++){
                   12212:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   12213:        fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.183     brouard  12214:        for(i=1; i<=nlstate;i++)
                   12215:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  12216:            fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.183     brouard  12217:        fprintf(ficrespij,"\n");
                   12218:       }
1.337     brouard  12219:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12220:       fprintf(ficrespij,"\n");
1.180     brouard  12221:     }
1.337     brouard  12222:   }
                   12223:   /*}*/
                   12224:   return 0;
1.180     brouard  12225: }
1.218     brouard  12226:  
                   12227:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  12228:     /*------------- h Bij x at various ages ------------*/
1.336     brouard  12229:     /* To be optimized with precov */
1.217     brouard  12230:   int stepsize;
1.218     brouard  12231:   /* int agelim; */
                   12232:        int ageminl;
1.217     brouard  12233:   int hstepm;
                   12234:   int nhstepm;
1.238     brouard  12235:   int h, i, i1, j, k, nres;
1.218     brouard  12236:        
1.217     brouard  12237:   double agedeb;
                   12238:   double ***p3mat;
1.218     brouard  12239:        
                   12240:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   12241:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   12242:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   12243:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   12244:   }
                   12245:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   12246:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   12247:   
                   12248:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   12249:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  12250:   
1.218     brouard  12251:   /* agelim=AGESUP; */
1.289     brouard  12252:   ageminl=AGEINF; /* was 30 */
1.218     brouard  12253:   hstepm=stepsize*YEARM; /* Every year of age */
                   12254:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   12255:   
                   12256:   /* hstepm=1;   aff par mois*/
                   12257:   pstamp(ficrespijb);
1.255     brouard  12258:   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  12259:   i1= pow(2,cptcoveff);
1.218     brouard  12260:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12261:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   12262:   /*   k=k+1;  */
1.238     brouard  12263:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  12264:     k=TKresult[nres];
1.338     brouard  12265:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12266:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   12267:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   12268:     /*         continue; */
                   12269:     fprintf(ficrespijb,"\n#****** ");
                   12270:     for(j=1;j<=cptcovs;j++){
1.338     brouard  12271:       fprintf(ficrespijb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.337     brouard  12272:       /* for(j=1;j<=cptcoveff;j++) */
                   12273:       /*       fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12274:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   12275:       /*       fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12276:     }
                   12277:     fprintf(ficrespijb,"******\n");
                   12278:     if(invalidvarcomb[k]){  /* Is it necessary here? */
                   12279:       fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   12280:       continue;
                   12281:     }
                   12282:     
                   12283:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   12284:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   12285:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   12286:       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 */
                   12287:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
                   12288:       
                   12289:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   12290:       
                   12291:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   12292:       /* and memory limitations if stepm is small */
                   12293:       
                   12294:       /* oldm=oldms;savm=savms; */
                   12295:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   12296:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);/* Bug valgrind */
                   12297:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
                   12298:       fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
                   12299:       for(i=1; i<=nlstate;i++)
                   12300:        for(j=1; j<=nlstate+ndeath;j++)
                   12301:          fprintf(ficrespijb," %1d-%1d",i,j);
                   12302:       fprintf(ficrespijb,"\n");
                   12303:       for (h=0; h<=nhstepm; h++){
                   12304:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   12305:        fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   12306:        /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
1.217     brouard  12307:        for(i=1; i<=nlstate;i++)
                   12308:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  12309:            fprintf(ficrespijb," %.5f", p3mat[i][j][h]);/* Bug valgrind */
1.217     brouard  12310:        fprintf(ficrespijb,"\n");
1.337     brouard  12311:       }
                   12312:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12313:       fprintf(ficrespijb,"\n");
                   12314:     } /* end age deb */
                   12315:     /* } /\* end combination *\/ */
1.238     brouard  12316:   } /* end nres */
1.218     brouard  12317:   return 0;
                   12318:  } /*  hBijx */
1.217     brouard  12319: 
1.180     brouard  12320: 
1.136     brouard  12321: /***********************************************/
                   12322: /**************** Main Program *****************/
                   12323: /***********************************************/
                   12324: 
                   12325: int main(int argc, char *argv[])
                   12326: {
                   12327: #ifdef GSL
                   12328:   const gsl_multimin_fminimizer_type *T;
                   12329:   size_t iteri = 0, it;
                   12330:   int rval = GSL_CONTINUE;
                   12331:   int status = GSL_SUCCESS;
                   12332:   double ssval;
                   12333: #endif
                   12334:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  12335:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   12336:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  12337:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  12338:   int jj, ll, li, lj, lk;
1.136     brouard  12339:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  12340:   int num_filled;
1.136     brouard  12341:   int itimes;
                   12342:   int NDIM=2;
                   12343:   int vpopbased=0;
1.235     brouard  12344:   int nres=0;
1.258     brouard  12345:   int endishere=0;
1.277     brouard  12346:   int noffset=0;
1.274     brouard  12347:   int ncurrv=0; /* Temporary variable */
                   12348:   
1.164     brouard  12349:   char ca[32], cb[32];
1.136     brouard  12350:   /*  FILE *fichtm; *//* Html File */
                   12351:   /* FILE *ficgp;*/ /*Gnuplot File */
                   12352:   struct stat info;
1.191     brouard  12353:   double agedeb=0.;
1.194     brouard  12354: 
                   12355:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  12356:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  12357: 
1.165     brouard  12358:   double fret;
1.191     brouard  12359:   double dum=0.; /* Dummy variable */
1.136     brouard  12360:   double ***p3mat;
1.218     brouard  12361:   /* double ***mobaverage; */
1.319     brouard  12362:   double wald;
1.164     brouard  12363: 
                   12364:   char line[MAXLINE];
1.197     brouard  12365:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   12366: 
1.234     brouard  12367:   char  modeltemp[MAXLINE];
1.332     brouard  12368:   char resultline[MAXLINE], resultlineori[MAXLINE];
1.230     brouard  12369:   
1.136     brouard  12370:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  12371:   char *tok, *val; /* pathtot */
1.334     brouard  12372:   /* int firstobs=1, lastobs=10; /\* nobs = lastobs-firstobs declared globally ;*\/ */
1.195     brouard  12373:   int c,  h , cpt, c2;
1.191     brouard  12374:   int jl=0;
                   12375:   int i1, j1, jk, stepsize=0;
1.194     brouard  12376:   int count=0;
                   12377: 
1.164     brouard  12378:   int *tab; 
1.136     brouard  12379:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  12380:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   12381:   /* double anprojf, mprojf, jprojf; */
                   12382:   /* double jintmean,mintmean,aintmean;   */
                   12383:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   12384:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   12385:   double yrfproj= 10.0; /* Number of years of forward projections */
                   12386:   double yrbproj= 10.0; /* Number of years of backward projections */
                   12387:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  12388:   int mobilav=0,popforecast=0;
1.191     brouard  12389:   int hstepm=0, nhstepm=0;
1.136     brouard  12390:   int agemortsup;
                   12391:   float  sumlpop=0.;
                   12392:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   12393:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   12394: 
1.191     brouard  12395:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  12396:   double ftolpl=FTOL;
                   12397:   double **prlim;
1.217     brouard  12398:   double **bprlim;
1.317     brouard  12399:   double ***param; /* Matrix of parameters, param[i][j][k] param=ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel) 
                   12400:                     state of origin, state of destination including death, for each covariate: constante, age, and V1 V2 etc. */
1.251     brouard  12401:   double ***paramstart; /* Matrix of starting parameter values */
                   12402:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  12403:   double **matcov; /* Matrix of covariance */
1.203     brouard  12404:   double **hess; /* Hessian matrix */
1.136     brouard  12405:   double ***delti3; /* Scale */
                   12406:   double *delti; /* Scale */
                   12407:   double ***eij, ***vareij;
                   12408:   double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  12409: 
1.136     brouard  12410:   double *epj, vepp;
1.164     brouard  12411: 
1.273     brouard  12412:   double dateprev1, dateprev2;
1.296     brouard  12413:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   12414:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   12415: 
1.217     brouard  12416: 
1.136     brouard  12417:   double **ximort;
1.145     brouard  12418:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  12419:   int *dcwave;
                   12420: 
1.164     brouard  12421:   char z[1]="c";
1.136     brouard  12422: 
                   12423:   /*char  *strt;*/
                   12424:   char strtend[80];
1.126     brouard  12425: 
1.164     brouard  12426: 
1.126     brouard  12427: /*   setlocale (LC_ALL, ""); */
                   12428: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   12429: /*   textdomain (PACKAGE); */
                   12430: /*   setlocale (LC_CTYPE, ""); */
                   12431: /*   setlocale (LC_MESSAGES, ""); */
                   12432: 
                   12433:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  12434:   rstart_time = time(NULL);  
                   12435:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   12436:   start_time = *localtime(&rstart_time);
1.126     brouard  12437:   curr_time=start_time;
1.157     brouard  12438:   /*tml = *localtime(&start_time.tm_sec);*/
                   12439:   /* strcpy(strstart,asctime(&tml)); */
                   12440:   strcpy(strstart,asctime(&start_time));
1.126     brouard  12441: 
                   12442: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  12443: /*  tp.tm_sec = tp.tm_sec +86400; */
                   12444: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  12445: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   12446: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   12447: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  12448: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  12449: /*   strt=asctime(&tmg); */
                   12450: /*   printf("Time(after) =%s",strstart);  */
                   12451: /*  (void) time (&time_value);
                   12452: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   12453: *  tm = *localtime(&time_value);
                   12454: *  strstart=asctime(&tm);
                   12455: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   12456: */
                   12457: 
                   12458:   nberr=0; /* Number of errors and warnings */
                   12459:   nbwarn=0;
1.184     brouard  12460: #ifdef WIN32
                   12461:   _getcwd(pathcd, size);
                   12462: #else
1.126     brouard  12463:   getcwd(pathcd, size);
1.184     brouard  12464: #endif
1.191     brouard  12465:   syscompilerinfo(0);
1.196     brouard  12466:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  12467:   if(argc <=1){
                   12468:     printf("\nEnter the parameter file name: ");
1.205     brouard  12469:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   12470:       printf("ERROR Empty parameter file name\n");
                   12471:       goto end;
                   12472:     }
1.126     brouard  12473:     i=strlen(pathr);
                   12474:     if(pathr[i-1]=='\n')
                   12475:       pathr[i-1]='\0';
1.156     brouard  12476:     i=strlen(pathr);
1.205     brouard  12477:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  12478:       pathr[i-1]='\0';
1.205     brouard  12479:     }
                   12480:     i=strlen(pathr);
                   12481:     if( i==0 ){
                   12482:       printf("ERROR Empty parameter file name\n");
                   12483:       goto end;
                   12484:     }
                   12485:     for (tok = pathr; tok != NULL; ){
1.126     brouard  12486:       printf("Pathr |%s|\n",pathr);
                   12487:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   12488:       printf("val= |%s| pathr=%s\n",val,pathr);
                   12489:       strcpy (pathtot, val);
                   12490:       if(pathr[0] == '\0') break; /* Dirty */
                   12491:     }
                   12492:   }
1.281     brouard  12493:   else if (argc<=2){
                   12494:     strcpy(pathtot,argv[1]);
                   12495:   }
1.126     brouard  12496:   else{
                   12497:     strcpy(pathtot,argv[1]);
1.281     brouard  12498:     strcpy(z,argv[2]);
                   12499:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  12500:   }
                   12501:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   12502:   /*cygwin_split_path(pathtot,path,optionfile);
                   12503:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   12504:   /* cutv(path,optionfile,pathtot,'\\');*/
                   12505: 
                   12506:   /* Split argv[0], imach program to get pathimach */
                   12507:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   12508:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   12509:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   12510:  /*   strcpy(pathimach,argv[0]); */
                   12511:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   12512:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   12513:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  12514: #ifdef WIN32
                   12515:   _chdir(path); /* Can be a relative path */
                   12516:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   12517: #else
1.126     brouard  12518:   chdir(path); /* Can be a relative path */
1.184     brouard  12519:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   12520: #endif
                   12521:   printf("Current directory %s!\n",pathcd);
1.126     brouard  12522:   strcpy(command,"mkdir ");
                   12523:   strcat(command,optionfilefiname);
                   12524:   if((outcmd=system(command)) != 0){
1.169     brouard  12525:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  12526:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   12527:     /* fclose(ficlog); */
                   12528: /*     exit(1); */
                   12529:   }
                   12530: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   12531: /*     perror("mkdir"); */
                   12532: /*   } */
                   12533: 
                   12534:   /*-------- arguments in the command line --------*/
                   12535: 
1.186     brouard  12536:   /* Main Log file */
1.126     brouard  12537:   strcat(filelog, optionfilefiname);
                   12538:   strcat(filelog,".log");    /* */
                   12539:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   12540:     printf("Problem with logfile %s\n",filelog);
                   12541:     goto end;
                   12542:   }
                   12543:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  12544:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  12545:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   12546:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   12547:  path=%s \n\
                   12548:  optionfile=%s\n\
                   12549:  optionfilext=%s\n\
1.156     brouard  12550:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  12551: 
1.197     brouard  12552:   syscompilerinfo(1);
1.167     brouard  12553: 
1.126     brouard  12554:   printf("Local time (at start):%s",strstart);
                   12555:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   12556:   fflush(ficlog);
                   12557: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  12558: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  12559: 
                   12560:   /* */
                   12561:   strcpy(fileres,"r");
                   12562:   strcat(fileres, optionfilefiname);
1.201     brouard  12563:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  12564:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  12565:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  12566: 
1.186     brouard  12567:   /* Main ---------arguments file --------*/
1.126     brouard  12568: 
                   12569:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  12570:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   12571:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  12572:     fflush(ficlog);
1.149     brouard  12573:     /* goto end; */
                   12574:     exit(70); 
1.126     brouard  12575:   }
                   12576: 
                   12577:   strcpy(filereso,"o");
1.201     brouard  12578:   strcat(filereso,fileresu);
1.126     brouard  12579:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   12580:     printf("Problem with Output resultfile: %s\n", filereso);
                   12581:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   12582:     fflush(ficlog);
                   12583:     goto end;
                   12584:   }
1.278     brouard  12585:       /*-------- Rewriting parameter file ----------*/
                   12586:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   12587:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   12588:   strcat(rfileres,".");    /* */
                   12589:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   12590:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   12591:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   12592:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   12593:     fflush(ficlog);
                   12594:     goto end;
                   12595:   }
                   12596:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  12597: 
1.278     brouard  12598:                                      
1.126     brouard  12599:   /* Reads comments: lines beginning with '#' */
                   12600:   numlinepar=0;
1.277     brouard  12601:   /* Is it a BOM UTF-8 Windows file? */
                   12602:   /* First parameter line */
1.197     brouard  12603:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  12604:     noffset=0;
                   12605:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   12606:     {
                   12607:       noffset=noffset+3;
                   12608:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   12609:     }
1.302     brouard  12610: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   12611:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
1.277     brouard  12612:     {
                   12613:       noffset=noffset+2;
                   12614:       printf("# File is an UTF16BE BOM file\n");
                   12615:     }
                   12616:     else if( line[0] == 0 && line[1] == 0)
                   12617:     {
                   12618:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   12619:        noffset=noffset+4;
                   12620:        printf("# File is an UTF16BE BOM file\n");
                   12621:       }
                   12622:     } else{
                   12623:       ;/*printf(" Not a BOM file\n");*/
                   12624:     }
                   12625:   
1.197     brouard  12626:     /* If line starts with a # it is a comment */
1.277     brouard  12627:     if (line[noffset] == '#') {
1.197     brouard  12628:       numlinepar++;
                   12629:       fputs(line,stdout);
                   12630:       fputs(line,ficparo);
1.278     brouard  12631:       fputs(line,ficres);
1.197     brouard  12632:       fputs(line,ficlog);
                   12633:       continue;
                   12634:     }else
                   12635:       break;
                   12636:   }
                   12637:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   12638:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   12639:     if (num_filled != 5) {
                   12640:       printf("Should be 5 parameters\n");
1.283     brouard  12641:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  12642:     }
1.126     brouard  12643:     numlinepar++;
1.197     brouard  12644:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  12645:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   12646:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   12647:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  12648:   }
                   12649:   /* Second parameter line */
                   12650:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  12651:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   12652:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  12653:     if (line[0] == '#') {
                   12654:       numlinepar++;
1.283     brouard  12655:       printf("%s",line);
                   12656:       fprintf(ficres,"%s",line);
                   12657:       fprintf(ficparo,"%s",line);
                   12658:       fprintf(ficlog,"%s",line);
1.197     brouard  12659:       continue;
                   12660:     }else
                   12661:       break;
                   12662:   }
1.223     brouard  12663:   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", \
                   12664:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   12665:     if (num_filled != 11) {
                   12666:       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  12667:       printf("but line=%s\n",line);
1.283     brouard  12668:       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");
                   12669:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  12670:     }
1.286     brouard  12671:     if( lastpass > maxwav){
                   12672:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   12673:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   12674:       fflush(ficlog);
                   12675:       goto end;
                   12676:     }
                   12677:       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  12678:     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  12679:     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  12680:     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  12681:   }
1.203     brouard  12682:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  12683:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  12684:   /* Third parameter line */
                   12685:   while(fgets(line, MAXLINE, ficpar)) {
                   12686:     /* If line starts with a # it is a comment */
                   12687:     if (line[0] == '#') {
                   12688:       numlinepar++;
1.283     brouard  12689:       printf("%s",line);
                   12690:       fprintf(ficres,"%s",line);
                   12691:       fprintf(ficparo,"%s",line);
                   12692:       fprintf(ficlog,"%s",line);
1.197     brouard  12693:       continue;
                   12694:     }else
                   12695:       break;
                   12696:   }
1.201     brouard  12697:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
1.279     brouard  12698:     if (num_filled != 1){
1.302     brouard  12699:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   12700:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
1.197     brouard  12701:       model[0]='\0';
                   12702:       goto end;
                   12703:     }
                   12704:     else{
                   12705:       if (model[0]=='+'){
                   12706:        for(i=1; i<=strlen(model);i++)
                   12707:          modeltemp[i-1]=model[i];
1.201     brouard  12708:        strcpy(model,modeltemp); 
1.197     brouard  12709:       }
                   12710:     }
1.338     brouard  12711:     /* printf(" model=1+age%s modeltemp= %s, model=1+age+%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  12712:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  12713:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   12714:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   12715:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  12716:   }
                   12717:   /* 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); */
                   12718:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   12719:   /* 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  12720:   /* 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); */
                   12721:   /* 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  12722:   fflush(ficlog);
1.190     brouard  12723:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   12724:   if(model[0]=='#'){
1.279     brouard  12725:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   12726:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   12727:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  12728:     if(mle != -1){
1.279     brouard  12729:       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  12730:       exit(1);
                   12731:     }
                   12732:   }
1.126     brouard  12733:   while((c=getc(ficpar))=='#' && c!= EOF){
                   12734:     ungetc(c,ficpar);
                   12735:     fgets(line, MAXLINE, ficpar);
                   12736:     numlinepar++;
1.195     brouard  12737:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   12738:       z[0]=line[1];
1.342     brouard  12739:     }else if(line[1]=='d'){ /* For debugging individual values of covariates in ficresilk */
1.343     brouard  12740:       debugILK=1;printf("DebugILK\n");
1.195     brouard  12741:     }
                   12742:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  12743:     fputs(line, stdout);
                   12744:     //puts(line);
1.126     brouard  12745:     fputs(line,ficparo);
                   12746:     fputs(line,ficlog);
                   12747:   }
                   12748:   ungetc(c,ficpar);
                   12749: 
                   12750:    
1.290     brouard  12751:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   12752:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   12753:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
1.341     brouard  12754:   /* if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /\**< Time varying covariate (dummy and quantitative)*\/ */
                   12755:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);  /**< Might be better */
1.136     brouard  12756:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   12757:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   12758:      v1+v2*age+v2*v3 makes cptcovn = 3
                   12759:   */
                   12760:   if (strlen(model)>1) 
1.187     brouard  12761:     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  12762:   else
1.187     brouard  12763:     ncovmodel=2; /* Constant and age */
1.133     brouard  12764:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   12765:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  12766:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   12767:     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);
                   12768:     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);
                   12769:     fflush(stdout);
                   12770:     fclose (ficlog);
                   12771:     goto end;
                   12772:   }
1.126     brouard  12773:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   12774:   delti=delti3[1][1];
                   12775:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   12776:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  12777: /* We could also provide initial parameters values giving by simple logistic regression 
                   12778:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   12779:       /* for(i=1;i<nlstate;i++){ */
                   12780:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   12781:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   12782:       /* } */
1.126     brouard  12783:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  12784:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   12785:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  12786:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   12787:     fclose (ficparo);
                   12788:     fclose (ficlog);
                   12789:     goto end;
                   12790:     exit(0);
1.220     brouard  12791:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  12792:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  12793:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   12794:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  12795:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   12796:     matcov=matrix(1,npar,1,npar);
1.203     brouard  12797:     hess=matrix(1,npar,1,npar);
1.220     brouard  12798:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  12799:     /* Read guessed parameters */
1.126     brouard  12800:     /* Reads comments: lines beginning with '#' */
                   12801:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12802:       ungetc(c,ficpar);
                   12803:       fgets(line, MAXLINE, ficpar);
                   12804:       numlinepar++;
1.141     brouard  12805:       fputs(line,stdout);
1.126     brouard  12806:       fputs(line,ficparo);
                   12807:       fputs(line,ficlog);
                   12808:     }
                   12809:     ungetc(c,ficpar);
                   12810:     
                   12811:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  12812:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  12813:     for(i=1; i <=nlstate; i++){
1.234     brouard  12814:       j=0;
1.126     brouard  12815:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  12816:        if(jj==i) continue;
                   12817:        j++;
1.292     brouard  12818:        while((c=getc(ficpar))=='#' && c!= EOF){
                   12819:          ungetc(c,ficpar);
                   12820:          fgets(line, MAXLINE, ficpar);
                   12821:          numlinepar++;
                   12822:          fputs(line,stdout);
                   12823:          fputs(line,ficparo);
                   12824:          fputs(line,ficlog);
                   12825:        }
                   12826:        ungetc(c,ficpar);
1.234     brouard  12827:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   12828:        if ((i1 != i) || (j1 != jj)){
                   12829:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  12830: It might be a problem of design; if ncovcol and the model are correct\n \
                   12831: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  12832:          exit(1);
                   12833:        }
                   12834:        fprintf(ficparo,"%1d%1d",i1,j1);
                   12835:        if(mle==1)
                   12836:          printf("%1d%1d",i,jj);
                   12837:        fprintf(ficlog,"%1d%1d",i,jj);
                   12838:        for(k=1; k<=ncovmodel;k++){
                   12839:          fscanf(ficpar," %lf",&param[i][j][k]);
                   12840:          if(mle==1){
                   12841:            printf(" %lf",param[i][j][k]);
                   12842:            fprintf(ficlog," %lf",param[i][j][k]);
                   12843:          }
                   12844:          else
                   12845:            fprintf(ficlog," %lf",param[i][j][k]);
                   12846:          fprintf(ficparo," %lf",param[i][j][k]);
                   12847:        }
                   12848:        fscanf(ficpar,"\n");
                   12849:        numlinepar++;
                   12850:        if(mle==1)
                   12851:          printf("\n");
                   12852:        fprintf(ficlog,"\n");
                   12853:        fprintf(ficparo,"\n");
1.126     brouard  12854:       }
                   12855:     }  
                   12856:     fflush(ficlog);
1.234     brouard  12857:     
1.251     brouard  12858:     /* Reads parameters values */
1.126     brouard  12859:     p=param[1][1];
1.251     brouard  12860:     pstart=paramstart[1][1];
1.126     brouard  12861:     
                   12862:     /* Reads comments: lines beginning with '#' */
                   12863:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12864:       ungetc(c,ficpar);
                   12865:       fgets(line, MAXLINE, ficpar);
                   12866:       numlinepar++;
1.141     brouard  12867:       fputs(line,stdout);
1.126     brouard  12868:       fputs(line,ficparo);
                   12869:       fputs(line,ficlog);
                   12870:     }
                   12871:     ungetc(c,ficpar);
                   12872: 
                   12873:     for(i=1; i <=nlstate; i++){
                   12874:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  12875:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   12876:        if ( (i1-i) * (j1-j) != 0){
                   12877:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   12878:          exit(1);
                   12879:        }
                   12880:        printf("%1d%1d",i,j);
                   12881:        fprintf(ficparo,"%1d%1d",i1,j1);
                   12882:        fprintf(ficlog,"%1d%1d",i1,j1);
                   12883:        for(k=1; k<=ncovmodel;k++){
                   12884:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   12885:          printf(" %le",delti3[i][j][k]);
                   12886:          fprintf(ficparo," %le",delti3[i][j][k]);
                   12887:          fprintf(ficlog," %le",delti3[i][j][k]);
                   12888:        }
                   12889:        fscanf(ficpar,"\n");
                   12890:        numlinepar++;
                   12891:        printf("\n");
                   12892:        fprintf(ficparo,"\n");
                   12893:        fprintf(ficlog,"\n");
1.126     brouard  12894:       }
                   12895:     }
                   12896:     fflush(ficlog);
1.234     brouard  12897:     
1.145     brouard  12898:     /* Reads covariance matrix */
1.126     brouard  12899:     delti=delti3[1][1];
1.220     brouard  12900:                
                   12901:                
1.126     brouard  12902:     /* 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  12903:                
1.126     brouard  12904:     /* Reads comments: lines beginning with '#' */
                   12905:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12906:       ungetc(c,ficpar);
                   12907:       fgets(line, MAXLINE, ficpar);
                   12908:       numlinepar++;
1.141     brouard  12909:       fputs(line,stdout);
1.126     brouard  12910:       fputs(line,ficparo);
                   12911:       fputs(line,ficlog);
                   12912:     }
                   12913:     ungetc(c,ficpar);
1.220     brouard  12914:                
1.126     brouard  12915:     matcov=matrix(1,npar,1,npar);
1.203     brouard  12916:     hess=matrix(1,npar,1,npar);
1.131     brouard  12917:     for(i=1; i <=npar; i++)
                   12918:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  12919:                
1.194     brouard  12920:     /* Scans npar lines */
1.126     brouard  12921:     for(i=1; i <=npar; i++){
1.226     brouard  12922:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  12923:       if(count != 3){
1.226     brouard  12924:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  12925: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   12926: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  12927:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  12928: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   12929: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  12930:        exit(1);
1.220     brouard  12931:       }else{
1.226     brouard  12932:        if(mle==1)
                   12933:          printf("%1d%1d%d",i1,j1,jk);
                   12934:       }
                   12935:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   12936:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  12937:       for(j=1; j <=i; j++){
1.226     brouard  12938:        fscanf(ficpar," %le",&matcov[i][j]);
                   12939:        if(mle==1){
                   12940:          printf(" %.5le",matcov[i][j]);
                   12941:        }
                   12942:        fprintf(ficlog," %.5le",matcov[i][j]);
                   12943:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  12944:       }
                   12945:       fscanf(ficpar,"\n");
                   12946:       numlinepar++;
                   12947:       if(mle==1)
1.220     brouard  12948:                                printf("\n");
1.126     brouard  12949:       fprintf(ficlog,"\n");
                   12950:       fprintf(ficparo,"\n");
                   12951:     }
1.194     brouard  12952:     /* End of read covariance matrix npar lines */
1.126     brouard  12953:     for(i=1; i <=npar; i++)
                   12954:       for(j=i+1;j<=npar;j++)
1.226     brouard  12955:        matcov[i][j]=matcov[j][i];
1.126     brouard  12956:     
                   12957:     if(mle==1)
                   12958:       printf("\n");
                   12959:     fprintf(ficlog,"\n");
                   12960:     
                   12961:     fflush(ficlog);
                   12962:     
                   12963:   }    /* End of mle != -3 */
1.218     brouard  12964:   
1.186     brouard  12965:   /*  Main data
                   12966:    */
1.290     brouard  12967:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   12968:   /* num=lvector(1,n); */
                   12969:   /* moisnais=vector(1,n); */
                   12970:   /* annais=vector(1,n); */
                   12971:   /* moisdc=vector(1,n); */
                   12972:   /* andc=vector(1,n); */
                   12973:   /* weight=vector(1,n); */
                   12974:   /* agedc=vector(1,n); */
                   12975:   /* cod=ivector(1,n); */
                   12976:   /* for(i=1;i<=n;i++){ */
                   12977:   num=lvector(firstobs,lastobs);
                   12978:   moisnais=vector(firstobs,lastobs);
                   12979:   annais=vector(firstobs,lastobs);
                   12980:   moisdc=vector(firstobs,lastobs);
                   12981:   andc=vector(firstobs,lastobs);
                   12982:   weight=vector(firstobs,lastobs);
                   12983:   agedc=vector(firstobs,lastobs);
                   12984:   cod=ivector(firstobs,lastobs);
                   12985:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  12986:     num[i]=0;
                   12987:     moisnais[i]=0;
                   12988:     annais[i]=0;
                   12989:     moisdc[i]=0;
                   12990:     andc[i]=0;
                   12991:     agedc[i]=0;
                   12992:     cod[i]=0;
                   12993:     weight[i]=1.0; /* Equal weights, 1 by default */
                   12994:   }
1.290     brouard  12995:   mint=matrix(1,maxwav,firstobs,lastobs);
                   12996:   anint=matrix(1,maxwav,firstobs,lastobs);
1.325     brouard  12997:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */
1.336     brouard  12998:   /* printf("BUG ncovmodel=%d NCOVMAX=%d 2**ncovmodel=%f BUG\n",ncovmodel,NCOVMAX,pow(2,ncovmodel)); */
1.126     brouard  12999:   tab=ivector(1,NCOVMAX);
1.144     brouard  13000:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  13001:   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  13002: 
1.136     brouard  13003:   /* Reads data from file datafile */
                   13004:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   13005:     goto end;
                   13006: 
                   13007:   /* Calculation of the number of parameters from char model */
1.234     brouard  13008:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  13009:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   13010:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   13011:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   13012:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  13013:   */
                   13014:   
                   13015:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   13016:   TvarsDind=ivector(1,NCOVMAX); /*  */
1.330     brouard  13017:   TnsdVar=ivector(1,NCOVMAX); /*  */
1.335     brouard  13018:     /* for(i=1; i<=NCOVMAX;i++) TnsdVar[i]=3; */
1.234     brouard  13019:   TvarsD=ivector(1,NCOVMAX); /*  */
                   13020:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   13021:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  13022:   TvarF=ivector(1,NCOVMAX); /*  */
                   13023:   TvarFind=ivector(1,NCOVMAX); /*  */
                   13024:   TvarV=ivector(1,NCOVMAX); /*  */
                   13025:   TvarVind=ivector(1,NCOVMAX); /*  */
                   13026:   TvarA=ivector(1,NCOVMAX); /*  */
                   13027:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  13028:   TvarFD=ivector(1,NCOVMAX); /*  */
                   13029:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   13030:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   13031:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   13032:   TvarVD=ivector(1,NCOVMAX); /*  */
                   13033:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   13034:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   13035:   TvarVQind=ivector(1,NCOVMAX); /*  */
1.339     brouard  13036:   TvarVV=ivector(1,NCOVMAX); /*  */
                   13037:   TvarVVind=ivector(1,NCOVMAX); /*  */
1.231     brouard  13038: 
1.230     brouard  13039:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  13040:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  13041:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   13042:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   13043:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.137     brouard  13044:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   13045:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   13046:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   13047:   */
                   13048:   /* For model-covariate k tells which data-covariate to use but
                   13049:     because this model-covariate is a construction we invent a new column
                   13050:     ncovcol + k1
                   13051:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   13052:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  13053:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   13054:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  13055:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   13056:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  13057:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  13058:   */
1.145     brouard  13059:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   13060:   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  13061:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   13062:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.330     brouard  13063:   Tvardk=imatrix(1,NCOVMAX,1,2);
1.145     brouard  13064:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  13065:                         4 covariates (3 plus signs)
                   13066:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
1.328     brouard  13067:                           */  
                   13068:   for(i=1;i<NCOVMAX;i++)
                   13069:     Tage[i]=0;
1.230     brouard  13070:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  13071:                                * individual dummy, fixed or varying:
                   13072:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   13073:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  13074:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   13075:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   13076:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   13077:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   13078:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  13079:                                * individual quantitative, fixed or varying:
                   13080:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   13081:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   13082:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.186     brouard  13083: /* Main decodemodel */
                   13084: 
1.187     brouard  13085: 
1.223     brouard  13086:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  13087:     goto end;
                   13088: 
1.137     brouard  13089:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   13090:     nbwarn++;
                   13091:     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); 
                   13092:     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); 
                   13093:   }
1.136     brouard  13094:     /*  if(mle==1){*/
1.137     brouard  13095:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   13096:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  13097:   }
                   13098: 
                   13099:     /*-calculation of age at interview from date of interview and age at death -*/
                   13100:   agev=matrix(1,maxwav,1,imx);
                   13101: 
                   13102:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   13103:     goto end;
                   13104: 
1.126     brouard  13105: 
1.136     brouard  13106:   agegomp=(int)agemin;
1.290     brouard  13107:   free_vector(moisnais,firstobs,lastobs);
                   13108:   free_vector(annais,firstobs,lastobs);
1.126     brouard  13109:   /* free_matrix(mint,1,maxwav,1,n);
                   13110:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  13111:   /* free_vector(moisdc,1,n); */
                   13112:   /* free_vector(andc,1,n); */
1.145     brouard  13113:   /* */
                   13114:   
1.126     brouard  13115:   wav=ivector(1,imx);
1.214     brouard  13116:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13117:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13118:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13119:   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.*/
                   13120:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   13121:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  13122:    
                   13123:   /* Concatenates waves */
1.214     brouard  13124:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   13125:      Death is a valid wave (if date is known).
                   13126:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   13127:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   13128:      and mw[mi+1][i]. dh depends on stepm.
                   13129:   */
                   13130: 
1.126     brouard  13131:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  13132:   /* Concatenates waves */
1.145     brouard  13133:  
1.290     brouard  13134:   free_vector(moisdc,firstobs,lastobs);
                   13135:   free_vector(andc,firstobs,lastobs);
1.215     brouard  13136: 
1.126     brouard  13137:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   13138:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   13139:   ncodemax[1]=1;
1.145     brouard  13140:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  13141:   cptcoveff=0;
1.220     brouard  13142:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
1.335     brouard  13143:     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  13144:   }
                   13145:   
                   13146:   ncovcombmax=pow(2,cptcoveff);
1.338     brouard  13147:   invalidvarcomb=ivector(0, ncovcombmax); 
                   13148:   for(i=0;i<ncovcombmax;i++)
1.227     brouard  13149:     invalidvarcomb[i]=0;
                   13150:   
1.211     brouard  13151:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  13152:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  13153:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  13154:   
1.200     brouard  13155:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  13156:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  13157:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  13158:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   13159:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   13160:    * (currently 0 or 1) in the data.
                   13161:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   13162:    * corresponding modality (h,j).
                   13163:    */
                   13164: 
1.145     brouard  13165:   h=0;
                   13166:   /*if (cptcovn > 0) */
1.126     brouard  13167:   m=pow(2,cptcoveff);
                   13168:  
1.144     brouard  13169:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  13170:           * For k=4 covariates, h goes from 1 to m=2**k
                   13171:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   13172:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.329     brouard  13173:           *     h\k   1     2     3     4   *  h-1\k-1  4  3  2  1          
                   13174:           *______________________________   *______________________
                   13175:           *     1 i=1 1 i=1 1 i=1 1 i=1 1   *     0     0  0  0  0 
                   13176:           *     2     2     1     1     1   *     1     0  0  0  1 
                   13177:           *     3 i=2 1     2     1     1   *     2     0  0  1  0 
                   13178:           *     4     2     2     1     1   *     3     0  0  1  1 
                   13179:           *     5 i=3 1 i=2 1     2     1   *     4     0  1  0  0 
                   13180:           *     6     2     1     2     1   *     5     0  1  0  1 
                   13181:           *     7 i=4 1     2     2     1   *     6     0  1  1  0 
                   13182:           *     8     2     2     2     1   *     7     0  1  1  1 
                   13183:           *     9 i=5 1 i=3 1 i=2 1     2   *     8     1  0  0  0 
                   13184:           *    10     2     1     1     2   *     9     1  0  0  1 
                   13185:           *    11 i=6 1     2     1     2   *    10     1  0  1  0 
                   13186:           *    12     2     2     1     2   *    11     1  0  1  1 
                   13187:           *    13 i=7 1 i=4 1     2     2   *    12     1  1  0  0  
                   13188:           *    14     2     1     2     2   *    13     1  1  0  1 
                   13189:           *    15 i=8 1     2     2     2   *    14     1  1  1  0 
                   13190:           *    16     2     2     2     2   *    15     1  1  1  1          
                   13191:           */                                     
1.212     brouard  13192:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  13193:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   13194:      * and the value of each covariate?
                   13195:      * V1=1, V2=1, V3=2, V4=1 ?
                   13196:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   13197:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   13198:      * In order to get the real value in the data, we use nbcode
                   13199:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   13200:      * We are keeping this crazy system in order to be able (in the future?) 
                   13201:      * to have more than 2 values (0 or 1) for a covariate.
                   13202:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   13203:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   13204:      *              bbbbbbbb
                   13205:      *              76543210     
                   13206:      *   h-1        00000101 (6-1=5)
1.219     brouard  13207:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  13208:      *           &
                   13209:      *     1        00000001 (1)
1.219     brouard  13210:      *              00000000        = 1 & ((h-1) >> (k-1))
                   13211:      *          +1= 00000001 =1 
1.211     brouard  13212:      *
                   13213:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   13214:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   13215:      *    >>k'            11
                   13216:      *          &   00000001
                   13217:      *            = 00000001
                   13218:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   13219:      * Reverse h=6 and m=16?
                   13220:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   13221:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   13222:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   13223:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   13224:      * V3=decodtabm(14,3,2**4)=2
                   13225:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   13226:      *(h-1) >> (j-1)    0011 =13 >> 2
                   13227:      *          &1 000000001
                   13228:      *           = 000000001
                   13229:      *         +1= 000000010 =2
                   13230:      *                  2211
                   13231:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   13232:      *                  V3=2
1.220     brouard  13233:                 * codtabm and decodtabm are identical
1.211     brouard  13234:      */
                   13235: 
1.145     brouard  13236: 
                   13237:  free_ivector(Ndum,-1,NCOVMAX);
                   13238: 
                   13239: 
1.126     brouard  13240:     
1.186     brouard  13241:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  13242:   strcpy(optionfilegnuplot,optionfilefiname);
                   13243:   if(mle==-3)
1.201     brouard  13244:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  13245:   strcat(optionfilegnuplot,".gp");
                   13246: 
                   13247:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   13248:     printf("Problem with file %s",optionfilegnuplot);
                   13249:   }
                   13250:   else{
1.204     brouard  13251:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  13252:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  13253:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   13254:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  13255:   }
                   13256:   /*  fclose(ficgp);*/
1.186     brouard  13257: 
                   13258: 
                   13259:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  13260: 
                   13261:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   13262:   if(mle==-3)
1.201     brouard  13263:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  13264:   strcat(optionfilehtm,".htm");
                   13265:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  13266:     printf("Problem with %s \n",optionfilehtm);
                   13267:     exit(0);
1.126     brouard  13268:   }
                   13269: 
                   13270:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   13271:   strcat(optionfilehtmcov,"-cov.htm");
                   13272:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   13273:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   13274:   }
                   13275:   else{
                   13276:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   13277: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  13278: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  13279:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   13280:   }
                   13281: 
1.335     brouard  13282:   fprintf(fichtm,"<html><head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n\
                   13283: <title>IMaCh %s</title></head>\n\
                   13284:  <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n\
                   13285: <font size=\"3\">Sponsored by Copyright (C)  2002-2015 <a href=http://www.ined.fr>INED</a>\
                   13286: -EUROREVES-Institut de longévité-2013-2022-Japan Society for the Promotion of Sciences 日本学術振興会 \
                   13287: (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - \
                   13288: <a href=https://software.intel.com/en-us>Intel Software 2015-2018</a></font><br> \n", optionfilehtm);
                   13289:   
                   13290:   fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  13291: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  13292: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.337     brouard  13293: 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  13294: \n\
                   13295: <hr  size=\"2\" color=\"#EC5E5E\">\
                   13296:  <ul><li><h4>Parameter files</h4>\n\
                   13297:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   13298:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   13299:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   13300:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   13301:  - Date and time at start: %s</ul>\n",\
1.335     brouard  13302:          version,fullversion,optionfilehtm,optionfilehtm,title,datafile,datafile,firstpass,lastpass,stepm, weightopt, model, \
1.126     brouard  13303:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   13304:          fileres,fileres,\
                   13305:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   13306:   fflush(fichtm);
                   13307: 
                   13308:   strcpy(pathr,path);
                   13309:   strcat(pathr,optionfilefiname);
1.184     brouard  13310: #ifdef WIN32
                   13311:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   13312: #else
1.126     brouard  13313:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  13314: #endif
                   13315:          
1.126     brouard  13316:   
1.220     brouard  13317:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   13318:                 and for any valid combination of covariates
1.126     brouard  13319:      and prints on file fileres'p'. */
1.251     brouard  13320:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  13321:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  13322: 
                   13323:   fprintf(fichtm,"\n");
1.286     brouard  13324:   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  13325:          ftol, stepm);
                   13326:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   13327:   ncurrv=1;
                   13328:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   13329:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   13330:   ncurrv=i;
                   13331:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  13332:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  13333:   ncurrv=i;
                   13334:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  13335:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  13336:   ncurrv=i;
                   13337:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   13338:   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", \
                   13339:           nlstate, ndeath, maxwav, mle, weightopt);
                   13340: 
                   13341:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   13342: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   13343: 
                   13344:   
1.317     brouard  13345:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Number of (used) observations=%d <br>\n\
1.126     brouard  13346: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   13347: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  13348:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  13349:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  13350:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   13351:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   13352:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   13353:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  13354: 
1.126     brouard  13355:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   13356:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   13357:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   13358: 
                   13359:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  13360:   /* For mortality only */
1.126     brouard  13361:   if (mle==-3){
1.136     brouard  13362:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  13363:     for(i=1;i<=NDIM;i++)
                   13364:       for(j=1;j<=NDIM;j++)
                   13365:        ximort[i][j]=0.;
1.186     brouard  13366:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  13367:     cens=ivector(firstobs,lastobs);
                   13368:     ageexmed=vector(firstobs,lastobs);
                   13369:     agecens=vector(firstobs,lastobs);
                   13370:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  13371:                
1.126     brouard  13372:     for (i=1; i<=imx; i++){
                   13373:       dcwave[i]=-1;
                   13374:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  13375:        if (s[m][i]>nlstate) {
                   13376:          dcwave[i]=m;
                   13377:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   13378:          break;
                   13379:        }
1.126     brouard  13380:     }
1.226     brouard  13381:     
1.126     brouard  13382:     for (i=1; i<=imx; i++) {
                   13383:       if (wav[i]>0){
1.226     brouard  13384:        ageexmed[i]=agev[mw[1][i]][i];
                   13385:        j=wav[i];
                   13386:        agecens[i]=1.; 
                   13387:        
                   13388:        if (ageexmed[i]> 1 && wav[i] > 0){
                   13389:          agecens[i]=agev[mw[j][i]][i];
                   13390:          cens[i]= 1;
                   13391:        }else if (ageexmed[i]< 1) 
                   13392:          cens[i]= -1;
                   13393:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   13394:          cens[i]=0 ;
1.126     brouard  13395:       }
                   13396:       else cens[i]=-1;
                   13397:     }
                   13398:     
                   13399:     for (i=1;i<=NDIM;i++) {
                   13400:       for (j=1;j<=NDIM;j++)
1.226     brouard  13401:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  13402:     }
                   13403:     
1.302     brouard  13404:     p[1]=0.0268; p[NDIM]=0.083;
                   13405:     /* printf("%lf %lf", p[1], p[2]); */
1.126     brouard  13406:     
                   13407:     
1.136     brouard  13408: #ifdef GSL
                   13409:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  13410: #else
1.126     brouard  13411:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  13412: #endif
1.201     brouard  13413:     strcpy(filerespow,"POW-MORT_"); 
                   13414:     strcat(filerespow,fileresu);
1.126     brouard  13415:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   13416:       printf("Problem with resultfile: %s\n", filerespow);
                   13417:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   13418:     }
1.136     brouard  13419: #ifdef GSL
                   13420:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  13421: #else
1.126     brouard  13422:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  13423: #endif
1.126     brouard  13424:     /*  for (i=1;i<=nlstate;i++)
                   13425:        for(j=1;j<=nlstate+ndeath;j++)
                   13426:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   13427:     */
                   13428:     fprintf(ficrespow,"\n");
1.136     brouard  13429: #ifdef GSL
                   13430:     /* gsl starts here */ 
                   13431:     T = gsl_multimin_fminimizer_nmsimplex;
                   13432:     gsl_multimin_fminimizer *sfm = NULL;
                   13433:     gsl_vector *ss, *x;
                   13434:     gsl_multimin_function minex_func;
                   13435: 
                   13436:     /* Initial vertex size vector */
                   13437:     ss = gsl_vector_alloc (NDIM);
                   13438:     
                   13439:     if (ss == NULL){
                   13440:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   13441:     }
                   13442:     /* Set all step sizes to 1 */
                   13443:     gsl_vector_set_all (ss, 0.001);
                   13444: 
                   13445:     /* Starting point */
1.126     brouard  13446:     
1.136     brouard  13447:     x = gsl_vector_alloc (NDIM);
                   13448:     
                   13449:     if (x == NULL){
                   13450:       gsl_vector_free(ss);
                   13451:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   13452:     }
                   13453:   
                   13454:     /* Initialize method and iterate */
                   13455:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  13456:     /*     gsl_vector_set(x, 0, 0.0268); */
                   13457:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  13458:     gsl_vector_set(x, 0, p[1]);
                   13459:     gsl_vector_set(x, 1, p[2]);
                   13460: 
                   13461:     minex_func.f = &gompertz_f;
                   13462:     minex_func.n = NDIM;
                   13463:     minex_func.params = (void *)&p; /* ??? */
                   13464:     
                   13465:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   13466:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   13467:     
                   13468:     printf("Iterations beginning .....\n\n");
                   13469:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   13470: 
                   13471:     iteri=0;
                   13472:     while (rval == GSL_CONTINUE){
                   13473:       iteri++;
                   13474:       status = gsl_multimin_fminimizer_iterate(sfm);
                   13475:       
                   13476:       if (status) printf("error: %s\n", gsl_strerror (status));
                   13477:       fflush(0);
                   13478:       
                   13479:       if (status) 
                   13480:         break;
                   13481:       
                   13482:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   13483:       ssval = gsl_multimin_fminimizer_size (sfm);
                   13484:       
                   13485:       if (rval == GSL_SUCCESS)
                   13486:         printf ("converged to a local maximum at\n");
                   13487:       
                   13488:       printf("%5d ", iteri);
                   13489:       for (it = 0; it < NDIM; it++){
                   13490:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   13491:       }
                   13492:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   13493:     }
                   13494:     
                   13495:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   13496:     
                   13497:     gsl_vector_free(x); /* initial values */
                   13498:     gsl_vector_free(ss); /* inital step size */
                   13499:     for (it=0; it<NDIM; it++){
                   13500:       p[it+1]=gsl_vector_get(sfm->x,it);
                   13501:       fprintf(ficrespow," %.12lf", p[it]);
                   13502:     }
                   13503:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   13504: #endif
                   13505: #ifdef POWELL
                   13506:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   13507: #endif  
1.126     brouard  13508:     fclose(ficrespow);
                   13509:     
1.203     brouard  13510:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  13511: 
                   13512:     for(i=1; i <=NDIM; i++)
                   13513:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  13514:                                matcov[i][j]=matcov[j][i];
1.126     brouard  13515:     
                   13516:     printf("\nCovariance matrix\n ");
1.203     brouard  13517:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  13518:     for(i=1; i <=NDIM; i++) {
                   13519:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  13520:                                printf("%f ",matcov[i][j]);
                   13521:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  13522:       }
1.203     brouard  13523:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  13524:     }
                   13525:     
                   13526:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  13527:     for (i=1;i<=NDIM;i++) {
1.126     brouard  13528:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  13529:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   13530:     }
1.302     brouard  13531:     lsurv=vector(agegomp,AGESUP);
                   13532:     lpop=vector(agegomp,AGESUP);
                   13533:     tpop=vector(agegomp,AGESUP);
1.126     brouard  13534:     lsurv[agegomp]=100000;
                   13535:     
                   13536:     for (k=agegomp;k<=AGESUP;k++) {
                   13537:       agemortsup=k;
                   13538:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   13539:     }
                   13540:     
                   13541:     for (k=agegomp;k<agemortsup;k++)
                   13542:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   13543:     
                   13544:     for (k=agegomp;k<agemortsup;k++){
                   13545:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   13546:       sumlpop=sumlpop+lpop[k];
                   13547:     }
                   13548:     
                   13549:     tpop[agegomp]=sumlpop;
                   13550:     for (k=agegomp;k<(agemortsup-3);k++){
                   13551:       /*  tpop[k+1]=2;*/
                   13552:       tpop[k+1]=tpop[k]-lpop[k];
                   13553:     }
                   13554:     
                   13555:     
                   13556:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   13557:     for (k=agegomp;k<(agemortsup-2);k++) 
                   13558:       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]);
                   13559:     
                   13560:     
                   13561:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  13562:                ageminpar=50;
                   13563:                agemaxpar=100;
1.194     brouard  13564:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   13565:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   13566: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13567: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   13568:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   13569: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13570: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  13571:     }else{
                   13572:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   13573:                        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  13574:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  13575:                }
1.201     brouard  13576:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  13577:                     stepm, weightopt,\
                   13578:                     model,imx,p,matcov,agemortsup);
                   13579:     
1.302     brouard  13580:     free_vector(lsurv,agegomp,AGESUP);
                   13581:     free_vector(lpop,agegomp,AGESUP);
                   13582:     free_vector(tpop,agegomp,AGESUP);
1.220     brouard  13583:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  13584:     free_ivector(dcwave,firstobs,lastobs);
                   13585:     free_vector(agecens,firstobs,lastobs);
                   13586:     free_vector(ageexmed,firstobs,lastobs);
                   13587:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  13588: #ifdef GSL
1.136     brouard  13589: #endif
1.186     brouard  13590:   } /* Endof if mle==-3 mortality only */
1.205     brouard  13591:   /* Standard  */
                   13592:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   13593:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   13594:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  13595:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  13596:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   13597:     for (k=1; k<=npar;k++)
                   13598:       printf(" %d %8.5f",k,p[k]);
                   13599:     printf("\n");
1.205     brouard  13600:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   13601:       /* mlikeli uses func not funcone */
1.247     brouard  13602:       /* for(i=1;i<nlstate;i++){ */
                   13603:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   13604:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   13605:       /* } */
1.205     brouard  13606:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   13607:     }
                   13608:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   13609:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   13610:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   13611:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   13612:     }
                   13613:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  13614:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   13615:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
1.335     brouard  13616:           /* exit(0); */
1.126     brouard  13617:     for (k=1; k<=npar;k++)
                   13618:       printf(" %d %8.5f",k,p[k]);
                   13619:     printf("\n");
                   13620:     
                   13621:     /*--------- results files --------------*/
1.283     brouard  13622:     /* 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  13623:     
                   13624:     
                   13625:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  13626:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); /* Printing model equation */
1.126     brouard  13627:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  13628: 
                   13629:     printf("#model=  1      +     age ");
                   13630:     fprintf(ficres,"#model=  1      +     age ");
                   13631:     fprintf(ficlog,"#model=  1      +     age ");
                   13632:     fprintf(fichtm,"\n<ul><li> model=1+age+%s\n \
                   13633: </ul>", model);
                   13634: 
                   13635:     fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">\n");
                   13636:     fprintf(fichtm, "<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   13637:     if(nagesqr==1){
                   13638:       printf("  + age*age  ");
                   13639:       fprintf(ficres,"  + age*age  ");
                   13640:       fprintf(ficlog,"  + age*age  ");
                   13641:       fprintf(fichtm, "<th>+ age*age</th>");
                   13642:     }
                   13643:     for(j=1;j <=ncovmodel-2;j++){
                   13644:       if(Typevar[j]==0) {
                   13645:        printf("  +      V%d  ",Tvar[j]);
                   13646:        fprintf(ficres,"  +      V%d  ",Tvar[j]);
                   13647:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   13648:        fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   13649:       }else if(Typevar[j]==1) {
                   13650:        printf("  +    V%d*age ",Tvar[j]);
                   13651:        fprintf(ficres,"  +    V%d*age ",Tvar[j]);
                   13652:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   13653:        fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   13654:       }else if(Typevar[j]==2) {
                   13655:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13656:        fprintf(ficres,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13657:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13658:        fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13659:       }
                   13660:     }
                   13661:     printf("\n");
                   13662:     fprintf(ficres,"\n");
                   13663:     fprintf(ficlog,"\n");
                   13664:     fprintf(fichtm, "</tr>");
                   13665:     fprintf(fichtm, "\n");
                   13666:     
                   13667:     
1.126     brouard  13668:     for(i=1,jk=1; i <=nlstate; i++){
                   13669:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  13670:        if (k != i) {
1.319     brouard  13671:          fprintf(fichtm, "<tr>");
1.225     brouard  13672:          printf("%d%d ",i,k);
                   13673:          fprintf(ficlog,"%d%d ",i,k);
                   13674:          fprintf(ficres,"%1d%1d ",i,k);
1.319     brouard  13675:          fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  13676:          for(j=1; j <=ncovmodel; j++){
                   13677:            printf("%12.7f ",p[jk]);
                   13678:            fprintf(ficlog,"%12.7f ",p[jk]);
                   13679:            fprintf(ficres,"%12.7f ",p[jk]);
1.319     brouard  13680:            fprintf(fichtm, "<td>%12.7f</td>",p[jk]);
1.225     brouard  13681:            jk++; 
                   13682:          }
                   13683:          printf("\n");
                   13684:          fprintf(ficlog,"\n");
                   13685:          fprintf(ficres,"\n");
1.319     brouard  13686:          fprintf(fichtm, "</tr>\n");
1.225     brouard  13687:        }
1.126     brouard  13688:       }
                   13689:     }
1.319     brouard  13690:     /* fprintf(fichtm,"</tr>\n"); */
                   13691:     fprintf(fichtm,"</table>\n");
                   13692:     fprintf(fichtm, "\n");
                   13693: 
1.203     brouard  13694:     if(mle != 0){
                   13695:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  13696:       ftolhess=ftol; /* Usually correct */
1.203     brouard  13697:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   13698:       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");
                   13699:       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  13700:       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  13701:       fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">");
                   13702:       fprintf(fichtm, "\n<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   13703:       if(nagesqr==1){
                   13704:        printf("  + age*age  ");
                   13705:        fprintf(ficres,"  + age*age  ");
                   13706:        fprintf(ficlog,"  + age*age  ");
                   13707:        fprintf(fichtm, "<th>+ age*age</th>");
                   13708:       }
                   13709:       for(j=1;j <=ncovmodel-2;j++){
                   13710:        if(Typevar[j]==0) {
                   13711:          printf("  +      V%d  ",Tvar[j]);
                   13712:          fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   13713:        }else if(Typevar[j]==1) {
                   13714:          printf("  +    V%d*age ",Tvar[j]);
                   13715:          fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   13716:        }else if(Typevar[j]==2) {
                   13717:          fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13718:        }
                   13719:       }
                   13720:       fprintf(fichtm, "</tr>\n");
                   13721:  
1.203     brouard  13722:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  13723:        for(k=1; k <=(nlstate+ndeath); k++){
                   13724:          if (k != i) {
1.319     brouard  13725:            fprintf(fichtm, "<tr valign=top>");
1.225     brouard  13726:            printf("%d%d ",i,k);
                   13727:            fprintf(ficlog,"%d%d ",i,k);
1.319     brouard  13728:            fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  13729:            for(j=1; j <=ncovmodel; j++){
1.319     brouard  13730:              wald=p[jk]/sqrt(matcov[jk][jk]);
1.324     brouard  13731:              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]));
                   13732:              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  13733:              if(fabs(wald) > 1.96){
1.321     brouard  13734:                fprintf(fichtm, "<td><b>%12.7f</b></br> (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
1.319     brouard  13735:              }else{
                   13736:                fprintf(fichtm, "<td>%12.7f (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
                   13737:              }
1.324     brouard  13738:              fprintf(fichtm,"W=%8.3f</br>",wald);
1.319     brouard  13739:              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  13740:              jk++; 
                   13741:            }
                   13742:            printf("\n");
                   13743:            fprintf(ficlog,"\n");
1.319     brouard  13744:            fprintf(fichtm, "</tr>\n");
1.225     brouard  13745:          }
                   13746:        }
1.193     brouard  13747:       }
1.203     brouard  13748:     } /* end of hesscov and Wald tests */
1.319     brouard  13749:     fprintf(fichtm,"</table>\n");
1.225     brouard  13750:     
1.203     brouard  13751:     /*  */
1.126     brouard  13752:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   13753:     printf("# Scales (for hessian or gradient estimation)\n");
                   13754:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   13755:     for(i=1,jk=1; i <=nlstate; i++){
                   13756:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  13757:        if (j!=i) {
                   13758:          fprintf(ficres,"%1d%1d",i,j);
                   13759:          printf("%1d%1d",i,j);
                   13760:          fprintf(ficlog,"%1d%1d",i,j);
                   13761:          for(k=1; k<=ncovmodel;k++){
                   13762:            printf(" %.5e",delti[jk]);
                   13763:            fprintf(ficlog," %.5e",delti[jk]);
                   13764:            fprintf(ficres," %.5e",delti[jk]);
                   13765:            jk++;
                   13766:          }
                   13767:          printf("\n");
                   13768:          fprintf(ficlog,"\n");
                   13769:          fprintf(ficres,"\n");
                   13770:        }
1.126     brouard  13771:       }
                   13772:     }
                   13773:     
                   13774:     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  13775:     if(mle >= 1) /* To big for the screen */
1.126     brouard  13776:       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");
                   13777:     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");
                   13778:     /* # 121 Var(a12)\n\ */
                   13779:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   13780:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   13781:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   13782:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   13783:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   13784:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   13785:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   13786:     
                   13787:     
                   13788:     /* Just to have a covariance matrix which will be more understandable
                   13789:        even is we still don't want to manage dictionary of variables
                   13790:     */
                   13791:     for(itimes=1;itimes<=2;itimes++){
                   13792:       jj=0;
                   13793:       for(i=1; i <=nlstate; i++){
1.225     brouard  13794:        for(j=1; j <=nlstate+ndeath; j++){
                   13795:          if(j==i) continue;
                   13796:          for(k=1; k<=ncovmodel;k++){
                   13797:            jj++;
                   13798:            ca[0]= k+'a'-1;ca[1]='\0';
                   13799:            if(itimes==1){
                   13800:              if(mle>=1)
                   13801:                printf("#%1d%1d%d",i,j,k);
                   13802:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   13803:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   13804:            }else{
                   13805:              if(mle>=1)
                   13806:                printf("%1d%1d%d",i,j,k);
                   13807:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   13808:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   13809:            }
                   13810:            ll=0;
                   13811:            for(li=1;li <=nlstate; li++){
                   13812:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   13813:                if(lj==li) continue;
                   13814:                for(lk=1;lk<=ncovmodel;lk++){
                   13815:                  ll++;
                   13816:                  if(ll<=jj){
                   13817:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   13818:                    if(ll<jj){
                   13819:                      if(itimes==1){
                   13820:                        if(mle>=1)
                   13821:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13822:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13823:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13824:                      }else{
                   13825:                        if(mle>=1)
                   13826:                          printf(" %.5e",matcov[jj][ll]); 
                   13827:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   13828:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   13829:                      }
                   13830:                    }else{
                   13831:                      if(itimes==1){
                   13832:                        if(mle>=1)
                   13833:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   13834:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   13835:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   13836:                      }else{
                   13837:                        if(mle>=1)
                   13838:                          printf(" %.7e",matcov[jj][ll]); 
                   13839:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   13840:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   13841:                      }
                   13842:                    }
                   13843:                  }
                   13844:                } /* end lk */
                   13845:              } /* end lj */
                   13846:            } /* end li */
                   13847:            if(mle>=1)
                   13848:              printf("\n");
                   13849:            fprintf(ficlog,"\n");
                   13850:            fprintf(ficres,"\n");
                   13851:            numlinepar++;
                   13852:          } /* end k*/
                   13853:        } /*end j */
1.126     brouard  13854:       } /* end i */
                   13855:     } /* end itimes */
                   13856:     
                   13857:     fflush(ficlog);
                   13858:     fflush(ficres);
1.225     brouard  13859:     while(fgets(line, MAXLINE, ficpar)) {
                   13860:       /* If line starts with a # it is a comment */
                   13861:       if (line[0] == '#') {
                   13862:        numlinepar++;
                   13863:        fputs(line,stdout);
                   13864:        fputs(line,ficparo);
                   13865:        fputs(line,ficlog);
1.299     brouard  13866:        fputs(line,ficres);
1.225     brouard  13867:        continue;
                   13868:       }else
                   13869:        break;
                   13870:     }
                   13871:     
1.209     brouard  13872:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   13873:     /*   ungetc(c,ficpar); */
                   13874:     /*   fgets(line, MAXLINE, ficpar); */
                   13875:     /*   fputs(line,stdout); */
                   13876:     /*   fputs(line,ficparo); */
                   13877:     /* } */
                   13878:     /* ungetc(c,ficpar); */
1.126     brouard  13879:     
                   13880:     estepm=0;
1.209     brouard  13881:     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  13882:       
                   13883:       if (num_filled != 6) {
                   13884:        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);
                   13885:        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);
                   13886:        goto end;
                   13887:       }
                   13888:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   13889:     }
                   13890:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   13891:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   13892:     
1.209     brouard  13893:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  13894:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   13895:     if (fage <= 2) {
                   13896:       bage = ageminpar;
                   13897:       fage = agemaxpar;
                   13898:     }
                   13899:     
                   13900:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  13901:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   13902:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  13903:                
1.186     brouard  13904:     /* Other stuffs, more or less useful */    
1.254     brouard  13905:     while(fgets(line, MAXLINE, ficpar)) {
                   13906:       /* If line starts with a # it is a comment */
                   13907:       if (line[0] == '#') {
                   13908:        numlinepar++;
                   13909:        fputs(line,stdout);
                   13910:        fputs(line,ficparo);
                   13911:        fputs(line,ficlog);
1.299     brouard  13912:        fputs(line,ficres);
1.254     brouard  13913:        continue;
                   13914:       }else
                   13915:        break;
                   13916:     }
                   13917: 
                   13918:     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){
                   13919:       
                   13920:       if (num_filled != 7) {
                   13921:        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);
                   13922:        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);
                   13923:        goto end;
                   13924:       }
                   13925:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   13926:       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);
                   13927:       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);
                   13928:       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  13929:     }
1.254     brouard  13930: 
                   13931:     while(fgets(line, MAXLINE, ficpar)) {
                   13932:       /* If line starts with a # it is a comment */
                   13933:       if (line[0] == '#') {
                   13934:        numlinepar++;
                   13935:        fputs(line,stdout);
                   13936:        fputs(line,ficparo);
                   13937:        fputs(line,ficlog);
1.299     brouard  13938:        fputs(line,ficres);
1.254     brouard  13939:        continue;
                   13940:       }else
                   13941:        break;
1.126     brouard  13942:     }
                   13943:     
                   13944:     
                   13945:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   13946:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   13947:     
1.254     brouard  13948:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   13949:       if (num_filled != 1) {
                   13950:        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);
                   13951:        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);
                   13952:        goto end;
                   13953:       }
                   13954:       printf("pop_based=%d\n",popbased);
                   13955:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   13956:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   13957:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   13958:     }
                   13959:      
1.258     brouard  13960:     /* Results */
1.332     brouard  13961:     /* Value of covariate in each resultine will be compututed (if product) and sorted according to model rank */
                   13962:     /* It is precov[] because we need the varying age in order to compute the real cov[] of the model equation */  
                   13963:     precov=matrix(1,MAXRESULTLINESPONE,1,NCOVMAX+1);
1.307     brouard  13964:     endishere=0;
1.258     brouard  13965:     nresult=0;
1.308     brouard  13966:     parameterline=0;
1.258     brouard  13967:     do{
                   13968:       if(!fgets(line, MAXLINE, ficpar)){
                   13969:        endishere=1;
1.308     brouard  13970:        parameterline=15;
1.258     brouard  13971:       }else if (line[0] == '#') {
                   13972:        /* If line starts with a # it is a comment */
1.254     brouard  13973:        numlinepar++;
                   13974:        fputs(line,stdout);
                   13975:        fputs(line,ficparo);
                   13976:        fputs(line,ficlog);
1.299     brouard  13977:        fputs(line,ficres);
1.254     brouard  13978:        continue;
1.258     brouard  13979:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   13980:        parameterline=11;
1.296     brouard  13981:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  13982:        parameterline=12;
1.307     brouard  13983:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
1.258     brouard  13984:        parameterline=13;
1.307     brouard  13985:       }
1.258     brouard  13986:       else{
                   13987:        parameterline=14;
1.254     brouard  13988:       }
1.308     brouard  13989:       switch (parameterline){ /* =0 only if only comments */
1.258     brouard  13990:       case 11:
1.296     brouard  13991:        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)){
                   13992:                  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  13993:          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);
                   13994:          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);
                   13995:          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);
                   13996:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  13997:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   13998:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  13999:           prvforecast = 1;
                   14000:        } 
                   14001:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.313     brouard  14002:          printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   14003:          fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   14004:          fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  14005:           prvforecast = 2;
                   14006:        }
                   14007:        else {
                   14008:          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);
                   14009:          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);
                   14010:          goto end;
1.258     brouard  14011:        }
1.254     brouard  14012:        break;
1.258     brouard  14013:       case 12:
1.296     brouard  14014:        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)){
                   14015:           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);
                   14016:          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);
                   14017:          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);
                   14018:          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);
                   14019:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  14020:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   14021:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  14022:           prvbackcast = 1;
                   14023:        } 
                   14024:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.313     brouard  14025:          printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   14026:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   14027:          fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  14028:           prvbackcast = 2;
                   14029:        }
                   14030:        else {
                   14031:          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);
                   14032:          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);
                   14033:          goto end;
1.258     brouard  14034:        }
1.230     brouard  14035:        break;
1.258     brouard  14036:       case 13:
1.332     brouard  14037:        num_filled=sscanf(line,"result:%[^\n]\n",resultlineori);
1.307     brouard  14038:        nresult++; /* Sum of resultlines */
1.342     brouard  14039:        /* printf("Result %d: result:%s\n",nresult, resultlineori); */
1.332     brouard  14040:        /* removefirstspace(&resultlineori); */
                   14041:        
                   14042:        if(strstr(resultlineori,"v") !=0){
                   14043:          printf("Error. 'v' must be in upper case 'V' result: %s ",resultlineori);
                   14044:          fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultlineori);fflush(ficlog);
                   14045:          return 1;
                   14046:        }
                   14047:        trimbb(resultline, resultlineori); /* Suppressing double blank in the resultline */
1.342     brouard  14048:        /* printf("Decoderesult resultline=\"%s\" resultlineori=\"%s\"\n", resultline, resultlineori); */
1.318     brouard  14049:        if(nresult > MAXRESULTLINESPONE-1){
                   14050:          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);
                   14051:          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  14052:          goto end;
                   14053:        }
1.332     brouard  14054:        
1.310     brouard  14055:        if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.314     brouard  14056:          fprintf(ficparo,"result: %s\n",resultline);
                   14057:          fprintf(ficres,"result: %s\n",resultline);
                   14058:          fprintf(ficlog,"result: %s\n",resultline);
1.310     brouard  14059:        } else
                   14060:          goto end;
1.307     brouard  14061:        break;
                   14062:       case 14:
                   14063:        printf("Error: Unknown command '%s'\n",line);
                   14064:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
1.314     brouard  14065:        if(line[0] == ' ' || line[0] == '\n'){
                   14066:          printf("It should not be an empty line '%s'\n",line);
                   14067:          fprintf(ficlog,"It should not be an empty line '%s'\n",line);
                   14068:        }         
1.307     brouard  14069:        if(ncovmodel >=2 && nresult==0 ){
                   14070:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   14071:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  14072:        }
1.307     brouard  14073:        /* goto end; */
                   14074:        break;
1.308     brouard  14075:       case 15:
                   14076:        printf("End of resultlines.\n");
                   14077:        fprintf(ficlog,"End of resultlines.\n");
                   14078:        break;
                   14079:       default: /* parameterline =0 */
1.307     brouard  14080:        nresult=1;
                   14081:        decoderesult(".",nresult ); /* No covariate */
1.258     brouard  14082:       } /* End switch parameterline */
                   14083:     }while(endishere==0); /* End do */
1.126     brouard  14084:     
1.230     brouard  14085:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  14086:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  14087:     
                   14088:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  14089:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  14090:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  14091: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14092: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  14093:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  14094: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14095: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  14096:     }else{
1.270     brouard  14097:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  14098:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   14099:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   14100:       if(prvforecast==1){
                   14101:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   14102:         jprojd=jproj1;
                   14103:         mprojd=mproj1;
                   14104:         anprojd=anproj1;
                   14105:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   14106:         jprojf=jproj2;
                   14107:         mprojf=mproj2;
                   14108:         anprojf=anproj2;
                   14109:       } else if(prvforecast == 2){
                   14110:         dateprojd=dateintmean;
                   14111:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   14112:         dateprojf=dateintmean+yrfproj;
                   14113:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   14114:       }
                   14115:       if(prvbackcast==1){
                   14116:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   14117:         jbackd=jback1;
                   14118:         mbackd=mback1;
                   14119:         anbackd=anback1;
                   14120:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   14121:         jbackf=jback2;
                   14122:         mbackf=mback2;
                   14123:         anbackf=anback2;
                   14124:       } else if(prvbackcast == 2){
                   14125:         datebackd=dateintmean;
                   14126:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   14127:         datebackf=dateintmean-yrbproj;
                   14128:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   14129:       }
                   14130:       
                   14131:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);
1.220     brouard  14132:     }
                   14133:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  14134:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   14135:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  14136:                
1.225     brouard  14137:     /*------------ free_vector  -------------*/
                   14138:     /*  chdir(path); */
1.220     brouard  14139:                
1.215     brouard  14140:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   14141:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   14142:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   14143:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  14144:     free_lvector(num,firstobs,lastobs);
                   14145:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  14146:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   14147:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   14148:     fclose(ficparo);
                   14149:     fclose(ficres);
1.220     brouard  14150:                
                   14151:                
1.186     brouard  14152:     /* Other results (useful)*/
1.220     brouard  14153:                
                   14154:                
1.126     brouard  14155:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  14156:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   14157:     prlim=matrix(1,nlstate,1,nlstate);
1.332     brouard  14158:     /* Computes the prevalence limit for each combination k of the dummy covariates by calling prevalim(k) */
1.209     brouard  14159:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  14160:     fclose(ficrespl);
                   14161: 
                   14162:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  14163:     /*#include "hpijx.h"*/
1.332     brouard  14164:     /** 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?*/
                   14165:     /* calls hpxij with combination k */
1.180     brouard  14166:     hPijx(p, bage, fage);
1.145     brouard  14167:     fclose(ficrespij);
1.227     brouard  14168:     
1.220     brouard  14169:     /* ncovcombmax=  pow(2,cptcoveff); */
1.332     brouard  14170:     /*-------------- Variance of one-step probabilities for a combination ij or for nres ?---*/
1.145     brouard  14171:     k=1;
1.126     brouard  14172:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  14173:     
1.269     brouard  14174:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   14175:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   14176:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  14177:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  14178:        for(k=1;k<=ncovcombmax;k++)
                   14179:          probs[i][j][k]=0.;
1.269     brouard  14180:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   14181:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  14182:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  14183:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   14184:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  14185:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  14186:          for(k=1;k<=ncovcombmax;k++)
                   14187:            mobaverages[i][j][k]=0.;
1.219     brouard  14188:       mobaverage=mobaverages;
                   14189:       if (mobilav!=0) {
1.235     brouard  14190:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  14191:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  14192:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   14193:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   14194:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   14195:        }
1.269     brouard  14196:       } else if (mobilavproj !=0) {
1.235     brouard  14197:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  14198:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  14199:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   14200:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   14201:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   14202:        }
1.269     brouard  14203:       }else{
                   14204:        printf("Internal error moving average\n");
                   14205:        fflush(stdout);
                   14206:        exit(1);
1.219     brouard  14207:       }
                   14208:     }/* end if moving average */
1.227     brouard  14209:     
1.126     brouard  14210:     /*---------- Forecasting ------------------*/
1.296     brouard  14211:     if(prevfcast==1){ 
                   14212:       /*   /\*    if(stepm ==1){*\/ */
                   14213:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   14214:       /*This done previously after freqsummary.*/
                   14215:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   14216:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   14217:       
                   14218:       /* } else if (prvforecast==2){ */
                   14219:       /*   /\*    if(stepm ==1){*\/ */
                   14220:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   14221:       /* } */
                   14222:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   14223:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  14224:     }
1.269     brouard  14225: 
1.296     brouard  14226:     /* Prevbcasting */
                   14227:     if(prevbcast==1){
1.219     brouard  14228:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   14229:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   14230:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   14231: 
                   14232:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   14233: 
                   14234:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  14235: 
1.219     brouard  14236:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   14237:       fclose(ficresplb);
                   14238: 
1.222     brouard  14239:       hBijx(p, bage, fage, mobaverage);
                   14240:       fclose(ficrespijb);
1.219     brouard  14241: 
1.296     brouard  14242:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   14243:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   14244:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   14245:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   14246:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   14247:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   14248: 
                   14249:       
1.269     brouard  14250:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  14251: 
                   14252:       
1.269     brouard  14253:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  14254:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   14255:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   14256:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  14257:     }    /* end  Prevbcasting */
1.268     brouard  14258:  
1.186     brouard  14259:  
                   14260:     /* ------ Other prevalence ratios------------ */
1.126     brouard  14261: 
1.215     brouard  14262:     free_ivector(wav,1,imx);
                   14263:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   14264:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   14265:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  14266:                
                   14267:                
1.127     brouard  14268:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  14269:                
1.201     brouard  14270:     strcpy(filerese,"E_");
                   14271:     strcat(filerese,fileresu);
1.126     brouard  14272:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   14273:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   14274:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   14275:     }
1.208     brouard  14276:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   14277:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  14278: 
                   14279:     pstamp(ficreseij);
1.219     brouard  14280:                
1.235     brouard  14281:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   14282:     if (cptcovn < 1){i1=1;}
                   14283:     
                   14284:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   14285:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  14286:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  14287:        continue;
1.219     brouard  14288:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  14289:       printf("\n#****** ");
1.225     brouard  14290:       for(j=1;j<=cptcoveff;j++) {
1.332     brouard  14291:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   14292:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.235     brouard  14293:       }
                   14294:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.337     brouard  14295:        printf(" V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]); /* TvarsQ[j] gives the name of the jth quantitative (fixed or time v) */
                   14296:        fprintf(ficreseij,"V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]);
1.219     brouard  14297:       }
                   14298:       fprintf(ficreseij,"******\n");
1.235     brouard  14299:       printf("******\n");
1.219     brouard  14300:       
                   14301:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   14302:       oldm=oldms;savm=savms;
1.330     brouard  14303:       /* 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  14304:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  14305:       
1.219     brouard  14306:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  14307:     }
                   14308:     fclose(ficreseij);
1.208     brouard  14309:     printf("done evsij\n");fflush(stdout);
                   14310:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  14311: 
1.218     brouard  14312:                
1.227     brouard  14313:     /*---------- State-specific expectancies and variances ------------*/
1.336     brouard  14314:     /* Should be moved in a function */                
1.201     brouard  14315:     strcpy(filerest,"T_");
                   14316:     strcat(filerest,fileresu);
1.127     brouard  14317:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   14318:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   14319:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   14320:     }
1.208     brouard  14321:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   14322:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  14323:     strcpy(fileresstde,"STDE_");
                   14324:     strcat(fileresstde,fileresu);
1.126     brouard  14325:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  14326:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   14327:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  14328:     }
1.227     brouard  14329:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   14330:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  14331: 
1.201     brouard  14332:     strcpy(filerescve,"CVE_");
                   14333:     strcat(filerescve,fileresu);
1.126     brouard  14334:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  14335:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   14336:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  14337:     }
1.227     brouard  14338:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   14339:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  14340: 
1.201     brouard  14341:     strcpy(fileresv,"V_");
                   14342:     strcat(fileresv,fileresu);
1.126     brouard  14343:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   14344:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   14345:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   14346:     }
1.227     brouard  14347:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   14348:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  14349: 
1.235     brouard  14350:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   14351:     if (cptcovn < 1){i1=1;}
                   14352:     
1.334     brouard  14353:     for(nres=1; nres <= nresult; nres++) /* For each resultline, find the combination and output results according to the values of dummies and then quanti.  */
                   14354:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying. For each nres and each value at position k
                   14355:                          * we know Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline
                   14356:                          * Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline 
                   14357:                          * and Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
                   14358:       /* */
                   14359:       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  14360:        continue;
1.321     brouard  14361:       printf("\n# model %s \n#****** Result for:", model);
                   14362:       fprintf(ficrest,"\n# model %s \n#****** Result for:", model);
                   14363:       fprintf(ficlog,"\n# model %s \n#****** Result for:", model);
1.334     brouard  14364:       /* It might not be a good idea to mix dummies and quantitative */
                   14365:       /* 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 *\/ */
                   14366:       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 */
                   14367:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* Output by variables in the resultline *\/ */
                   14368:        /* Tvaraff[j] is the name of the dummy variable in position j in the equation model:
                   14369:         * Tvaraff[1]@9={4, 3, 0, 0, 0, 0, 0, 0, 0}, in model=V5+V4+V3+V4*V3+V5*age
                   14370:         * (V5 is quanti) V4 and V3 are dummies
                   14371:         * TnsdVar[4] is the position 1 and TnsdVar[3]=2 in codtabm(k,l)(V4  V3)=V4  V3
                   14372:         *                                                              l=1 l=2
                   14373:         *                                                           k=1  1   1   0   0
                   14374:         *                                                           k=2  2   1   1   0
                   14375:         *                                                           k=3 [1] [2]  0   1
                   14376:         *                                                           k=4  2   2   1   1
                   14377:         * If nres=1 result: V3=1 V4=0 then k=3 and outputs
                   14378:         * If nres=2 result: V4=1 V3=0 then k=2 and outputs
                   14379:         * nres=1 =>k=3 j=1 V4= nbcode[4][codtabm(3,1)=1)=0; j=2  V3= nbcode[3][codtabm(3,2)=2]=1
                   14380:         * nres=2 =>k=2 j=1 V4= nbcode[4][codtabm(2,1)=2)=1; j=2  V3= nbcode[3][codtabm(2,2)=1]=0
                   14381:         */
                   14382:        /* Tvresult[nres][j] Name of the variable at position j in this resultline */
                   14383:        /* Tresult[nres][j] Value of this variable at position j could be a float if quantitative  */
                   14384: /* We give up with the combinations!! */
1.342     brouard  14385:        /* if(debugILK) */
                   14386:        /*   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  14387: 
                   14388:        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  14389:          /* 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] */
                   14390:          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  */
                   14391:          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  */
                   14392:          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  14393:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   14394:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   14395:          }else{
                   14396:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   14397:          }
                   14398:          /* fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14399:          /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14400:        }else if(Dummy[modelresult[nres][j]]==1){ /* Quanti variable */
                   14401:          /* For each selected (single) quantitative value */
1.337     brouard  14402:          printf(" V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   14403:          fprintf(ficlog," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   14404:          fprintf(ficrest," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
1.334     brouard  14405:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   14406:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   14407:          }else{
                   14408:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   14409:          }
                   14410:        }else{
                   14411:          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 */
                   14412:          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 */
                   14413:          exit(1);
                   14414:        }
1.335     brouard  14415:       } /* End loop for each variable in the resultline */
1.334     brouard  14416:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   14417:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /\* Wrong j is not in the equation model *\/ */
                   14418:       /*       fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14419:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14420:       /* }      */
1.208     brouard  14421:       fprintf(ficrest,"******\n");
1.227     brouard  14422:       fprintf(ficlog,"******\n");
                   14423:       printf("******\n");
1.208     brouard  14424:       
                   14425:       fprintf(ficresstdeij,"\n#****** ");
                   14426:       fprintf(ficrescveij,"\n#****** ");
1.337     brouard  14427:       /* It could have been: for(j=1;j<=cptcoveff;j++) {printf("V=%d=%lg",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);} */
                   14428:       /* But it won't be sorted and depends on how the resultline is ordered */
1.225     brouard  14429:       for(j=1;j<=cptcoveff;j++) {
1.334     brouard  14430:        fprintf(ficresstdeij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   14431:        /* fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14432:        /* fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14433:       }
                   14434:       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  14435:        fprintf(ficresstdeij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
                   14436:        fprintf(ficrescveij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
1.235     brouard  14437:       }        
1.208     brouard  14438:       fprintf(ficresstdeij,"******\n");
                   14439:       fprintf(ficrescveij,"******\n");
                   14440:       
                   14441:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  14442:       /* pstamp(ficresvij); */
1.225     brouard  14443:       for(j=1;j<=cptcoveff;j++) 
1.335     brouard  14444:        fprintf(ficresvij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   14445:        /* fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[TnsdVar[Tvaraff[j]]])]); */
1.235     brouard  14446:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  14447:        /* fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]); /\* To solve *\/ */
1.337     brouard  14448:        fprintf(ficresvij," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /* Solved */
1.235     brouard  14449:       }        
1.208     brouard  14450:       fprintf(ficresvij,"******\n");
                   14451:       
                   14452:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   14453:       oldm=oldms;savm=savms;
1.235     brouard  14454:       printf(" cvevsij ");
                   14455:       fprintf(ficlog, " cvevsij ");
                   14456:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  14457:       printf(" end cvevsij \n ");
                   14458:       fprintf(ficlog, " end cvevsij \n ");
                   14459:       
                   14460:       /*
                   14461:        */
                   14462:       /* goto endfree; */
                   14463:       
                   14464:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   14465:       pstamp(ficrest);
                   14466:       
1.269     brouard  14467:       epj=vector(1,nlstate+1);
1.208     brouard  14468:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  14469:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   14470:        cptcod= 0; /* To be deleted */
                   14471:        printf("varevsij vpopbased=%d \n",vpopbased);
                   14472:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  14473:        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  14474:        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 ");
                   14475:        if(vpopbased==1)
                   14476:          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);
                   14477:        else
1.288     brouard  14478:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
1.335     brouard  14479:        fprintf(ficrest,"# Age popbased mobilav e.. (std) "); /* Adding covariate values? */
1.227     brouard  14480:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   14481:        fprintf(ficrest,"\n");
                   14482:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  14483:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   14484:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  14485:        for(age=bage; age <=fage ;age++){
1.235     brouard  14486:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  14487:          if (vpopbased==1) {
                   14488:            if(mobilav ==0){
                   14489:              for(i=1; i<=nlstate;i++)
                   14490:                prlim[i][i]=probs[(int)age][i][k];
                   14491:            }else{ /* mobilav */ 
                   14492:              for(i=1; i<=nlstate;i++)
                   14493:                prlim[i][i]=mobaverage[(int)age][i][k];
                   14494:            }
                   14495:          }
1.219     brouard  14496:          
1.227     brouard  14497:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   14498:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   14499:          /* printf(" age %4.0f ",age); */
                   14500:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   14501:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   14502:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   14503:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   14504:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   14505:            }
                   14506:            epj[nlstate+1] +=epj[j];
                   14507:          }
                   14508:          /* printf(" age %4.0f \n",age); */
1.219     brouard  14509:          
1.227     brouard  14510:          for(i=1, vepp=0.;i <=nlstate;i++)
                   14511:            for(j=1;j <=nlstate;j++)
                   14512:              vepp += vareij[i][j][(int)age];
                   14513:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   14514:          for(j=1;j <=nlstate;j++){
                   14515:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   14516:          }
                   14517:          fprintf(ficrest,"\n");
                   14518:        }
1.208     brouard  14519:       } /* End vpopbased */
1.269     brouard  14520:       free_vector(epj,1,nlstate+1);
1.208     brouard  14521:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   14522:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  14523:       printf("done selection\n");fflush(stdout);
                   14524:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  14525:       
1.335     brouard  14526:     } /* End k selection or end covariate selection for nres */
1.227     brouard  14527: 
                   14528:     printf("done State-specific expectancies\n");fflush(stdout);
                   14529:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   14530: 
1.335     brouard  14531:     /* variance-covariance of forward period prevalence */
1.269     brouard  14532:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  14533: 
1.227     brouard  14534:     
1.290     brouard  14535:     free_vector(weight,firstobs,lastobs);
1.330     brouard  14536:     free_imatrix(Tvardk,1,NCOVMAX,1,2);
1.227     brouard  14537:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  14538:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   14539:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   14540:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   14541:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  14542:     free_ivector(tab,1,NCOVMAX);
                   14543:     fclose(ficresstdeij);
                   14544:     fclose(ficrescveij);
                   14545:     fclose(ficresvij);
                   14546:     fclose(ficrest);
                   14547:     fclose(ficpar);
                   14548:     
                   14549:     
1.126     brouard  14550:     /*---------- End : free ----------------*/
1.219     brouard  14551:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  14552:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   14553:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  14554:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   14555:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  14556:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  14557:   /* endfree:*/
                   14558:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   14559:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   14560:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.341     brouard  14561:   /* if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs); */
                   14562:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);
1.290     brouard  14563:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   14564:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   14565:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  14566:   free_matrix(matcov,1,npar,1,npar);
                   14567:   free_matrix(hess,1,npar,1,npar);
                   14568:   /*free_vector(delti,1,npar);*/
                   14569:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   14570:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  14571:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  14572:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   14573:   
                   14574:   free_ivector(ncodemax,1,NCOVMAX);
                   14575:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   14576:   free_ivector(Dummy,-1,NCOVMAX);
                   14577:   free_ivector(Fixed,-1,NCOVMAX);
1.238     brouard  14578:   free_ivector(DummyV,1,NCOVMAX);
                   14579:   free_ivector(FixedV,1,NCOVMAX);
1.227     brouard  14580:   free_ivector(Typevar,-1,NCOVMAX);
                   14581:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  14582:   free_ivector(TvarsQ,1,NCOVMAX);
                   14583:   free_ivector(TvarsQind,1,NCOVMAX);
                   14584:   free_ivector(TvarsD,1,NCOVMAX);
1.330     brouard  14585:   free_ivector(TnsdVar,1,NCOVMAX);
1.234     brouard  14586:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  14587:   free_ivector(TvarFD,1,NCOVMAX);
                   14588:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  14589:   free_ivector(TvarF,1,NCOVMAX);
                   14590:   free_ivector(TvarFind,1,NCOVMAX);
                   14591:   free_ivector(TvarV,1,NCOVMAX);
                   14592:   free_ivector(TvarVind,1,NCOVMAX);
                   14593:   free_ivector(TvarA,1,NCOVMAX);
                   14594:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  14595:   free_ivector(TvarFQ,1,NCOVMAX);
                   14596:   free_ivector(TvarFQind,1,NCOVMAX);
                   14597:   free_ivector(TvarVD,1,NCOVMAX);
                   14598:   free_ivector(TvarVDind,1,NCOVMAX);
                   14599:   free_ivector(TvarVQ,1,NCOVMAX);
                   14600:   free_ivector(TvarVQind,1,NCOVMAX);
1.339     brouard  14601:   free_ivector(TvarVV,1,NCOVMAX);
                   14602:   free_ivector(TvarVVind,1,NCOVMAX);
                   14603:   
1.230     brouard  14604:   free_ivector(Tvarsel,1,NCOVMAX);
                   14605:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  14606:   free_ivector(Tposprod,1,NCOVMAX);
                   14607:   free_ivector(Tprod,1,NCOVMAX);
                   14608:   free_ivector(Tvaraff,1,NCOVMAX);
1.338     brouard  14609:   free_ivector(invalidvarcomb,0,ncovcombmax);
1.227     brouard  14610:   free_ivector(Tage,1,NCOVMAX);
                   14611:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  14612:   free_ivector(TmodelInvind,1,NCOVMAX);
                   14613:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.332     brouard  14614: 
                   14615:   free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /* Could be elsewhere ?*/
                   14616: 
1.227     brouard  14617:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   14618:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  14619:   fflush(fichtm);
                   14620:   fflush(ficgp);
                   14621:   
1.227     brouard  14622:   
1.126     brouard  14623:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  14624:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   14625:     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  14626:   }else{
                   14627:     printf("End of Imach\n");
                   14628:     fprintf(ficlog,"End of Imach\n");
                   14629:   }
                   14630:   printf("See log file on %s\n",filelog);
                   14631:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  14632:   /*(void) gettimeofday(&end_time,&tzp);*/
                   14633:   rend_time = time(NULL);  
                   14634:   end_time = *localtime(&rend_time);
                   14635:   /* tml = *localtime(&end_time.tm_sec); */
                   14636:   strcpy(strtend,asctime(&end_time));
1.126     brouard  14637:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   14638:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  14639:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  14640:   
1.157     brouard  14641:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   14642:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   14643:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  14644:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   14645: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   14646:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   14647:   fclose(fichtm);
                   14648:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   14649:   fclose(fichtmcov);
                   14650:   fclose(ficgp);
                   14651:   fclose(ficlog);
                   14652:   /*------ End -----------*/
1.227     brouard  14653:   
1.281     brouard  14654: 
                   14655: /* Executes gnuplot */
1.227     brouard  14656:   
                   14657:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  14658: #ifdef WIN32
1.227     brouard  14659:   if (_chdir(pathcd) != 0)
                   14660:     printf("Can't move to directory %s!\n",path);
                   14661:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  14662: #else
1.227     brouard  14663:     if(chdir(pathcd) != 0)
                   14664:       printf("Can't move to directory %s!\n", path);
                   14665:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  14666: #endif 
1.126     brouard  14667:     printf("Current directory %s!\n",pathcd);
                   14668:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   14669:   sprintf(plotcmd,"gnuplot");
1.157     brouard  14670: #ifdef _WIN32
1.126     brouard  14671:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   14672: #endif
                   14673:   if(!stat(plotcmd,&info)){
1.158     brouard  14674:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  14675:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  14676:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  14677:     }else
                   14678:       strcpy(pplotcmd,plotcmd);
1.157     brouard  14679: #ifdef __unix
1.126     brouard  14680:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   14681:     if(!stat(plotcmd,&info)){
1.158     brouard  14682:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  14683:     }else
                   14684:       strcpy(pplotcmd,plotcmd);
                   14685: #endif
                   14686:   }else
                   14687:     strcpy(pplotcmd,plotcmd);
                   14688:   
                   14689:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  14690:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  14691:   strcpy(pplotcmd,plotcmd);
1.227     brouard  14692:   
1.126     brouard  14693:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  14694:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  14695:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  14696:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  14697:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  14698:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  14699:       strcpy(plotcmd,pplotcmd);
                   14700:     }
1.126     brouard  14701:   }
1.158     brouard  14702:   printf(" Successful, please wait...");
1.126     brouard  14703:   while (z[0] != 'q') {
                   14704:     /* chdir(path); */
1.154     brouard  14705:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  14706:     scanf("%s",z);
                   14707: /*     if (z[0] == 'c') system("./imach"); */
                   14708:     if (z[0] == 'e') {
1.158     brouard  14709: #ifdef __APPLE__
1.152     brouard  14710:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  14711: #elif __linux
                   14712:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  14713: #else
1.152     brouard  14714:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  14715: #endif
                   14716:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   14717:       system(pplotcmd);
1.126     brouard  14718:     }
                   14719:     else if (z[0] == 'g') system(plotcmd);
                   14720:     else if (z[0] == 'q') exit(0);
                   14721:   }
1.227     brouard  14722: end:
1.126     brouard  14723:   while (z[0] != 'q') {
1.195     brouard  14724:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  14725:     scanf("%s",z);
                   14726:   }
1.283     brouard  14727:   printf("End\n");
1.282     brouard  14728:   exit(0);
1.126     brouard  14729: }

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