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

1.357   ! brouard     1: /* $Id: imach.c,v 1.356 2023/05/23 12:08:43 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.357   ! brouard     4:   Revision 1.356  2023/05/23 12:08:43  brouard
        !             5:   Summary: 0.99r46
        !             6: 
        !             7:   * imach.c (Module): Fixed PROB_r
        !             8: 
1.356     brouard     9:   Revision 1.355  2023/05/22 17:03:18  brouard
                     10:   Summary: 0.99r46
                     11: 
                     12:   * imach.c (Module): In the ILK....txt file, the number of columns
                     13:   before the covariates values is dependent of the number of states (16+nlstate): 0.99r46
                     14: 
1.355     brouard    15:   Revision 1.354  2023/05/21 05:05:17  brouard
                     16:   Summary: Temporary change for imachprax
                     17: 
1.354     brouard    18:   Revision 1.353  2023/05/08 18:48:22  brouard
                     19:   *** empty log message ***
                     20: 
1.353     brouard    21:   Revision 1.352  2023/04/29 10:46:21  brouard
                     22:   *** empty log message ***
                     23: 
1.352     brouard    24:   Revision 1.351  2023/04/29 10:43:47  brouard
                     25:   Summary: 099r45
                     26: 
1.351     brouard    27:   Revision 1.350  2023/04/24 11:38:06  brouard
                     28:   *** empty log message ***
                     29: 
1.350     brouard    30:   Revision 1.349  2023/01/31 09:19:37  brouard
                     31:   Summary: Improvements in models with age*Vn*Vm
                     32: 
1.348     brouard    33:   Revision 1.347  2022/09/18 14:36:44  brouard
                     34:   Summary: version 0.99r42
                     35: 
1.347     brouard    36:   Revision 1.346  2022/09/16 13:52:36  brouard
                     37:   * src/imach.c (Module): 0.99r41 Was an error when product of timevarying and fixed. Using FixedV[of name] now. Thank you  Feinuo
                     38: 
1.346     brouard    39:   Revision 1.345  2022/09/16 13:40:11  brouard
                     40:   Summary: Version 0.99r41
                     41: 
                     42:   * imach.c (Module): 0.99r41 Was an error when product of timevarying and fixed. Using FixedV[of name] now. Thank you  Feinuo
                     43: 
1.345     brouard    44:   Revision 1.344  2022/09/14 19:33:30  brouard
                     45:   Summary: version 0.99r40
                     46: 
                     47:   * imach.c (Module): Fixing names of variables in T_ (thanks to Feinuo)
                     48: 
1.344     brouard    49:   Revision 1.343  2022/09/14 14:22:16  brouard
                     50:   Summary: version 0.99r39
                     51: 
                     52:   * imach.c (Module): Version 0.99r39 with colored dummy covariates
                     53:   (fixed or time varying), using new last columns of
                     54:   ILK_parameter.txt file.
                     55: 
1.343     brouard    56:   Revision 1.342  2022/09/11 19:54:09  brouard
                     57:   Summary: 0.99r38
                     58: 
                     59:   * imach.c (Module): Adding timevarying products of any kinds,
                     60:   should work before shifting cotvar from ncovcol+nqv columns in
                     61:   order to have a correspondance between the column of cotvar and
                     62:   the id of column.
                     63:   (Module): Some cleaning and adding covariates in ILK.txt
                     64: 
1.342     brouard    65:   Revision 1.341  2022/09/11 07:58:42  brouard
                     66:   Summary: Version 0.99r38
                     67: 
                     68:   After adding change in cotvar.
                     69: 
1.341     brouard    70:   Revision 1.340  2022/09/11 07:53:11  brouard
                     71:   Summary: Version imach 0.99r37
                     72: 
                     73:   * imach.c (Module): Adding timevarying products of any kinds,
                     74:   should work before shifting cotvar from ncovcol+nqv columns in
                     75:   order to have a correspondance between the column of cotvar and
                     76:   the id of column.
                     77: 
1.340     brouard    78:   Revision 1.339  2022/09/09 17:55:22  brouard
                     79:   Summary: version 0.99r37
                     80: 
                     81:   * imach.c (Module): Many improvements for fixing products of fixed
                     82:   timevarying as well as fixed * fixed, and test with quantitative
                     83:   covariate.
                     84: 
1.339     brouard    85:   Revision 1.338  2022/09/04 17:40:33  brouard
                     86:   Summary: 0.99r36
                     87: 
                     88:   * imach.c (Module): Now the easy runs i.e. without result or
                     89:   model=1+age only did not work. The defautl combination should be 1
                     90:   and not 0 because everything hasn't been tranformed yet.
                     91: 
1.338     brouard    92:   Revision 1.337  2022/09/02 14:26:02  brouard
                     93:   Summary: version 0.99r35
                     94: 
                     95:   * src/imach.c: Version 0.99r35 because it outputs same results with
                     96:   1+age+V1+V1*age for females and 1+age for females only
                     97:   (education=1 noweight)
                     98: 
1.337     brouard    99:   Revision 1.336  2022/08/31 09:52:36  brouard
                    100:   *** empty log message ***
                    101: 
1.336     brouard   102:   Revision 1.335  2022/08/31 08:23:16  brouard
                    103:   Summary: improvements...
                    104: 
1.335     brouard   105:   Revision 1.334  2022/08/25 09:08:41  brouard
                    106:   Summary: In progress for quantitative
                    107: 
1.334     brouard   108:   Revision 1.333  2022/08/21 09:10:30  brouard
                    109:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                    110:   reassigning covariates: my first idea was that people will always
                    111:   use the first covariate V1 into the model but in fact they are
                    112:   producing data with many covariates and can use an equation model
                    113:   with some of the covariate; it means that in a model V2+V3 instead
                    114:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                    115:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                    116:   the equation model is restricted to two variables only (V2, V3)
                    117:   and the combination for V2 should be codtabm(k,1) instead of
                    118:   (codtabm(k,2), and the code should be
                    119:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                    120:   made. All of these should be simplified once a day like we did in
                    121:   hpxij() for example by using precov[nres] which is computed in
                    122:   decoderesult for each nres of each resultline. Loop should be done
                    123:   on the equation model globally by distinguishing only product with
                    124:   age (which are changing with age) and no more on type of
                    125:   covariates, single dummies, single covariates.
                    126: 
1.333     brouard   127:   Revision 1.332  2022/08/21 09:06:25  brouard
                    128:   Summary: Version 0.99r33
                    129: 
                    130:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                    131:   reassigning covariates: my first idea was that people will always
                    132:   use the first covariate V1 into the model but in fact they are
                    133:   producing data with many covariates and can use an equation model
                    134:   with some of the covariate; it means that in a model V2+V3 instead
                    135:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                    136:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                    137:   the equation model is restricted to two variables only (V2, V3)
                    138:   and the combination for V2 should be codtabm(k,1) instead of
                    139:   (codtabm(k,2), and the code should be
                    140:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                    141:   made. All of these should be simplified once a day like we did in
                    142:   hpxij() for example by using precov[nres] which is computed in
                    143:   decoderesult for each nres of each resultline. Loop should be done
                    144:   on the equation model globally by distinguishing only product with
                    145:   age (which are changing with age) and no more on type of
                    146:   covariates, single dummies, single covariates.
                    147: 
1.332     brouard   148:   Revision 1.331  2022/08/07 05:40:09  brouard
                    149:   *** empty log message ***
                    150: 
1.331     brouard   151:   Revision 1.330  2022/08/06 07:18:25  brouard
                    152:   Summary: last 0.99r31
                    153: 
                    154:   *  imach.c (Module): Version of imach using partly decoderesult to rebuild xpxij function
                    155: 
1.330     brouard   156:   Revision 1.329  2022/08/03 17:29:54  brouard
                    157:   *  imach.c (Module): Many errors in graphs fixed with Vn*age covariates.
                    158: 
1.329     brouard   159:   Revision 1.328  2022/07/27 17:40:48  brouard
                    160:   Summary: valgrind bug fixed by initializing to zero DummyV as well as Tage
                    161: 
1.328     brouard   162:   Revision 1.327  2022/07/27 14:47:35  brouard
                    163:   Summary: Still a problem for one-step probabilities in case of quantitative variables
                    164: 
1.327     brouard   165:   Revision 1.326  2022/07/26 17:33:55  brouard
                    166:   Summary: some test with nres=1
                    167: 
1.326     brouard   168:   Revision 1.325  2022/07/25 14:27:23  brouard
                    169:   Summary: r30
                    170: 
                    171:   * imach.c (Module): Error cptcovn instead of nsd in bmij (was
                    172:   coredumped, revealed by Feiuno, thank you.
                    173: 
1.325     brouard   174:   Revision 1.324  2022/07/23 17:44:26  brouard
                    175:   *** empty log message ***
                    176: 
1.324     brouard   177:   Revision 1.323  2022/07/22 12:30:08  brouard
                    178:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    179: 
1.323     brouard   180:   Revision 1.322  2022/07/22 12:27:48  brouard
                    181:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    182: 
1.322     brouard   183:   Revision 1.321  2022/07/22 12:04:24  brouard
                    184:   Summary: r28
                    185: 
                    186:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    187: 
1.321     brouard   188:   Revision 1.320  2022/06/02 05:10:11  brouard
                    189:   *** empty log message ***
                    190: 
1.320     brouard   191:   Revision 1.319  2022/06/02 04:45:11  brouard
                    192:   * imach.c (Module): Adding the Wald tests from the log to the main
                    193:   htm for better display of the maximum likelihood estimators.
                    194: 
1.319     brouard   195:   Revision 1.318  2022/05/24 08:10:59  brouard
                    196:   * imach.c (Module): Some attempts to find a bug of wrong estimates
                    197:   of confidencce intervals with product in the equation modelC
                    198: 
1.318     brouard   199:   Revision 1.317  2022/05/15 15:06:23  brouard
                    200:   * imach.c (Module):  Some minor improvements
                    201: 
1.317     brouard   202:   Revision 1.316  2022/05/11 15:11:31  brouard
                    203:   Summary: r27
                    204: 
1.316     brouard   205:   Revision 1.315  2022/05/11 15:06:32  brouard
                    206:   *** empty log message ***
                    207: 
1.315     brouard   208:   Revision 1.314  2022/04/13 17:43:09  brouard
                    209:   * imach.c (Module): Adding link to text data files
                    210: 
1.314     brouard   211:   Revision 1.313  2022/04/11 15:57:42  brouard
                    212:   * imach.c (Module): Error in rewriting the 'r' file with yearsfproj or yearsbproj fixed
                    213: 
1.313     brouard   214:   Revision 1.312  2022/04/05 21:24:39  brouard
                    215:   *** empty log message ***
                    216: 
1.312     brouard   217:   Revision 1.311  2022/04/05 21:03:51  brouard
                    218:   Summary: Fixed quantitative covariates
                    219: 
                    220:          Fixed covariates (dummy or quantitative)
                    221:        with missing values have never been allowed but are ERRORS and
                    222:        program quits. Standard deviations of fixed covariates were
                    223:        wrongly computed. Mean and standard deviations of time varying
                    224:        covariates are still not computed.
                    225: 
1.311     brouard   226:   Revision 1.310  2022/03/17 08:45:53  brouard
                    227:   Summary: 99r25
                    228: 
                    229:   Improving detection of errors: result lines should be compatible with
                    230:   the model.
                    231: 
1.310     brouard   232:   Revision 1.309  2021/05/20 12:39:14  brouard
                    233:   Summary: Version 0.99r24
                    234: 
1.309     brouard   235:   Revision 1.308  2021/03/31 13:11:57  brouard
                    236:   Summary: Version 0.99r23
                    237: 
                    238: 
                    239:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
                    240: 
1.308     brouard   241:   Revision 1.307  2021/03/08 18:11:32  brouard
                    242:   Summary: 0.99r22 fixed bug on result:
                    243: 
1.307     brouard   244:   Revision 1.306  2021/02/20 15:44:02  brouard
                    245:   Summary: Version 0.99r21
                    246: 
                    247:   * imach.c (Module): Fix bug on quitting after result lines!
                    248:   (Module): Version 0.99r21
                    249: 
1.306     brouard   250:   Revision 1.305  2021/02/20 15:28:30  brouard
                    251:   * imach.c (Module): Fix bug on quitting after result lines!
                    252: 
1.305     brouard   253:   Revision 1.304  2021/02/12 11:34:20  brouard
                    254:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
                    255: 
1.304     brouard   256:   Revision 1.303  2021/02/11 19:50:15  brouard
                    257:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
                    258: 
1.303     brouard   259:   Revision 1.302  2020/02/22 21:00:05  brouard
                    260:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
                    261:   and life table from the data without any state)
                    262: 
1.302     brouard   263:   Revision 1.301  2019/06/04 13:51:20  brouard
                    264:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                    265: 
1.301     brouard   266:   Revision 1.300  2019/05/22 19:09:45  brouard
                    267:   Summary: version 0.99r19 of May 2019
                    268: 
1.300     brouard   269:   Revision 1.299  2019/05/22 18:37:08  brouard
                    270:   Summary: Cleaned 0.99r19
                    271: 
1.299     brouard   272:   Revision 1.298  2019/05/22 18:19:56  brouard
                    273:   *** empty log message ***
                    274: 
1.298     brouard   275:   Revision 1.297  2019/05/22 17:56:10  brouard
                    276:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                    277: 
1.297     brouard   278:   Revision 1.296  2019/05/20 13:03:18  brouard
                    279:   Summary: Projection syntax simplified
                    280: 
                    281: 
                    282:   We can now start projections, forward or backward, from the mean date
                    283:   of inteviews up to or down to a number of years of projection:
                    284:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                    285:   or
                    286:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                    287:   or
                    288:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                    289:   or
                    290:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                    291: 
1.296     brouard   292:   Revision 1.295  2019/05/18 09:52:50  brouard
                    293:   Summary: doxygen tex bug
                    294: 
1.295     brouard   295:   Revision 1.294  2019/05/16 14:54:33  brouard
                    296:   Summary: There was some wrong lines added
                    297: 
1.294     brouard   298:   Revision 1.293  2019/05/09 15:17:34  brouard
                    299:   *** empty log message ***
                    300: 
1.293     brouard   301:   Revision 1.292  2019/05/09 14:17:20  brouard
                    302:   Summary: Some updates
                    303: 
1.292     brouard   304:   Revision 1.291  2019/05/09 13:44:18  brouard
                    305:   Summary: Before ncovmax
                    306: 
1.291     brouard   307:   Revision 1.290  2019/05/09 13:39:37  brouard
                    308:   Summary: 0.99r18 unlimited number of individuals
                    309: 
                    310:   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.
                    311: 
1.290     brouard   312:   Revision 1.289  2018/12/13 09:16:26  brouard
                    313:   Summary: Bug for young ages (<-30) will be in r17
                    314: 
1.289     brouard   315:   Revision 1.288  2018/05/02 20:58:27  brouard
                    316:   Summary: Some bugs fixed
                    317: 
1.288     brouard   318:   Revision 1.287  2018/05/01 17:57:25  brouard
                    319:   Summary: Bug fixed by providing frequencies only for non missing covariates
                    320: 
1.287     brouard   321:   Revision 1.286  2018/04/27 14:27:04  brouard
                    322:   Summary: some minor bugs
                    323: 
1.286     brouard   324:   Revision 1.285  2018/04/21 21:02:16  brouard
                    325:   Summary: Some bugs fixed, valgrind tested
                    326: 
1.285     brouard   327:   Revision 1.284  2018/04/20 05:22:13  brouard
                    328:   Summary: Computing mean and stdeviation of fixed quantitative variables
                    329: 
1.284     brouard   330:   Revision 1.283  2018/04/19 14:49:16  brouard
                    331:   Summary: Some minor bugs fixed
                    332: 
1.283     brouard   333:   Revision 1.282  2018/02/27 22:50:02  brouard
                    334:   *** empty log message ***
                    335: 
1.282     brouard   336:   Revision 1.281  2018/02/27 19:25:23  brouard
                    337:   Summary: Adding second argument for quitting
                    338: 
1.281     brouard   339:   Revision 1.280  2018/02/21 07:58:13  brouard
                    340:   Summary: 0.99r15
                    341: 
                    342:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                    343: 
1.280     brouard   344:   Revision 1.279  2017/07/20 13:35:01  brouard
                    345:   Summary: temporary working
                    346: 
1.279     brouard   347:   Revision 1.278  2017/07/19 14:09:02  brouard
                    348:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                    349: 
1.278     brouard   350:   Revision 1.277  2017/07/17 08:53:49  brouard
                    351:   Summary: BOM files can be read now
                    352: 
1.277     brouard   353:   Revision 1.276  2017/06/30 15:48:31  brouard
                    354:   Summary: Graphs improvements
                    355: 
1.276     brouard   356:   Revision 1.275  2017/06/30 13:39:33  brouard
                    357:   Summary: Saito's color
                    358: 
1.275     brouard   359:   Revision 1.274  2017/06/29 09:47:08  brouard
                    360:   Summary: Version 0.99r14
                    361: 
1.274     brouard   362:   Revision 1.273  2017/06/27 11:06:02  brouard
                    363:   Summary: More documentation on projections
                    364: 
1.273     brouard   365:   Revision 1.272  2017/06/27 10:22:40  brouard
                    366:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    367: 
1.272     brouard   368:   Revision 1.271  2017/06/27 10:17:50  brouard
                    369:   Summary: Some bug with rint
                    370: 
1.271     brouard   371:   Revision 1.270  2017/05/24 05:45:29  brouard
                    372:   *** empty log message ***
                    373: 
1.270     brouard   374:   Revision 1.269  2017/05/23 08:39:25  brouard
                    375:   Summary: Code into subroutine, cleanings
                    376: 
1.269     brouard   377:   Revision 1.268  2017/05/18 20:09:32  brouard
                    378:   Summary: backprojection and confidence intervals of backprevalence
                    379: 
1.268     brouard   380:   Revision 1.267  2017/05/13 10:25:05  brouard
                    381:   Summary: temporary save for backprojection
                    382: 
1.267     brouard   383:   Revision 1.266  2017/05/13 07:26:12  brouard
                    384:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    385: 
1.266     brouard   386:   Revision 1.265  2017/04/26 16:22:11  brouard
                    387:   Summary: imach 0.99r13 Some bugs fixed
                    388: 
1.265     brouard   389:   Revision 1.264  2017/04/26 06:01:29  brouard
                    390:   Summary: Labels in graphs
                    391: 
1.264     brouard   392:   Revision 1.263  2017/04/24 15:23:15  brouard
                    393:   Summary: to save
                    394: 
1.263     brouard   395:   Revision 1.262  2017/04/18 16:48:12  brouard
                    396:   *** empty log message ***
                    397: 
1.262     brouard   398:   Revision 1.261  2017/04/05 10:14:09  brouard
                    399:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    400: 
1.261     brouard   401:   Revision 1.260  2017/04/04 17:46:59  brouard
                    402:   Summary: Gnuplot indexations fixed (humm)
                    403: 
1.260     brouard   404:   Revision 1.259  2017/04/04 13:01:16  brouard
                    405:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    406: 
1.259     brouard   407:   Revision 1.258  2017/04/03 10:17:47  brouard
                    408:   Summary: Version 0.99r12
                    409: 
                    410:   Some cleanings, conformed with updated documentation.
                    411: 
1.258     brouard   412:   Revision 1.257  2017/03/29 16:53:30  brouard
                    413:   Summary: Temp
                    414: 
1.257     brouard   415:   Revision 1.256  2017/03/27 05:50:23  brouard
                    416:   Summary: Temporary
                    417: 
1.256     brouard   418:   Revision 1.255  2017/03/08 16:02:28  brouard
                    419:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    420: 
1.255     brouard   421:   Revision 1.254  2017/03/08 07:13:00  brouard
                    422:   Summary: Fixing data parameter line
                    423: 
1.254     brouard   424:   Revision 1.253  2016/12/15 11:59:41  brouard
                    425:   Summary: 0.99 in progress
                    426: 
1.253     brouard   427:   Revision 1.252  2016/09/15 21:15:37  brouard
                    428:   *** empty log message ***
                    429: 
1.252     brouard   430:   Revision 1.251  2016/09/15 15:01:13  brouard
                    431:   Summary: not working
                    432: 
1.251     brouard   433:   Revision 1.250  2016/09/08 16:07:27  brouard
                    434:   Summary: continue
                    435: 
1.250     brouard   436:   Revision 1.249  2016/09/07 17:14:18  brouard
                    437:   Summary: Starting values from frequencies
                    438: 
1.249     brouard   439:   Revision 1.248  2016/09/07 14:10:18  brouard
                    440:   *** empty log message ***
                    441: 
1.248     brouard   442:   Revision 1.247  2016/09/02 11:11:21  brouard
                    443:   *** empty log message ***
                    444: 
1.247     brouard   445:   Revision 1.246  2016/09/02 08:49:22  brouard
                    446:   *** empty log message ***
                    447: 
1.246     brouard   448:   Revision 1.245  2016/09/02 07:25:01  brouard
                    449:   *** empty log message ***
                    450: 
1.245     brouard   451:   Revision 1.244  2016/09/02 07:17:34  brouard
                    452:   *** empty log message ***
                    453: 
1.244     brouard   454:   Revision 1.243  2016/09/02 06:45:35  brouard
                    455:   *** empty log message ***
                    456: 
1.243     brouard   457:   Revision 1.242  2016/08/30 15:01:20  brouard
                    458:   Summary: Fixing a lots
                    459: 
1.242     brouard   460:   Revision 1.241  2016/08/29 17:17:25  brouard
                    461:   Summary: gnuplot problem in Back projection to fix
                    462: 
1.241     brouard   463:   Revision 1.240  2016/08/29 07:53:18  brouard
                    464:   Summary: Better
                    465: 
1.240     brouard   466:   Revision 1.239  2016/08/26 15:51:03  brouard
                    467:   Summary: Improvement in Powell output in order to copy and paste
                    468: 
                    469:   Author:
                    470: 
1.239     brouard   471:   Revision 1.238  2016/08/26 14:23:35  brouard
                    472:   Summary: Starting tests of 0.99
                    473: 
1.238     brouard   474:   Revision 1.237  2016/08/26 09:20:19  brouard
                    475:   Summary: to valgrind
                    476: 
1.237     brouard   477:   Revision 1.236  2016/08/25 10:50:18  brouard
                    478:   *** empty log message ***
                    479: 
1.236     brouard   480:   Revision 1.235  2016/08/25 06:59:23  brouard
                    481:   *** empty log message ***
                    482: 
1.235     brouard   483:   Revision 1.234  2016/08/23 16:51:20  brouard
                    484:   *** empty log message ***
                    485: 
1.234     brouard   486:   Revision 1.233  2016/08/23 07:40:50  brouard
                    487:   Summary: not working
                    488: 
1.233     brouard   489:   Revision 1.232  2016/08/22 14:20:21  brouard
                    490:   Summary: not working
                    491: 
1.232     brouard   492:   Revision 1.231  2016/08/22 07:17:15  brouard
                    493:   Summary: not working
                    494: 
1.231     brouard   495:   Revision 1.230  2016/08/22 06:55:53  brouard
                    496:   Summary: Not working
                    497: 
1.230     brouard   498:   Revision 1.229  2016/07/23 09:45:53  brouard
                    499:   Summary: Completing for func too
                    500: 
1.229     brouard   501:   Revision 1.228  2016/07/22 17:45:30  brouard
                    502:   Summary: Fixing some arrays, still debugging
                    503: 
1.227     brouard   504:   Revision 1.226  2016/07/12 18:42:34  brouard
                    505:   Summary: temp
                    506: 
1.226     brouard   507:   Revision 1.225  2016/07/12 08:40:03  brouard
                    508:   Summary: saving but not running
                    509: 
1.225     brouard   510:   Revision 1.224  2016/07/01 13:16:01  brouard
                    511:   Summary: Fixes
                    512: 
1.224     brouard   513:   Revision 1.223  2016/02/19 09:23:35  brouard
                    514:   Summary: temporary
                    515: 
1.223     brouard   516:   Revision 1.222  2016/02/17 08:14:50  brouard
                    517:   Summary: Probably last 0.98 stable version 0.98r6
                    518: 
1.222     brouard   519:   Revision 1.221  2016/02/15 23:35:36  brouard
                    520:   Summary: minor bug
                    521: 
1.220     brouard   522:   Revision 1.219  2016/02/15 00:48:12  brouard
                    523:   *** empty log message ***
                    524: 
1.219     brouard   525:   Revision 1.218  2016/02/12 11:29:23  brouard
                    526:   Summary: 0.99 Back projections
                    527: 
1.218     brouard   528:   Revision 1.217  2015/12/23 17:18:31  brouard
                    529:   Summary: Experimental backcast
                    530: 
1.217     brouard   531:   Revision 1.216  2015/12/18 17:32:11  brouard
                    532:   Summary: 0.98r4 Warning and status=-2
                    533: 
                    534:   Version 0.98r4 is now:
                    535:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    536:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    537:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    538: 
1.216     brouard   539:   Revision 1.215  2015/12/16 08:52:24  brouard
                    540:   Summary: 0.98r4 working
                    541: 
1.215     brouard   542:   Revision 1.214  2015/12/16 06:57:54  brouard
                    543:   Summary: temporary not working
                    544: 
1.214     brouard   545:   Revision 1.213  2015/12/11 18:22:17  brouard
                    546:   Summary: 0.98r4
                    547: 
1.213     brouard   548:   Revision 1.212  2015/11/21 12:47:24  brouard
                    549:   Summary: minor typo
                    550: 
1.212     brouard   551:   Revision 1.211  2015/11/21 12:41:11  brouard
                    552:   Summary: 0.98r3 with some graph of projected cross-sectional
                    553: 
                    554:   Author: Nicolas Brouard
                    555: 
1.211     brouard   556:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   557:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   558:   Summary: Adding ftolpl parameter
                    559:   Author: N Brouard
                    560: 
                    561:   We had difficulties to get smoothed confidence intervals. It was due
                    562:   to the period prevalence which wasn't computed accurately. The inner
                    563:   parameter ftolpl is now an outer parameter of the .imach parameter
                    564:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    565:   computation are long.
                    566: 
1.209     brouard   567:   Revision 1.208  2015/11/17 14:31:57  brouard
                    568:   Summary: temporary
                    569: 
1.208     brouard   570:   Revision 1.207  2015/10/27 17:36:57  brouard
                    571:   *** empty log message ***
                    572: 
1.207     brouard   573:   Revision 1.206  2015/10/24 07:14:11  brouard
                    574:   *** empty log message ***
                    575: 
1.206     brouard   576:   Revision 1.205  2015/10/23 15:50:53  brouard
                    577:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    578: 
1.205     brouard   579:   Revision 1.204  2015/10/01 16:20:26  brouard
                    580:   Summary: Some new graphs of contribution to likelihood
                    581: 
1.204     brouard   582:   Revision 1.203  2015/09/30 17:45:14  brouard
                    583:   Summary: looking at better estimation of the hessian
                    584: 
                    585:   Also a better criteria for convergence to the period prevalence And
                    586:   therefore adding the number of years needed to converge. (The
                    587:   prevalence in any alive state shold sum to one
                    588: 
1.203     brouard   589:   Revision 1.202  2015/09/22 19:45:16  brouard
                    590:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    591: 
1.202     brouard   592:   Revision 1.201  2015/09/15 17:34:58  brouard
                    593:   Summary: 0.98r0
                    594: 
                    595:   - Some new graphs like suvival functions
                    596:   - Some bugs fixed like model=1+age+V2.
                    597: 
1.201     brouard   598:   Revision 1.200  2015/09/09 16:53:55  brouard
                    599:   Summary: Big bug thanks to Flavia
                    600: 
                    601:   Even model=1+age+V2. did not work anymore
                    602: 
1.200     brouard   603:   Revision 1.199  2015/09/07 14:09:23  brouard
                    604:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    605: 
1.199     brouard   606:   Revision 1.198  2015/09/03 07:14:39  brouard
                    607:   Summary: 0.98q5 Flavia
                    608: 
1.198     brouard   609:   Revision 1.197  2015/09/01 18:24:39  brouard
                    610:   *** empty log message ***
                    611: 
1.197     brouard   612:   Revision 1.196  2015/08/18 23:17:52  brouard
                    613:   Summary: 0.98q5
                    614: 
1.196     brouard   615:   Revision 1.195  2015/08/18 16:28:39  brouard
                    616:   Summary: Adding a hack for testing purpose
                    617: 
                    618:   After reading the title, ftol and model lines, if the comment line has
                    619:   a q, starting with #q, the answer at the end of the run is quit. It
                    620:   permits to run test files in batch with ctest. The former workaround was
                    621:   $ echo q | imach foo.imach
                    622: 
1.195     brouard   623:   Revision 1.194  2015/08/18 13:32:00  brouard
                    624:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    625: 
1.194     brouard   626:   Revision 1.193  2015/08/04 07:17:42  brouard
                    627:   Summary: 0.98q4
                    628: 
1.193     brouard   629:   Revision 1.192  2015/07/16 16:49:02  brouard
                    630:   Summary: Fixing some outputs
                    631: 
1.192     brouard   632:   Revision 1.191  2015/07/14 10:00:33  brouard
                    633:   Summary: Some fixes
                    634: 
1.191     brouard   635:   Revision 1.190  2015/05/05 08:51:13  brouard
                    636:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    637: 
                    638:   Fix 1+age+.
                    639: 
1.190     brouard   640:   Revision 1.189  2015/04/30 14:45:16  brouard
                    641:   Summary: 0.98q2
                    642: 
1.189     brouard   643:   Revision 1.188  2015/04/30 08:27:53  brouard
                    644:   *** empty log message ***
                    645: 
1.188     brouard   646:   Revision 1.187  2015/04/29 09:11:15  brouard
                    647:   *** empty log message ***
                    648: 
1.187     brouard   649:   Revision 1.186  2015/04/23 12:01:52  brouard
                    650:   Summary: V1*age is working now, version 0.98q1
                    651: 
                    652:   Some codes had been disabled in order to simplify and Vn*age was
                    653:   working in the optimization phase, ie, giving correct MLE parameters,
                    654:   but, as usual, outputs were not correct and program core dumped.
                    655: 
1.186     brouard   656:   Revision 1.185  2015/03/11 13:26:42  brouard
                    657:   Summary: Inclusion of compile and links command line for Intel Compiler
                    658: 
1.185     brouard   659:   Revision 1.184  2015/03/11 11:52:39  brouard
                    660:   Summary: Back from Windows 8. Intel Compiler
                    661: 
1.184     brouard   662:   Revision 1.183  2015/03/10 20:34:32  brouard
                    663:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    664: 
                    665:   We use directest instead of original Powell test; probably no
                    666:   incidence on the results, but better justifications;
                    667:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    668:   wrong results.
                    669: 
1.183     brouard   670:   Revision 1.182  2015/02/12 08:19:57  brouard
                    671:   Summary: Trying to keep directest which seems simpler and more general
                    672:   Author: Nicolas Brouard
                    673: 
1.182     brouard   674:   Revision 1.181  2015/02/11 23:22:24  brouard
                    675:   Summary: Comments on Powell added
                    676: 
                    677:   Author:
                    678: 
1.181     brouard   679:   Revision 1.180  2015/02/11 17:33:45  brouard
                    680:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    681: 
1.180     brouard   682:   Revision 1.179  2015/01/04 09:57:06  brouard
                    683:   Summary: back to OS/X
                    684: 
1.179     brouard   685:   Revision 1.178  2015/01/04 09:35:48  brouard
                    686:   *** empty log message ***
                    687: 
1.178     brouard   688:   Revision 1.177  2015/01/03 18:40:56  brouard
                    689:   Summary: Still testing ilc32 on OSX
                    690: 
1.177     brouard   691:   Revision 1.176  2015/01/03 16:45:04  brouard
                    692:   *** empty log message ***
                    693: 
1.176     brouard   694:   Revision 1.175  2015/01/03 16:33:42  brouard
                    695:   *** empty log message ***
                    696: 
1.175     brouard   697:   Revision 1.174  2015/01/03 16:15:49  brouard
                    698:   Summary: Still in cross-compilation
                    699: 
1.174     brouard   700:   Revision 1.173  2015/01/03 12:06:26  brouard
                    701:   Summary: trying to detect cross-compilation
                    702: 
1.173     brouard   703:   Revision 1.172  2014/12/27 12:07:47  brouard
                    704:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    705: 
1.172     brouard   706:   Revision 1.171  2014/12/23 13:26:59  brouard
                    707:   Summary: Back from Visual C
                    708: 
                    709:   Still problem with utsname.h on Windows
                    710: 
1.171     brouard   711:   Revision 1.170  2014/12/23 11:17:12  brouard
                    712:   Summary: Cleaning some \%% back to %%
                    713: 
                    714:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    715: 
1.170     brouard   716:   Revision 1.169  2014/12/22 23:08:31  brouard
                    717:   Summary: 0.98p
                    718: 
                    719:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    720: 
1.169     brouard   721:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   722:   Summary: update
1.169     brouard   723: 
1.168     brouard   724:   Revision 1.167  2014/12/22 13:50:56  brouard
                    725:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    726: 
                    727:   Testing on Linux 64
                    728: 
1.167     brouard   729:   Revision 1.166  2014/12/22 11:40:47  brouard
                    730:   *** empty log message ***
                    731: 
1.166     brouard   732:   Revision 1.165  2014/12/16 11:20:36  brouard
                    733:   Summary: After compiling on Visual C
                    734: 
                    735:   * imach.c (Module): Merging 1.61 to 1.162
                    736: 
1.165     brouard   737:   Revision 1.164  2014/12/16 10:52:11  brouard
                    738:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    739: 
                    740:   * imach.c (Module): Merging 1.61 to 1.162
                    741: 
1.164     brouard   742:   Revision 1.163  2014/12/16 10:30:11  brouard
                    743:   * imach.c (Module): Merging 1.61 to 1.162
                    744: 
1.163     brouard   745:   Revision 1.162  2014/09/25 11:43:39  brouard
                    746:   Summary: temporary backup 0.99!
                    747: 
1.162     brouard   748:   Revision 1.1  2014/09/16 11:06:58  brouard
                    749:   Summary: With some code (wrong) for nlopt
                    750: 
                    751:   Author:
                    752: 
                    753:   Revision 1.161  2014/09/15 20:41:41  brouard
                    754:   Summary: Problem with macro SQR on Intel compiler
                    755: 
1.161     brouard   756:   Revision 1.160  2014/09/02 09:24:05  brouard
                    757:   *** empty log message ***
                    758: 
1.160     brouard   759:   Revision 1.159  2014/09/01 10:34:10  brouard
                    760:   Summary: WIN32
                    761:   Author: Brouard
                    762: 
1.159     brouard   763:   Revision 1.158  2014/08/27 17:11:51  brouard
                    764:   *** empty log message ***
                    765: 
1.158     brouard   766:   Revision 1.157  2014/08/27 16:26:55  brouard
                    767:   Summary: Preparing windows Visual studio version
                    768:   Author: Brouard
                    769: 
                    770:   In order to compile on Visual studio, time.h is now correct and time_t
                    771:   and tm struct should be used. difftime should be used but sometimes I
                    772:   just make the differences in raw time format (time(&now).
                    773:   Trying to suppress #ifdef LINUX
                    774:   Add xdg-open for __linux in order to open default browser.
                    775: 
1.157     brouard   776:   Revision 1.156  2014/08/25 20:10:10  brouard
                    777:   *** empty log message ***
                    778: 
1.156     brouard   779:   Revision 1.155  2014/08/25 18:32:34  brouard
                    780:   Summary: New compile, minor changes
                    781:   Author: Brouard
                    782: 
1.155     brouard   783:   Revision 1.154  2014/06/20 17:32:08  brouard
                    784:   Summary: Outputs now all graphs of convergence to period prevalence
                    785: 
1.154     brouard   786:   Revision 1.153  2014/06/20 16:45:46  brouard
                    787:   Summary: If 3 live state, convergence to period prevalence on same graph
                    788:   Author: Brouard
                    789: 
1.153     brouard   790:   Revision 1.152  2014/06/18 17:54:09  brouard
                    791:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    792: 
1.152     brouard   793:   Revision 1.151  2014/06/18 16:43:30  brouard
                    794:   *** empty log message ***
                    795: 
1.151     brouard   796:   Revision 1.150  2014/06/18 16:42:35  brouard
                    797:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    798:   Author: brouard
                    799: 
1.150     brouard   800:   Revision 1.149  2014/06/18 15:51:14  brouard
                    801:   Summary: Some fixes in parameter files errors
                    802:   Author: Nicolas Brouard
                    803: 
1.149     brouard   804:   Revision 1.148  2014/06/17 17:38:48  brouard
                    805:   Summary: Nothing new
                    806:   Author: Brouard
                    807: 
                    808:   Just a new packaging for OS/X version 0.98nS
                    809: 
1.148     brouard   810:   Revision 1.147  2014/06/16 10:33:11  brouard
                    811:   *** empty log message ***
                    812: 
1.147     brouard   813:   Revision 1.146  2014/06/16 10:20:28  brouard
                    814:   Summary: Merge
                    815:   Author: Brouard
                    816: 
                    817:   Merge, before building revised version.
                    818: 
1.146     brouard   819:   Revision 1.145  2014/06/10 21:23:15  brouard
                    820:   Summary: Debugging with valgrind
                    821:   Author: Nicolas Brouard
                    822: 
                    823:   Lot of changes in order to output the results with some covariates
                    824:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    825:   improve the code.
                    826:   No more memory valgrind error but a lot has to be done in order to
                    827:   continue the work of splitting the code into subroutines.
                    828:   Also, decodemodel has been improved. Tricode is still not
                    829:   optimal. nbcode should be improved. Documentation has been added in
                    830:   the source code.
                    831: 
1.144     brouard   832:   Revision 1.143  2014/01/26 09:45:38  brouard
                    833:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    834: 
                    835:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    836:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    837: 
1.143     brouard   838:   Revision 1.142  2014/01/26 03:57:36  brouard
                    839:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    840: 
                    841:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    842: 
1.142     brouard   843:   Revision 1.141  2014/01/26 02:42:01  brouard
                    844:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    845: 
1.141     brouard   846:   Revision 1.140  2011/09/02 10:37:54  brouard
                    847:   Summary: times.h is ok with mingw32 now.
                    848: 
1.140     brouard   849:   Revision 1.139  2010/06/14 07:50:17  brouard
                    850:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    851:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    852: 
1.139     brouard   853:   Revision 1.138  2010/04/30 18:19:40  brouard
                    854:   *** empty log message ***
                    855: 
1.138     brouard   856:   Revision 1.137  2010/04/29 18:11:38  brouard
                    857:   (Module): Checking covariates for more complex models
                    858:   than V1+V2. A lot of change to be done. Unstable.
                    859: 
1.137     brouard   860:   Revision 1.136  2010/04/26 20:30:53  brouard
                    861:   (Module): merging some libgsl code. Fixing computation
                    862:   of likelione (using inter/intrapolation if mle = 0) in order to
                    863:   get same likelihood as if mle=1.
                    864:   Some cleaning of code and comments added.
                    865: 
1.136     brouard   866:   Revision 1.135  2009/10/29 15:33:14  brouard
                    867:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    868: 
1.135     brouard   869:   Revision 1.134  2009/10/29 13:18:53  brouard
                    870:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    871: 
1.134     brouard   872:   Revision 1.133  2009/07/06 10:21:25  brouard
                    873:   just nforces
                    874: 
1.133     brouard   875:   Revision 1.132  2009/07/06 08:22:05  brouard
                    876:   Many tings
                    877: 
1.132     brouard   878:   Revision 1.131  2009/06/20 16:22:47  brouard
                    879:   Some dimensions resccaled
                    880: 
1.131     brouard   881:   Revision 1.130  2009/05/26 06:44:34  brouard
                    882:   (Module): Max Covariate is now set to 20 instead of 8. A
                    883:   lot of cleaning with variables initialized to 0. Trying to make
                    884:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    885: 
1.130     brouard   886:   Revision 1.129  2007/08/31 13:49:27  lievre
                    887:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    888: 
1.129     lievre    889:   Revision 1.128  2006/06/30 13:02:05  brouard
                    890:   (Module): Clarifications on computing e.j
                    891: 
1.128     brouard   892:   Revision 1.127  2006/04/28 18:11:50  brouard
                    893:   (Module): Yes the sum of survivors was wrong since
                    894:   imach-114 because nhstepm was no more computed in the age
                    895:   loop. Now we define nhstepma in the age loop.
                    896:   (Module): In order to speed up (in case of numerous covariates) we
                    897:   compute health expectancies (without variances) in a first step
                    898:   and then all the health expectancies with variances or standard
                    899:   deviation (needs data from the Hessian matrices) which slows the
                    900:   computation.
                    901:   In the future we should be able to stop the program is only health
                    902:   expectancies and graph are needed without standard deviations.
                    903: 
1.127     brouard   904:   Revision 1.126  2006/04/28 17:23:28  brouard
                    905:   (Module): Yes the sum of survivors was wrong since
                    906:   imach-114 because nhstepm was no more computed in the age
                    907:   loop. Now we define nhstepma in the age loop.
                    908:   Version 0.98h
                    909: 
1.126     brouard   910:   Revision 1.125  2006/04/04 15:20:31  lievre
                    911:   Errors in calculation of health expectancies. Age was not initialized.
                    912:   Forecasting file added.
                    913: 
                    914:   Revision 1.124  2006/03/22 17:13:53  lievre
                    915:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    916:   The log-likelihood is printed in the log file
                    917: 
                    918:   Revision 1.123  2006/03/20 10:52:43  brouard
                    919:   * imach.c (Module): <title> changed, corresponds to .htm file
                    920:   name. <head> headers where missing.
                    921: 
                    922:   * imach.c (Module): Weights can have a decimal point as for
                    923:   English (a comma might work with a correct LC_NUMERIC environment,
                    924:   otherwise the weight is truncated).
                    925:   Modification of warning when the covariates values are not 0 or
                    926:   1.
                    927:   Version 0.98g
                    928: 
                    929:   Revision 1.122  2006/03/20 09:45:41  brouard
                    930:   (Module): Weights can have a decimal point as for
                    931:   English (a comma might work with a correct LC_NUMERIC environment,
                    932:   otherwise the weight is truncated).
                    933:   Modification of warning when the covariates values are not 0 or
                    934:   1.
                    935:   Version 0.98g
                    936: 
                    937:   Revision 1.121  2006/03/16 17:45:01  lievre
                    938:   * imach.c (Module): Comments concerning covariates added
                    939: 
                    940:   * imach.c (Module): refinements in the computation of lli if
                    941:   status=-2 in order to have more reliable computation if stepm is
                    942:   not 1 month. Version 0.98f
                    943: 
                    944:   Revision 1.120  2006/03/16 15:10:38  lievre
                    945:   (Module): refinements in the computation of lli if
                    946:   status=-2 in order to have more reliable computation if stepm is
                    947:   not 1 month. Version 0.98f
                    948: 
                    949:   Revision 1.119  2006/03/15 17:42:26  brouard
                    950:   (Module): Bug if status = -2, the loglikelihood was
                    951:   computed as likelihood omitting the logarithm. Version O.98e
                    952: 
                    953:   Revision 1.118  2006/03/14 18:20:07  brouard
                    954:   (Module): varevsij Comments added explaining the second
                    955:   table of variances if popbased=1 .
                    956:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    957:   (Module): Function pstamp added
                    958:   (Module): Version 0.98d
                    959: 
                    960:   Revision 1.117  2006/03/14 17:16:22  brouard
                    961:   (Module): varevsij Comments added explaining the second
                    962:   table of variances if popbased=1 .
                    963:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    964:   (Module): Function pstamp added
                    965:   (Module): Version 0.98d
                    966: 
                    967:   Revision 1.116  2006/03/06 10:29:27  brouard
                    968:   (Module): Variance-covariance wrong links and
                    969:   varian-covariance of ej. is needed (Saito).
                    970: 
                    971:   Revision 1.115  2006/02/27 12:17:45  brouard
                    972:   (Module): One freematrix added in mlikeli! 0.98c
                    973: 
                    974:   Revision 1.114  2006/02/26 12:57:58  brouard
                    975:   (Module): Some improvements in processing parameter
                    976:   filename with strsep.
                    977: 
                    978:   Revision 1.113  2006/02/24 14:20:24  brouard
                    979:   (Module): Memory leaks checks with valgrind and:
                    980:   datafile was not closed, some imatrix were not freed and on matrix
                    981:   allocation too.
                    982: 
                    983:   Revision 1.112  2006/01/30 09:55:26  brouard
                    984:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    985: 
                    986:   Revision 1.111  2006/01/25 20:38:18  brouard
                    987:   (Module): Lots of cleaning and bugs added (Gompertz)
                    988:   (Module): Comments can be added in data file. Missing date values
                    989:   can be a simple dot '.'.
                    990: 
                    991:   Revision 1.110  2006/01/25 00:51:50  brouard
                    992:   (Module): Lots of cleaning and bugs added (Gompertz)
                    993: 
                    994:   Revision 1.109  2006/01/24 19:37:15  brouard
                    995:   (Module): Comments (lines starting with a #) are allowed in data.
                    996: 
                    997:   Revision 1.108  2006/01/19 18:05:42  lievre
                    998:   Gnuplot problem appeared...
                    999:   To be fixed
                   1000: 
                   1001:   Revision 1.107  2006/01/19 16:20:37  brouard
                   1002:   Test existence of gnuplot in imach path
                   1003: 
                   1004:   Revision 1.106  2006/01/19 13:24:36  brouard
                   1005:   Some cleaning and links added in html output
                   1006: 
                   1007:   Revision 1.105  2006/01/05 20:23:19  lievre
                   1008:   *** empty log message ***
                   1009: 
                   1010:   Revision 1.104  2005/09/30 16:11:43  lievre
                   1011:   (Module): sump fixed, loop imx fixed, and simplifications.
                   1012:   (Module): If the status is missing at the last wave but we know
                   1013:   that the person is alive, then we can code his/her status as -2
                   1014:   (instead of missing=-1 in earlier versions) and his/her
                   1015:   contributions to the likelihood is 1 - Prob of dying from last
                   1016:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                   1017:   the healthy state at last known wave). Version is 0.98
                   1018: 
                   1019:   Revision 1.103  2005/09/30 15:54:49  lievre
                   1020:   (Module): sump fixed, loop imx fixed, and simplifications.
                   1021: 
                   1022:   Revision 1.102  2004/09/15 17:31:30  brouard
                   1023:   Add the possibility to read data file including tab characters.
                   1024: 
                   1025:   Revision 1.101  2004/09/15 10:38:38  brouard
                   1026:   Fix on curr_time
                   1027: 
                   1028:   Revision 1.100  2004/07/12 18:29:06  brouard
                   1029:   Add version for Mac OS X. Just define UNIX in Makefile
                   1030: 
                   1031:   Revision 1.99  2004/06/05 08:57:40  brouard
                   1032:   *** empty log message ***
                   1033: 
                   1034:   Revision 1.98  2004/05/16 15:05:56  brouard
                   1035:   New version 0.97 . First attempt to estimate force of mortality
                   1036:   directly from the data i.e. without the need of knowing the health
                   1037:   state at each age, but using a Gompertz model: log u =a + b*age .
                   1038:   This is the basic analysis of mortality and should be done before any
                   1039:   other analysis, in order to test if the mortality estimated from the
                   1040:   cross-longitudinal survey is different from the mortality estimated
                   1041:   from other sources like vital statistic data.
                   1042: 
                   1043:   The same imach parameter file can be used but the option for mle should be -3.
                   1044: 
1.324     brouard  1045:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard  1046:   former routines in order to include the new code within the former code.
                   1047: 
                   1048:   The output is very simple: only an estimate of the intercept and of
                   1049:   the slope with 95% confident intervals.
                   1050: 
                   1051:   Current limitations:
                   1052:   A) Even if you enter covariates, i.e. with the
                   1053:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                   1054:   B) There is no computation of Life Expectancy nor Life Table.
                   1055: 
                   1056:   Revision 1.97  2004/02/20 13:25:42  lievre
                   1057:   Version 0.96d. Population forecasting command line is (temporarily)
                   1058:   suppressed.
                   1059: 
                   1060:   Revision 1.96  2003/07/15 15:38:55  brouard
                   1061:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                   1062:   rewritten within the same printf. Workaround: many printfs.
                   1063: 
                   1064:   Revision 1.95  2003/07/08 07:54:34  brouard
                   1065:   * imach.c (Repository):
                   1066:   (Repository): Using imachwizard code to output a more meaningful covariance
                   1067:   matrix (cov(a12,c31) instead of numbers.
                   1068: 
                   1069:   Revision 1.94  2003/06/27 13:00:02  brouard
                   1070:   Just cleaning
                   1071: 
                   1072:   Revision 1.93  2003/06/25 16:33:55  brouard
                   1073:   (Module): On windows (cygwin) function asctime_r doesn't
                   1074:   exist so I changed back to asctime which exists.
                   1075:   (Module): Version 0.96b
                   1076: 
                   1077:   Revision 1.92  2003/06/25 16:30:45  brouard
                   1078:   (Module): On windows (cygwin) function asctime_r doesn't
                   1079:   exist so I changed back to asctime which exists.
                   1080: 
                   1081:   Revision 1.91  2003/06/25 15:30:29  brouard
                   1082:   * imach.c (Repository): Duplicated warning errors corrected.
                   1083:   (Repository): Elapsed time after each iteration is now output. It
                   1084:   helps to forecast when convergence will be reached. Elapsed time
                   1085:   is stamped in powell.  We created a new html file for the graphs
                   1086:   concerning matrix of covariance. It has extension -cov.htm.
                   1087: 
                   1088:   Revision 1.90  2003/06/24 12:34:15  brouard
                   1089:   (Module): Some bugs corrected for windows. Also, when
                   1090:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1091:   of the covariance matrix to be input.
                   1092: 
                   1093:   Revision 1.89  2003/06/24 12:30:52  brouard
                   1094:   (Module): Some bugs corrected for windows. Also, when
                   1095:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1096:   of the covariance matrix to be input.
                   1097: 
                   1098:   Revision 1.88  2003/06/23 17:54:56  brouard
                   1099:   * 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.
                   1100: 
                   1101:   Revision 1.87  2003/06/18 12:26:01  brouard
                   1102:   Version 0.96
                   1103: 
                   1104:   Revision 1.86  2003/06/17 20:04:08  brouard
                   1105:   (Module): Change position of html and gnuplot routines and added
                   1106:   routine fileappend.
                   1107: 
                   1108:   Revision 1.85  2003/06/17 13:12:43  brouard
                   1109:   * imach.c (Repository): Check when date of death was earlier that
                   1110:   current date of interview. It may happen when the death was just
                   1111:   prior to the death. In this case, dh was negative and likelihood
                   1112:   was wrong (infinity). We still send an "Error" but patch by
                   1113:   assuming that the date of death was just one stepm after the
                   1114:   interview.
                   1115:   (Repository): Because some people have very long ID (first column)
                   1116:   we changed int to long in num[] and we added a new lvector for
                   1117:   memory allocation. But we also truncated to 8 characters (left
                   1118:   truncation)
                   1119:   (Repository): No more line truncation errors.
                   1120: 
                   1121:   Revision 1.84  2003/06/13 21:44:43  brouard
                   1122:   * imach.c (Repository): Replace "freqsummary" at a correct
                   1123:   place. It differs from routine "prevalence" which may be called
                   1124:   many times. Probs is memory consuming and must be used with
                   1125:   parcimony.
                   1126:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                   1127: 
                   1128:   Revision 1.83  2003/06/10 13:39:11  lievre
                   1129:   *** empty log message ***
                   1130: 
                   1131:   Revision 1.82  2003/06/05 15:57:20  brouard
                   1132:   Add log in  imach.c and  fullversion number is now printed.
                   1133: 
                   1134: */
                   1135: /*
                   1136:    Interpolated Markov Chain
                   1137: 
                   1138:   Short summary of the programme:
                   1139:   
1.227     brouard  1140:   This program computes Healthy Life Expectancies or State-specific
                   1141:   (if states aren't health statuses) Expectancies from
                   1142:   cross-longitudinal data. Cross-longitudinal data consist in: 
                   1143: 
                   1144:   -1- a first survey ("cross") where individuals from different ages
                   1145:   are interviewed on their health status or degree of disability (in
                   1146:   the case of a health survey which is our main interest)
                   1147: 
                   1148:   -2- at least a second wave of interviews ("longitudinal") which
                   1149:   measure each change (if any) in individual health status.  Health
                   1150:   expectancies are computed from the time spent in each health state
                   1151:   according to a model. More health states you consider, more time is
                   1152:   necessary to reach the Maximum Likelihood of the parameters involved
                   1153:   in the model.  The simplest model is the multinomial logistic model
                   1154:   where pij is the probability to be observed in state j at the second
                   1155:   wave conditional to be observed in state i at the first
                   1156:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                   1157:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                   1158:   have a more complex model than "constant and age", you should modify
                   1159:   the program where the markup *Covariates have to be included here
                   1160:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard  1161:   convergence.
                   1162: 
                   1163:   The advantage of this computer programme, compared to a simple
                   1164:   multinomial logistic model, is clear when the delay between waves is not
                   1165:   identical for each individual. Also, if a individual missed an
                   1166:   intermediate interview, the information is lost, but taken into
                   1167:   account using an interpolation or extrapolation.  
                   1168: 
                   1169:   hPijx is the probability to be observed in state i at age x+h
                   1170:   conditional to the observed state i at age x. The delay 'h' can be
                   1171:   split into an exact number (nh*stepm) of unobserved intermediate
                   1172:   states. This elementary transition (by month, quarter,
                   1173:   semester or year) is modelled as a multinomial logistic.  The hPx
                   1174:   matrix is simply the matrix product of nh*stepm elementary matrices
                   1175:   and the contribution of each individual to the likelihood is simply
                   1176:   hPijx.
                   1177: 
                   1178:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard  1179:   of the life expectancies. It also computes the period (stable) prevalence.
                   1180: 
                   1181: Back prevalence and projections:
1.227     brouard  1182: 
                   1183:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                   1184:    double agemaxpar, double ftolpl, int *ncvyearp, double
                   1185:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                   1186:    mobilavproj)
                   1187: 
                   1188:     Computes the back prevalence limit for any combination of
                   1189:     covariate values k at any age between ageminpar and agemaxpar and
                   1190:     returns it in **bprlim. In the loops,
                   1191: 
                   1192:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                   1193:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                   1194: 
                   1195:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard  1196:    Computes for any combination of covariates k and any age between bage and fage 
                   1197:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1198:                        oldm=oldms;savm=savms;
1.227     brouard  1199: 
1.267     brouard  1200:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard  1201:      Computes the transition matrix starting at age 'age' over
                   1202:      'nhstepm*hstepm*stepm' months (i.e. until
                   1203:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard  1204:      nhstepm*hstepm matrices. 
                   1205: 
                   1206:      Returns p3mat[i][j][h] after calling
                   1207:      p3mat[i][j][h]=matprod2(newm,
                   1208:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                   1209:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                   1210:      oldm);
1.226     brouard  1211: 
                   1212: Important routines
                   1213: 
                   1214: - func (or funcone), computes logit (pij) distinguishing
                   1215:   o fixed variables (single or product dummies or quantitative);
                   1216:   o varying variables by:
                   1217:    (1) wave (single, product dummies, quantitative), 
                   1218:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                   1219:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                   1220:        % varying dummy (not done) or quantitative (not done);
                   1221: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                   1222:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                   1223: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
1.325     brouard  1224:   o There are 2**cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
1.226     brouard  1225:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard  1226: 
1.226     brouard  1227: 
                   1228:   
1.324     brouard  1229:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                   1230:            Institut national d'études démographiques, Paris.
1.126     brouard  1231:   This software have been partly granted by Euro-REVES, a concerted action
                   1232:   from the European Union.
                   1233:   It is copyrighted identically to a GNU software product, ie programme and
                   1234:   software can be distributed freely for non commercial use. Latest version
                   1235:   can be accessed at http://euroreves.ined.fr/imach .
                   1236: 
                   1237:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                   1238:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                   1239:   
                   1240:   **********************************************************************/
                   1241: /*
                   1242:   main
                   1243:   read parameterfile
                   1244:   read datafile
                   1245:   concatwav
                   1246:   freqsummary
                   1247:   if (mle >= 1)
                   1248:     mlikeli
                   1249:   print results files
                   1250:   if mle==1 
                   1251:      computes hessian
                   1252:   read end of parameter file: agemin, agemax, bage, fage, estepm
                   1253:       begin-prev-date,...
                   1254:   open gnuplot file
                   1255:   open html file
1.145     brouard  1256:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1257:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1258:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1259:     freexexit2 possible for memory heap.
                   1260: 
                   1261:   h Pij x                         | pij_nom  ficrestpij
                   1262:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1263:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1264:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1265: 
                   1266:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1267:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1268:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1269:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1270:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1271: 
1.126     brouard  1272:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1273:   health expectancies
                   1274:   Variance-covariance of DFLE
                   1275:   prevalence()
                   1276:    movingaverage()
                   1277:   varevsij() 
                   1278:   if popbased==1 varevsij(,popbased)
                   1279:   total life expectancies
                   1280:   Variance of period (stable) prevalence
                   1281:  end
                   1282: */
                   1283: 
1.187     brouard  1284: /* #define DEBUG */
                   1285: /* #define DEBUGBRENT */
1.203     brouard  1286: /* #define DEBUGLINMIN */
                   1287: /* #define DEBUGHESS */
                   1288: #define DEBUGHESSIJ
1.224     brouard  1289: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1290: #define POWELL /* Instead of NLOPT */
1.224     brouard  1291: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1292: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1293: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.319     brouard  1294: /* #define FLATSUP  *//* Suppresses directions where likelihood is flat */
1.357   ! brouard  1295: #define POWELLORIGINCONJUGATE  /* Don't use conjugate but biggest decrease if valuable */
1.126     brouard  1296: 
                   1297: #include <math.h>
                   1298: #include <stdio.h>
                   1299: #include <stdlib.h>
                   1300: #include <string.h>
1.226     brouard  1301: #include <ctype.h>
1.159     brouard  1302: 
                   1303: #ifdef _WIN32
                   1304: #include <io.h>
1.172     brouard  1305: #include <windows.h>
                   1306: #include <tchar.h>
1.159     brouard  1307: #else
1.126     brouard  1308: #include <unistd.h>
1.159     brouard  1309: #endif
1.126     brouard  1310: 
                   1311: #include <limits.h>
                   1312: #include <sys/types.h>
1.171     brouard  1313: 
                   1314: #if defined(__GNUC__)
                   1315: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1316: #endif
                   1317: 
1.126     brouard  1318: #include <sys/stat.h>
                   1319: #include <errno.h>
1.159     brouard  1320: /* extern int errno; */
1.126     brouard  1321: 
1.157     brouard  1322: /* #ifdef LINUX */
                   1323: /* #include <time.h> */
                   1324: /* #include "timeval.h" */
                   1325: /* #else */
                   1326: /* #include <sys/time.h> */
                   1327: /* #endif */
                   1328: 
1.126     brouard  1329: #include <time.h>
                   1330: 
1.136     brouard  1331: #ifdef GSL
                   1332: #include <gsl/gsl_errno.h>
                   1333: #include <gsl/gsl_multimin.h>
                   1334: #endif
                   1335: 
1.167     brouard  1336: 
1.162     brouard  1337: #ifdef NLOPT
                   1338: #include <nlopt.h>
                   1339: typedef struct {
                   1340:   double (* function)(double [] );
                   1341: } myfunc_data ;
                   1342: #endif
                   1343: 
1.126     brouard  1344: /* #include <libintl.h> */
                   1345: /* #define _(String) gettext (String) */
                   1346: 
1.349     brouard  1347: #define MAXLINE 16384 /* Was 256 and 1024 and 2048. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1348: 
                   1349: #define GNUPLOTPROGRAM "gnuplot"
1.343     brouard  1350: #define GNUPLOTVERSION 5.1
                   1351: double gnuplotversion=GNUPLOTVERSION;
1.126     brouard  1352: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
1.329     brouard  1353: #define FILENAMELENGTH 256
1.126     brouard  1354: 
                   1355: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1356: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1357: 
1.349     brouard  1358: #define MAXPARM 216 /**< Maximum number of parameters for the optimization was 128 */
1.144     brouard  1359: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1360: 
                   1361: #define NINTERVMAX 8
1.144     brouard  1362: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1363: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.325     brouard  1364: #define NCOVMAX 30  /**< Maximum number of covariates used in the model, including generated covariates V1*V2 or V1*age */
1.197     brouard  1365: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1366: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1367: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1368: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1369: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1370: /* #define AGESUP 130 */
1.288     brouard  1371: /* #define AGESUP 150 */
                   1372: #define AGESUP 200
1.268     brouard  1373: #define AGEINF 0
1.218     brouard  1374: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1375: #define AGEBASE 40
1.194     brouard  1376: #define AGEOVERFLOW 1.e20
1.164     brouard  1377: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1378: #ifdef _WIN32
                   1379: #define DIRSEPARATOR '\\'
                   1380: #define CHARSEPARATOR "\\"
                   1381: #define ODIRSEPARATOR '/'
                   1382: #else
1.126     brouard  1383: #define DIRSEPARATOR '/'
                   1384: #define CHARSEPARATOR "/"
                   1385: #define ODIRSEPARATOR '\\'
                   1386: #endif
                   1387: 
1.357   ! brouard  1388: /* $Id: imach.c,v 1.356 2023/05/23 12:08:43 brouard Exp $ */
1.126     brouard  1389: /* $State: Exp $ */
1.196     brouard  1390: #include "version.h"
                   1391: char version[]=__IMACH_VERSION__;
1.352     brouard  1392: char copyright[]="April 2023,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.357   ! brouard  1393: char fullversion[]="$Revision: 1.356 $ $Date: 2023/05/23 12:08:43 $"; 
1.126     brouard  1394: char strstart[80];
                   1395: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1396: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.342     brouard  1397: int debugILK=0; /* debugILK is set by a #d in a comment line */
1.187     brouard  1398: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.330     brouard  1399: /* Number of covariates model (1)=V2+V1+ V3*age+V2*V4 */
                   1400: /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
1.335     brouard  1401: 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  1402: 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  1403: int cptcovs=0; /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   1404: int cptcovsnq=0; /**< cptcovsnq number of SIMPLE covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1405: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
1.349     brouard  1406: int cptcovprodage=0; /**< Number of fixed covariates with age: V3*age or V2*V3*age 1 */
                   1407: int cptcovprodvage=0; /**< Number of varying covariates with age: V7*age or V7*V6*age */
                   1408: int cptcovdageprod=0; /**< Number of doubleproducts with age, since 0.99r44 only: age*Vn*Vm for gnuplot printing*/
1.145     brouard  1409: int cptcovprodnoage=0; /**< Number of covariate products without age */   
1.335     brouard  1410: 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  1411: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1412: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.339     brouard  1413: int ncovvt=0; /* Total number of effective (wave) varying covariates (dummy or quantitative or products [without age]) in the model */
1.349     brouard  1414: int ncovvta=0; /*  +age*V6 + age*V7+ age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 Total number of expandend products [with age]) in the model */
                   1415: int ncovta=0; /*age*V3*V2 +age*V2+agev3+ageV4  +age*V6 + age*V7+ age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 Total number of expandend products [with age]) in the model */
                   1416: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (single or product, dummy or quantitative) in the model */
                   1417: int ncovva=0; /* +age*V6 + age*V7+ge*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 Total number of effective (wave and stepm) varying with age covariates (single or product, dummy or quantitative) in the model */
1.234     brouard  1418: int nsd=0; /**< Total number of single dummy variables (output) */
                   1419: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1420: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1421: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1422: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1423: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1424: int cptcov=0; /* Working variable */
1.334     brouard  1425: int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs+1 declared globally ;*/
1.290     brouard  1426: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1427: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.302     brouard  1428: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
1.126     brouard  1429: int nlstate=2; /* Number of live states */
                   1430: int ndeath=1; /* Number of dead states */
1.130     brouard  1431: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.339     brouard  1432: int nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable*/
                   1433: int ncovcolt=0; /* ncovcolt=ncovcol+nqv+ntv+nqtv; total of covariates in the data, not in the model equation*/ 
1.126     brouard  1434: int popbased=0;
                   1435: 
                   1436: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1437: int maxwav=0; /* Maxim number of waves */
                   1438: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1439: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1440: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard  1441:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1442: int mle=1, weightopt=0;
1.126     brouard  1443: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1444: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1445: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1446:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1447: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1448: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1449: 
1.130     brouard  1450: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1451: double **matprod2(); /* test */
1.126     brouard  1452: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1453: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1454: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1455: 
1.136     brouard  1456: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1457: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1458: FILE *ficlog, *ficrespow;
1.130     brouard  1459: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1460: double fretone; /* Only one call to likelihood */
1.130     brouard  1461: long ipmx=0; /* Number of contributions */
1.126     brouard  1462: double sw; /* Sum of weights */
                   1463: char filerespow[FILENAMELENGTH];
                   1464: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1465: FILE *ficresilk;
                   1466: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1467: FILE *ficresprobmorprev;
                   1468: FILE *fichtm, *fichtmcov; /* Html File */
                   1469: FILE *ficreseij;
                   1470: char filerese[FILENAMELENGTH];
                   1471: FILE *ficresstdeij;
                   1472: char fileresstde[FILENAMELENGTH];
                   1473: FILE *ficrescveij;
                   1474: char filerescve[FILENAMELENGTH];
                   1475: FILE  *ficresvij;
                   1476: char fileresv[FILENAMELENGTH];
1.269     brouard  1477: 
1.126     brouard  1478: char title[MAXLINE];
1.234     brouard  1479: char model[MAXLINE]; /**< The model line */
1.217     brouard  1480: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1481: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1482: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1483: char command[FILENAMELENGTH];
                   1484: int  outcmd=0;
                   1485: 
1.217     brouard  1486: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1487: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1488: char filelog[FILENAMELENGTH]; /* Log file */
                   1489: char filerest[FILENAMELENGTH];
                   1490: char fileregp[FILENAMELENGTH];
                   1491: char popfile[FILENAMELENGTH];
                   1492: 
                   1493: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1494: 
1.157     brouard  1495: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1496: /* struct timezone tzp; */
                   1497: /* extern int gettimeofday(); */
                   1498: struct tm tml, *gmtime(), *localtime();
                   1499: 
                   1500: extern time_t time();
                   1501: 
                   1502: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1503: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
1.349     brouard  1504: time_t   rlast_btime; /* raw time */
1.157     brouard  1505: struct tm tm;
                   1506: 
1.126     brouard  1507: char strcurr[80], strfor[80];
                   1508: 
                   1509: char *endptr;
                   1510: long lval;
                   1511: double dval;
                   1512: 
                   1513: #define NR_END 1
                   1514: #define FREE_ARG char*
                   1515: #define FTOL 1.0e-10
                   1516: 
                   1517: #define NRANSI 
1.240     brouard  1518: #define ITMAX 200
                   1519: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1520: 
                   1521: #define TOL 2.0e-4 
                   1522: 
                   1523: #define CGOLD 0.3819660 
                   1524: #define ZEPS 1.0e-10 
                   1525: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1526: 
                   1527: #define GOLD 1.618034 
                   1528: #define GLIMIT 100.0 
                   1529: #define TINY 1.0e-20 
                   1530: 
                   1531: static double maxarg1,maxarg2;
                   1532: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1533: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1534:   
                   1535: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1536: #define rint(a) floor(a+0.5)
1.166     brouard  1537: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1538: #define mytinydouble 1.0e-16
1.166     brouard  1539: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1540: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1541: /* static double dsqrarg; */
                   1542: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1543: static double sqrarg;
                   1544: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1545: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1546: int agegomp= AGEGOMP;
                   1547: 
                   1548: int imx; 
                   1549: int stepm=1;
                   1550: /* Stepm, step in month: minimum step interpolation*/
                   1551: 
                   1552: int estepm;
                   1553: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1554: 
                   1555: int m,nb;
                   1556: long *num;
1.197     brouard  1557: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1558: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1559:                   covariate for which somebody answered excluding 
                   1560:                   undefined. Usually 2: 0 and 1. */
                   1561: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1562:                             covariate for which somebody answered including 
                   1563:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1564: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1565: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1566: double ***mobaverage, ***mobaverages; /* New global variable */
1.332     brouard  1567: 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  1568: double *ageexmed,*agecens;
                   1569: double dateintmean=0;
1.296     brouard  1570:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1571:   double anprojf, mprojf, jprojf;
1.126     brouard  1572: 
1.296     brouard  1573:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1574:   double anbackf, mbackf, jbackf;
                   1575:   double jintmean,mintmean,aintmean;  
1.126     brouard  1576: double *weight;
                   1577: int **s; /* Status */
1.141     brouard  1578: double *agedc;
1.145     brouard  1579: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1580:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1581:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1582: double **coqvar; /* Fixed quantitative covariate nqv */
1.341     brouard  1583: double ***cotvar; /* Time varying covariate start at ncovcol + nqv + (1 to ntv) */
1.225     brouard  1584: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1585: double  idx; 
                   1586: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.319     brouard  1587: /* Some documentation */
                   1588:       /*   Design original data
                   1589:        *  V1   V2   V3   V4  V5  V6  V7  V8  Weight ddb ddth d1st s1 V9 V10 V11 V12 s2 V9 V10 V11 V12 
                   1590:        *  <          ncovcol=6   >   nqv=2 (V7 V8)                   dv dv  dv  qtv    dv dv  dvv qtv
                   1591:        *                                                             ntv=3     nqtv=1
1.330     brouard  1592:        *  cptcovn number of covariates (not including constant and age or age*age) = number of plus sign + 1 = 10+1=11
1.319     brouard  1593:        * For time varying covariate, quanti or dummies
                   1594:        *       cotqvar[wav][iv(1 to nqtv)][i]= [1][12][i]=(V12) quanti
1.341     brouard  1595:        *       cotvar[wav][ncovcol+nqv+ iv(1 to nqtv)][i]= [(1 to nqtv)][i]=(V12) quanti
1.319     brouard  1596:        *       cotvar[wav][iv(1 to ntv)][i]= [1][1][i]=(V9) dummies at wav 1
                   1597:        *       cotvar[wav][iv(1 to ntv)][i]= [1][2][i]=(V10) dummies at wav 1
1.332     brouard  1598:        *       covar[Vk,i], value of the Vkth fixed covariate dummy or quanti for individual i:
1.319     brouard  1599:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   1600:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 + V9 + V9*age + V10
                   1601:        *   k=  1    2      3       4     5       6      7        8   9     10       11 
                   1602:        */
                   1603: /* According to the model, more columns can be added to covar by the product of covariates */
1.318     brouard  1604: /* 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
                   1605:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1606:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1607: */
1.349     brouard  1608: /*           V5+V4+ V3+V4*V3 +V5*age+V2 +V1*V2+V1*age+V1+V4*V3*age */
                   1609: /*    kmodel  1  2   3    4     5     6    7     8     9    10 */
                   1610: /*Typevar[k]=  0  0   0   2     1    0    2     1     0    3 *//*0 for simple covariate (dummy, quantitative,*/
                   1611:                                                                /* fixed or varying), 1 for age product, 2 for*/
                   1612:                                                                /* product without age, 3 for age and double product   */
                   1613: /*Dummy[k]=    1  0   0   1     3    1    1     2     0     3  *//*Dummy[k] 0=dummy (0 1), 1 quantitative */
                   1614:                                                                 /*(single or product without age), 2 dummy*/
                   1615:                                                                /* with age product, 3 quant with age product*/
                   1616: /*Tvar[k]=     5  4   3   6     5    2    7     1     1     6 */
                   1617: /*    nsd         1   2                               3 */ /* Counting single dummies covar fixed or tv */
                   1618: /*TnsdVar[Tvar]   1   2                               3 */ 
                   1619: /*Tvaraff[nsd]    4   3                               1 */ /* ID of single dummy cova fixed or timevary*/
                   1620: /*TvarsD[nsd]     4   3                               1 */ /* ID of single dummy cova fixed or timevary*/
                   1621: /*TvarsDind[nsd]  2   3                               9 */ /* position K of single dummy cova */
                   1622: /*    nsq      1                     2                  */ /* Counting single quantit tv */
                   1623: /* TvarsQ[k]   5                     2                  */ /* Number of single quantitative cova */
                   1624: /* TvarsQind   1                     6                  */ /* position K of single quantitative cova */
                   1625: /* Tprod[i]=k             1               2             */ /* Position in model of the ith prod without age */
                   1626: /* cptcovage                    1               2         3 */ /* Counting cov*age in the model equation */
                   1627: /* Tage[cptcovage]=k            5               8         10 */ /* Position in the model of ith cov*age */
1.350     brouard  1628: /* model="V2+V3+V4+V6+V7+V6*V2+V7*V2+V6*V3+V7*V3+V6*V4+V7*V4+age*V2+age*V3+age*V4+age*V6+age*V7+age*V6*V2+age*V6*V3+age*V7*V3+age*V6*V4+age*V7*V4\r"*/
                   1629: /*  p Tvard[1][1]@21 = {6, 2, 7, 2, 6, 3, 7, 3, 6, 4, 7, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0}*/
1.354     brouard  1630: /*  p Tvard[2][1]@21 = {7, 2, 6, 3, 7, 3, 6, 4, 7, 4, 0 <repeats 11 times>} */
1.350     brouard  1631: /* p Tvardk[1][1]@24 = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 2, 7, 2, 6, 3, 7, 3, 6, 4, 7, 4, 0, 0}*/
                   1632: /* p Tvardk[1][1]@22 = {0, 0, 0, 0, 0, 0, 0, 0, 6, 2, 7, 2, 6, 3, 7, 3, 6, 4, 7, 4, 0, 0} */
1.349     brouard  1633: /* Tvard[1][1]@4={4,3,1,2}    V4*V3 V1*V2               */ /* Position in model of the ith prod without age */
1.330     brouard  1634: /* 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  1635: /* 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  1636: /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.234     brouard  1637: /* Type                    */
                   1638: /* V         1  2  3  4  5 */
                   1639: /*           F  F  V  V  V */
                   1640: /*           D  Q  D  D  Q */
                   1641: /*                         */
                   1642: int *TvarsD;
1.330     brouard  1643: int *TnsdVar;
1.234     brouard  1644: int *TvarsDind;
                   1645: int *TvarsQ;
                   1646: int *TvarsQind;
                   1647: 
1.318     brouard  1648: #define MAXRESULTLINESPONE 10+1
1.235     brouard  1649: int nresult=0;
1.258     brouard  1650: int parameterline=0; /* # of the parameter (type) line */
1.334     brouard  1651: int TKresult[MAXRESULTLINESPONE]; /* TKresult[nres]=k for each resultline nres give the corresponding combination of dummies */
                   1652: int resultmodel[MAXRESULTLINESPONE][NCOVMAX];/* resultmodel[k1]=k3: k1th position in the model corresponds to the k3 position in the resultline */
                   1653: int modelresult[MAXRESULTLINESPONE][NCOVMAX];/* modelresult[k3]=k1: k1th position in the model corresponds to the k3 position in the resultline */
                   1654: int Tresult[MAXRESULTLINESPONE][NCOVMAX];/* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1655: int Tinvresult[MAXRESULTLINESPONE][NCOVMAX];/* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line  */
                   1656: double TinvDoQresult[MAXRESULTLINESPONE][NCOVMAX];/* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line */
1.334     brouard  1657: int Tvresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1658: double Tqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
1.318     brouard  1659: double Tqinvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
1.332     brouard  1660: int Tvqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline */
1.318     brouard  1661: 
                   1662: /* 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
                   1663:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1664:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1665: */
1.234     brouard  1666: /* 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  1667: 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 */
                   1668: 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 */
                   1669: 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 */
                   1670: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1671: 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 */
                   1672: 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  1673: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1674: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1675: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1676: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1677: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1678: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1679: 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 */
                   1680: 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  1681: int *TvarVV; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1682: int *TvarVVind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
1.349     brouard  1683: int *TvarVVA; /* We count ncovvt time varying covariates (single or products with age) and put their name into TvarVVA */
                   1684: int *TvarVVAind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1685: int *TvarAVVA; /* We count ALL ncovta time varying covariates (single or products with age) and put their name into TvarVVA */
                   1686: int *TvarAVVAind; /* We count ALL ncovta time varying covariates (single or products without age) and put their name into TvarVV */
1.339     brouard  1687:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
1.349     brouard  1688:       /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age */
                   1689:       /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   1690:       /* TvarVV={3,1,3,1,3}, for V3 and then the product V1*V3 is decomposed into V1 and V3 */        
                   1691:       /* TvarVVind={2,5,5,6,6}, for V3 and then the product V1*V3 is decomposed into V1 and V3 and V1*V3*age into 6,6 */              
1.230     brouard  1692: int *Tvarsel; /**< Selected covariates for output */
                   1693: double *Tvalsel; /**< Selected modality value of covariate for output */
1.349     brouard  1694: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product, 3 age*Vn*Vm */
1.227     brouard  1695: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1696: 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  1697: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1698: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1699: int *Tage;
1.227     brouard  1700: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1701: 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  1702: 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*/ 
                   1703: 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  1704: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1705: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1706: int **Tvard;
1.330     brouard  1707: int **Tvardk;
1.227     brouard  1708: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1709: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1710: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1711:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1712:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1713: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1714: double *lsurv, *lpop, *tpop;
                   1715: 
1.231     brouard  1716: #define FD 1; /* Fixed dummy covariate */
                   1717: #define FQ 2; /* Fixed quantitative covariate */
                   1718: #define FP 3; /* Fixed product covariate */
                   1719: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1720: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1721: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1722: #define VD 10; /* Varying dummy covariate */
                   1723: #define VQ 11; /* Varying quantitative covariate */
                   1724: #define VP 12; /* Varying product covariate */
                   1725: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1726: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1727: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1728: #define APFD 16; /* Age product * fixed dummy covariate */
                   1729: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1730: #define APVD 18; /* Age product * varying dummy covariate */
                   1731: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1732: 
                   1733: #define FTYPE 1; /* Fixed covariate */
                   1734: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1735: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1736: 
                   1737: struct kmodel{
                   1738:        int maintype; /* main type */
                   1739:        int subtype; /* subtype */
                   1740: };
                   1741: struct kmodel modell[NCOVMAX];
                   1742: 
1.143     brouard  1743: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1744: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1745: 
                   1746: /**************** split *************************/
                   1747: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1748: {
                   1749:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1750:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1751:   */ 
                   1752:   char *ss;                            /* pointer */
1.186     brouard  1753:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1754: 
                   1755:   l1 = strlen(path );                  /* length of path */
                   1756:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1757:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1758:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1759:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1760:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1761:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1762:     /* get current working directory */
                   1763:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1764: #ifdef WIN32
                   1765:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1766: #else
                   1767:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1768: #endif
1.126     brouard  1769:       return( GLOCK_ERROR_GETCWD );
                   1770:     }
                   1771:     /* got dirc from getcwd*/
                   1772:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1773:   } else {                             /* strip directory from path */
1.126     brouard  1774:     ss++;                              /* after this, the filename */
                   1775:     l2 = strlen( ss );                 /* length of filename */
                   1776:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1777:     strcpy( name, ss );                /* save file name */
                   1778:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1779:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1780:     printf(" DIRC2 = %s \n",dirc);
                   1781:   }
                   1782:   /* We add a separator at the end of dirc if not exists */
                   1783:   l1 = strlen( dirc );                 /* length of directory */
                   1784:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1785:     dirc[l1] =  DIRSEPARATOR;
                   1786:     dirc[l1+1] = 0; 
                   1787:     printf(" DIRC3 = %s \n",dirc);
                   1788:   }
                   1789:   ss = strrchr( name, '.' );           /* find last / */
                   1790:   if (ss >0){
                   1791:     ss++;
                   1792:     strcpy(ext,ss);                    /* save extension */
                   1793:     l1= strlen( name);
                   1794:     l2= strlen(ss)+1;
                   1795:     strncpy( finame, name, l1-l2);
                   1796:     finame[l1-l2]= 0;
                   1797:   }
                   1798: 
                   1799:   return( 0 );                         /* we're done */
                   1800: }
                   1801: 
                   1802: 
                   1803: /******************************************/
                   1804: 
                   1805: void replace_back_to_slash(char *s, char*t)
                   1806: {
                   1807:   int i;
                   1808:   int lg=0;
                   1809:   i=0;
                   1810:   lg=strlen(t);
                   1811:   for(i=0; i<= lg; i++) {
                   1812:     (s[i] = t[i]);
                   1813:     if (t[i]== '\\') s[i]='/';
                   1814:   }
                   1815: }
                   1816: 
1.132     brouard  1817: char *trimbb(char *out, char *in)
1.137     brouard  1818: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1819:   char *s;
                   1820:   s=out;
                   1821:   while (*in != '\0'){
1.137     brouard  1822:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1823:       in++;
                   1824:     }
                   1825:     *out++ = *in++;
                   1826:   }
                   1827:   *out='\0';
                   1828:   return s;
                   1829: }
                   1830: 
1.351     brouard  1831: char *trimbtab(char *out, char *in)
                   1832: { /* Trim  blanks or tabs in line but keeps first blanks if line starts with blanks */
                   1833:   char *s;
                   1834:   s=out;
                   1835:   while (*in != '\0'){
                   1836:     while( (*in == ' ' || *in == '\t')){ /* && *(in+1) != '\0'){*/
                   1837:       in++;
                   1838:     }
                   1839:     *out++ = *in++;
                   1840:   }
                   1841:   *out='\0';
                   1842:   return s;
                   1843: }
                   1844: 
1.187     brouard  1845: /* char *substrchaine(char *out, char *in, char *chain) */
                   1846: /* { */
                   1847: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1848: /*   char *s, *t; */
                   1849: /*   t=in;s=out; */
                   1850: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1851: /*     *out++ = *in++; */
                   1852: /*   } */
                   1853: 
                   1854: /*   /\* *in matches *chain *\/ */
                   1855: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1856: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1857: /*   } */
                   1858: /*   in--; chain--; */
                   1859: /*   while ( (*in != '\0')){ */
                   1860: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1861: /*     *out++ = *in++; */
                   1862: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1863: /*   } */
                   1864: /*   *out='\0'; */
                   1865: /*   out=s; */
                   1866: /*   return out; */
                   1867: /* } */
                   1868: char *substrchaine(char *out, char *in, char *chain)
                   1869: {
                   1870:   /* Substract chain 'chain' from 'in', return and output 'out' */
1.349     brouard  1871:   /* in="V1+V1*age+age*age+V2", chain="+age*age" out="V1+V1*age+V2" */
1.187     brouard  1872: 
                   1873:   char *strloc;
                   1874: 
1.349     brouard  1875:   strcpy (out, in);                   /* out="V1+V1*age+age*age+V2" */
                   1876:   strloc = strstr(out, chain); /* strloc points to out at "+age*age+V2"  */
                   1877:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out); /* strloc=+age*age+V2 chain="+age*age", out="V1+V1*age+age*age+V2" */
1.187     brouard  1878:   if(strloc != NULL){ 
1.349     brouard  1879:     /* will affect out */ /* strloc+strlen(chain)=|+V2 = "V1+V1*age+age*age|+V2" */ /* Will also work in Unicodek */
                   1880:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1); /* move number of bytes corresponding to the length of "+V2" which is 3, plus one is 4 (including the null)*/
                   1881:     /* equivalent to strcpy (strloc, strloc +strlen(chain)) if no overlap; Copies from "+V2" to V1+V1*age+ */
1.187     brouard  1882:   }
1.349     brouard  1883:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);  /* strloc=+V2 chain="+age*age", in="V1+V1*age+age*age+V2", out="V1+V1*age+V2" */
1.187     brouard  1884:   return out;
                   1885: }
                   1886: 
                   1887: 
1.145     brouard  1888: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1889: {
1.187     brouard  1890:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.349     brouard  1891:      and alocc starts after first occurence of char 'occ' : ex cutl(blocc,alocc,"abcdef2ghi2j",'2')
1.310     brouard  1892:      gives alocc="abcdef" and blocc="ghi2j".
1.145     brouard  1893:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1894:   */
1.160     brouard  1895:   char *s, *t;
1.145     brouard  1896:   t=in;s=in;
                   1897:   while ((*in != occ) && (*in != '\0')){
                   1898:     *alocc++ = *in++;
                   1899:   }
                   1900:   if( *in == occ){
                   1901:     *(alocc)='\0';
                   1902:     s=++in;
                   1903:   }
                   1904:  
                   1905:   if (s == t) {/* occ not found */
                   1906:     *(alocc-(in-s))='\0';
                   1907:     in=s;
                   1908:   }
                   1909:   while ( *in != '\0'){
                   1910:     *blocc++ = *in++;
                   1911:   }
                   1912: 
                   1913:   *blocc='\0';
                   1914:   return t;
                   1915: }
1.137     brouard  1916: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1917: {
1.187     brouard  1918:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1919:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1920:      gives blocc="abcdef2ghi" and alocc="j".
                   1921:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1922:   */
                   1923:   char *s, *t;
                   1924:   t=in;s=in;
                   1925:   while (*in != '\0'){
                   1926:     while( *in == occ){
                   1927:       *blocc++ = *in++;
                   1928:       s=in;
                   1929:     }
                   1930:     *blocc++ = *in++;
                   1931:   }
                   1932:   if (s == t) /* occ not found */
                   1933:     *(blocc-(in-s))='\0';
                   1934:   else
                   1935:     *(blocc-(in-s)-1)='\0';
                   1936:   in=s;
                   1937:   while ( *in != '\0'){
                   1938:     *alocc++ = *in++;
                   1939:   }
                   1940: 
                   1941:   *alocc='\0';
                   1942:   return s;
                   1943: }
                   1944: 
1.126     brouard  1945: int nbocc(char *s, char occ)
                   1946: {
                   1947:   int i,j=0;
                   1948:   int lg=20;
                   1949:   i=0;
                   1950:   lg=strlen(s);
                   1951:   for(i=0; i<= lg; i++) {
1.234     brouard  1952:     if  (s[i] == occ ) j++;
1.126     brouard  1953:   }
                   1954:   return j;
                   1955: }
                   1956: 
1.349     brouard  1957: int nboccstr(char *textin, char *chain)
                   1958: {
                   1959:   /* Counts the number of occurence of "chain"  in string textin */
                   1960:   /*  in="+V7*V4+age*V2+age*V3+age*V4"  chain="age" */
                   1961:   char *strloc;
                   1962:   
                   1963:   int i,j=0;
                   1964: 
                   1965:   i=0;
                   1966: 
                   1967:   strloc=textin; /* strloc points to "^+V7*V4+age+..." in textin */
                   1968:   for(;;) {
                   1969:     strloc= strstr(strloc,chain); /* strloc points to first character of chain in textin if found. Example strloc points^ to "+V7*V4+^age" in textin  */
                   1970:     if(strloc != NULL){
                   1971:       strloc = strloc+strlen(chain); /* strloc points to "+V7*V4+age^" in textin */
                   1972:       j++;
                   1973:     }else
                   1974:       break;
                   1975:   }
                   1976:   return j;
                   1977:   
                   1978: }
1.137     brouard  1979: /* void cutv(char *u,char *v, char*t, char occ) */
                   1980: /* { */
                   1981: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1982: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1983: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1984: /*   int i,lg,j,p=0; */
                   1985: /*   i=0; */
                   1986: /*   lg=strlen(t); */
                   1987: /*   for(j=0; j<=lg-1; j++) { */
                   1988: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1989: /*   } */
1.126     brouard  1990: 
1.137     brouard  1991: /*   for(j=0; j<p; j++) { */
                   1992: /*     (u[j] = t[j]); */
                   1993: /*   } */
                   1994: /*      u[p]='\0'; */
1.126     brouard  1995: 
1.137     brouard  1996: /*    for(j=0; j<= lg; j++) { */
                   1997: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1998: /*   } */
                   1999: /* } */
1.126     brouard  2000: 
1.160     brouard  2001: #ifdef _WIN32
                   2002: char * strsep(char **pp, const char *delim)
                   2003: {
                   2004:   char *p, *q;
                   2005:          
                   2006:   if ((p = *pp) == NULL)
                   2007:     return 0;
                   2008:   if ((q = strpbrk (p, delim)) != NULL)
                   2009:   {
                   2010:     *pp = q + 1;
                   2011:     *q = '\0';
                   2012:   }
                   2013:   else
                   2014:     *pp = 0;
                   2015:   return p;
                   2016: }
                   2017: #endif
                   2018: 
1.126     brouard  2019: /********************** nrerror ********************/
                   2020: 
                   2021: void nrerror(char error_text[])
                   2022: {
                   2023:   fprintf(stderr,"ERREUR ...\n");
                   2024:   fprintf(stderr,"%s\n",error_text);
                   2025:   exit(EXIT_FAILURE);
                   2026: }
                   2027: /*********************** vector *******************/
                   2028: double *vector(int nl, int nh)
                   2029: {
                   2030:   double *v;
                   2031:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   2032:   if (!v) nrerror("allocation failure in vector");
                   2033:   return v-nl+NR_END;
                   2034: }
                   2035: 
                   2036: /************************ free vector ******************/
                   2037: void free_vector(double*v, int nl, int nh)
                   2038: {
                   2039:   free((FREE_ARG)(v+nl-NR_END));
                   2040: }
                   2041: 
                   2042: /************************ivector *******************************/
                   2043: int *ivector(long nl,long nh)
                   2044: {
                   2045:   int *v;
                   2046:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   2047:   if (!v) nrerror("allocation failure in ivector");
                   2048:   return v-nl+NR_END;
                   2049: }
                   2050: 
                   2051: /******************free ivector **************************/
                   2052: void free_ivector(int *v, long nl, long nh)
                   2053: {
                   2054:   free((FREE_ARG)(v+nl-NR_END));
                   2055: }
                   2056: 
                   2057: /************************lvector *******************************/
                   2058: long *lvector(long nl,long nh)
                   2059: {
                   2060:   long *v;
                   2061:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   2062:   if (!v) nrerror("allocation failure in ivector");
                   2063:   return v-nl+NR_END;
                   2064: }
                   2065: 
                   2066: /******************free lvector **************************/
                   2067: void free_lvector(long *v, long nl, long nh)
                   2068: {
                   2069:   free((FREE_ARG)(v+nl-NR_END));
                   2070: }
                   2071: 
                   2072: /******************* imatrix *******************************/
                   2073: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   2074:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   2075: { 
                   2076:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   2077:   int **m; 
                   2078:   
                   2079:   /* allocate pointers to rows */ 
                   2080:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   2081:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   2082:   m += NR_END; 
                   2083:   m -= nrl; 
                   2084:   
                   2085:   
                   2086:   /* allocate rows and set pointers to them */ 
                   2087:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   2088:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   2089:   m[nrl] += NR_END; 
                   2090:   m[nrl] -= ncl; 
                   2091:   
                   2092:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   2093:   
                   2094:   /* return pointer to array of pointers to rows */ 
                   2095:   return m; 
                   2096: } 
                   2097: 
                   2098: /****************** free_imatrix *************************/
                   2099: void free_imatrix(m,nrl,nrh,ncl,nch)
                   2100:       int **m;
                   2101:       long nch,ncl,nrh,nrl; 
                   2102:      /* free an int matrix allocated by imatrix() */ 
                   2103: { 
                   2104:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   2105:   free((FREE_ARG) (m+nrl-NR_END)); 
                   2106: } 
                   2107: 
                   2108: /******************* matrix *******************************/
                   2109: double **matrix(long nrl, long nrh, long ncl, long nch)
                   2110: {
                   2111:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   2112:   double **m;
                   2113: 
                   2114:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2115:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2116:   m += NR_END;
                   2117:   m -= nrl;
                   2118: 
                   2119:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2120:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2121:   m[nrl] += NR_END;
                   2122:   m[nrl] -= ncl;
                   2123: 
                   2124:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2125:   return m;
1.145     brouard  2126:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   2127: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   2128: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  2129:    */
                   2130: }
                   2131: 
                   2132: /*************************free matrix ************************/
                   2133: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   2134: {
                   2135:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2136:   free((FREE_ARG)(m+nrl-NR_END));
                   2137: }
                   2138: 
                   2139: /******************* ma3x *******************************/
                   2140: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   2141: {
                   2142:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   2143:   double ***m;
                   2144: 
                   2145:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2146:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2147:   m += NR_END;
                   2148:   m -= nrl;
                   2149: 
                   2150:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2151:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2152:   m[nrl] += NR_END;
                   2153:   m[nrl] -= ncl;
                   2154: 
                   2155:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2156: 
                   2157:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   2158:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   2159:   m[nrl][ncl] += NR_END;
                   2160:   m[nrl][ncl] -= nll;
                   2161:   for (j=ncl+1; j<=nch; j++) 
                   2162:     m[nrl][j]=m[nrl][j-1]+nlay;
                   2163:   
                   2164:   for (i=nrl+1; i<=nrh; i++) {
                   2165:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   2166:     for (j=ncl+1; j<=nch; j++) 
                   2167:       m[i][j]=m[i][j-1]+nlay;
                   2168:   }
                   2169:   return m; 
                   2170:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   2171:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   2172:   */
                   2173: }
                   2174: 
                   2175: /*************************free ma3x ************************/
                   2176: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   2177: {
                   2178:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   2179:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2180:   free((FREE_ARG)(m+nrl-NR_END));
                   2181: }
                   2182: 
                   2183: /*************** function subdirf ***********/
                   2184: char *subdirf(char fileres[])
                   2185: {
                   2186:   /* Caution optionfilefiname is hidden */
                   2187:   strcpy(tmpout,optionfilefiname);
                   2188:   strcat(tmpout,"/"); /* Add to the right */
                   2189:   strcat(tmpout,fileres);
                   2190:   return tmpout;
                   2191: }
                   2192: 
                   2193: /*************** function subdirf2 ***********/
                   2194: char *subdirf2(char fileres[], char *preop)
                   2195: {
1.314     brouard  2196:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
                   2197:  Errors in subdirf, 2, 3 while printing tmpout is
1.315     brouard  2198:  rewritten within the same printf. Workaround: many printfs */
1.126     brouard  2199:   /* Caution optionfilefiname is hidden */
                   2200:   strcpy(tmpout,optionfilefiname);
                   2201:   strcat(tmpout,"/");
                   2202:   strcat(tmpout,preop);
                   2203:   strcat(tmpout,fileres);
                   2204:   return tmpout;
                   2205: }
                   2206: 
                   2207: /*************** function subdirf3 ***********/
                   2208: char *subdirf3(char fileres[], char *preop, char *preop2)
                   2209: {
                   2210:   
                   2211:   /* Caution optionfilefiname is hidden */
                   2212:   strcpy(tmpout,optionfilefiname);
                   2213:   strcat(tmpout,"/");
                   2214:   strcat(tmpout,preop);
                   2215:   strcat(tmpout,preop2);
                   2216:   strcat(tmpout,fileres);
                   2217:   return tmpout;
                   2218: }
1.213     brouard  2219:  
                   2220: /*************** function subdirfext ***********/
                   2221: char *subdirfext(char fileres[], char *preop, char *postop)
                   2222: {
                   2223:   
                   2224:   strcpy(tmpout,preop);
                   2225:   strcat(tmpout,fileres);
                   2226:   strcat(tmpout,postop);
                   2227:   return tmpout;
                   2228: }
1.126     brouard  2229: 
1.213     brouard  2230: /*************** function subdirfext3 ***********/
                   2231: char *subdirfext3(char fileres[], char *preop, char *postop)
                   2232: {
                   2233:   
                   2234:   /* Caution optionfilefiname is hidden */
                   2235:   strcpy(tmpout,optionfilefiname);
                   2236:   strcat(tmpout,"/");
                   2237:   strcat(tmpout,preop);
                   2238:   strcat(tmpout,fileres);
                   2239:   strcat(tmpout,postop);
                   2240:   return tmpout;
                   2241: }
                   2242:  
1.162     brouard  2243: char *asc_diff_time(long time_sec, char ascdiff[])
                   2244: {
                   2245:   long sec_left, days, hours, minutes;
                   2246:   days = (time_sec) / (60*60*24);
                   2247:   sec_left = (time_sec) % (60*60*24);
                   2248:   hours = (sec_left) / (60*60) ;
                   2249:   sec_left = (sec_left) %(60*60);
                   2250:   minutes = (sec_left) /60;
                   2251:   sec_left = (sec_left) % (60);
                   2252:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   2253:   return ascdiff;
                   2254: }
                   2255: 
1.126     brouard  2256: /***************** f1dim *************************/
                   2257: extern int ncom; 
                   2258: extern double *pcom,*xicom;
                   2259: extern double (*nrfunc)(double []); 
                   2260:  
                   2261: double f1dim(double x) 
                   2262: { 
                   2263:   int j; 
                   2264:   double f;
                   2265:   double *xt; 
                   2266:  
                   2267:   xt=vector(1,ncom); 
                   2268:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   2269:   f=(*nrfunc)(xt); 
                   2270:   free_vector(xt,1,ncom); 
                   2271:   return f; 
                   2272: } 
                   2273: 
                   2274: /*****************brent *************************/
                   2275: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  2276: {
                   2277:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   2278:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   2279:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   2280:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   2281:    * returned function value. 
                   2282:   */
1.126     brouard  2283:   int iter; 
                   2284:   double a,b,d,etemp;
1.159     brouard  2285:   double fu=0,fv,fw,fx;
1.164     brouard  2286:   double ftemp=0.;
1.126     brouard  2287:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   2288:   double e=0.0; 
                   2289:  
                   2290:   a=(ax < cx ? ax : cx); 
                   2291:   b=(ax > cx ? ax : cx); 
                   2292:   x=w=v=bx; 
                   2293:   fw=fv=fx=(*f)(x); 
                   2294:   for (iter=1;iter<=ITMAX;iter++) { 
                   2295:     xm=0.5*(a+b); 
                   2296:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   2297:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   2298:     printf(".");fflush(stdout);
                   2299:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  2300: #ifdef DEBUGBRENT
1.126     brouard  2301:     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);
                   2302:     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);
                   2303:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   2304: #endif
                   2305:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   2306:       *xmin=x; 
                   2307:       return fx; 
                   2308:     } 
                   2309:     ftemp=fu;
                   2310:     if (fabs(e) > tol1) { 
                   2311:       r=(x-w)*(fx-fv); 
                   2312:       q=(x-v)*(fx-fw); 
                   2313:       p=(x-v)*q-(x-w)*r; 
                   2314:       q=2.0*(q-r); 
                   2315:       if (q > 0.0) p = -p; 
                   2316:       q=fabs(q); 
                   2317:       etemp=e; 
                   2318:       e=d; 
                   2319:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  2320:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  2321:       else { 
1.224     brouard  2322:                                d=p/q; 
                   2323:                                u=x+d; 
                   2324:                                if (u-a < tol2 || b-u < tol2) 
                   2325:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  2326:       } 
                   2327:     } else { 
                   2328:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2329:     } 
                   2330:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   2331:     fu=(*f)(u); 
                   2332:     if (fu <= fx) { 
                   2333:       if (u >= x) a=x; else b=x; 
                   2334:       SHFT(v,w,x,u) 
1.183     brouard  2335:       SHFT(fv,fw,fx,fu) 
                   2336:     } else { 
                   2337:       if (u < x) a=u; else b=u; 
                   2338:       if (fu <= fw || w == x) { 
1.224     brouard  2339:                                v=w; 
                   2340:                                w=u; 
                   2341:                                fv=fw; 
                   2342:                                fw=fu; 
1.183     brouard  2343:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  2344:                                v=u; 
                   2345:                                fv=fu; 
1.183     brouard  2346:       } 
                   2347:     } 
1.126     brouard  2348:   } 
                   2349:   nrerror("Too many iterations in brent"); 
                   2350:   *xmin=x; 
                   2351:   return fx; 
                   2352: } 
                   2353: 
                   2354: /****************** mnbrak ***********************/
                   2355: 
                   2356: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2357:            double (*func)(double)) 
1.183     brouard  2358: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2359: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2360: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2361: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2362:    */
1.126     brouard  2363:   double ulim,u,r,q, dum;
                   2364:   double fu; 
1.187     brouard  2365: 
                   2366:   double scale=10.;
                   2367:   int iterscale=0;
                   2368: 
                   2369:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2370:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2371: 
                   2372: 
                   2373:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2374:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2375:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2376:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2377:   /* } */
                   2378: 
1.126     brouard  2379:   if (*fb > *fa) { 
                   2380:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2381:     SHFT(dum,*fb,*fa,dum) 
                   2382:   } 
1.126     brouard  2383:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2384:   *fc=(*func)(*cx); 
1.183     brouard  2385: #ifdef DEBUG
1.224     brouard  2386:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2387:   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  2388: #endif
1.224     brouard  2389:   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  2390:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2391:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2392:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2393:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2394:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2395:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2396:       fu=(*func)(u); 
1.163     brouard  2397: #ifdef DEBUG
                   2398:       /* f(x)=A(x-u)**2+f(u) */
                   2399:       double A, fparabu; 
                   2400:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2401:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2402:       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);
                   2403:       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  2404:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2405:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2406:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2407:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2408: #endif 
1.184     brouard  2409: #ifdef MNBRAKORIGINAL
1.183     brouard  2410: #else
1.191     brouard  2411: /*       if (fu > *fc) { */
                   2412: /* #ifdef DEBUG */
                   2413: /*       printf("mnbrak4  fu > fc \n"); */
                   2414: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2415: /* #endif */
                   2416: /*     /\* 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 *\\/  *\/ */
                   2417: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2418: /*     dum=u; /\* Shifting c and u *\/ */
                   2419: /*     u = *cx; */
                   2420: /*     *cx = dum; */
                   2421: /*     dum = fu; */
                   2422: /*     fu = *fc; */
                   2423: /*     *fc =dum; */
                   2424: /*       } else { /\* end *\/ */
                   2425: /* #ifdef DEBUG */
                   2426: /*       printf("mnbrak3  fu < fc \n"); */
                   2427: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2428: /* #endif */
                   2429: /*     dum=u; /\* Shifting c and u *\/ */
                   2430: /*     u = *cx; */
                   2431: /*     *cx = dum; */
                   2432: /*     dum = fu; */
                   2433: /*     fu = *fc; */
                   2434: /*     *fc =dum; */
                   2435: /*       } */
1.224     brouard  2436: #ifdef DEBUGMNBRAK
                   2437:                 double A, fparabu; 
                   2438:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2439:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2440:      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);
                   2441:      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  2442: #endif
1.191     brouard  2443:       dum=u; /* Shifting c and u */
                   2444:       u = *cx;
                   2445:       *cx = dum;
                   2446:       dum = fu;
                   2447:       fu = *fc;
                   2448:       *fc =dum;
1.183     brouard  2449: #endif
1.162     brouard  2450:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2451: #ifdef DEBUG
1.224     brouard  2452:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2453:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2454: #endif
1.126     brouard  2455:       fu=(*func)(u); 
                   2456:       if (fu < *fc) { 
1.183     brouard  2457: #ifdef DEBUG
1.224     brouard  2458:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2459:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2460: #endif
                   2461:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2462:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2463: #ifdef DEBUG
                   2464:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2465: #endif
                   2466:       } 
1.162     brouard  2467:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2468: #ifdef DEBUG
1.224     brouard  2469:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2470:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2471: #endif
1.126     brouard  2472:       u=ulim; 
                   2473:       fu=(*func)(u); 
1.183     brouard  2474:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2475: #ifdef DEBUG
1.224     brouard  2476:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2477:       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  2478: #endif
1.126     brouard  2479:       u=(*cx)+GOLD*(*cx-*bx); 
                   2480:       fu=(*func)(u); 
1.224     brouard  2481: #ifdef DEBUG
                   2482:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2483:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2484: #endif
1.183     brouard  2485:     } /* end tests */
1.126     brouard  2486:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2487:     SHFT(*fa,*fb,*fc,fu) 
                   2488: #ifdef DEBUG
1.224     brouard  2489:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2490:       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  2491: #endif
                   2492:   } /* 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  2493: } 
                   2494: 
                   2495: /*************** linmin ************************/
1.162     brouard  2496: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2497: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2498: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2499: the value of func at the returned location p . This is actually all accomplished by calling the
                   2500: routines mnbrak and brent .*/
1.126     brouard  2501: int ncom; 
                   2502: double *pcom,*xicom;
                   2503: double (*nrfunc)(double []); 
                   2504:  
1.224     brouard  2505: #ifdef LINMINORIGINAL
1.126     brouard  2506: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2507: #else
                   2508: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2509: #endif
1.126     brouard  2510: { 
                   2511:   double brent(double ax, double bx, double cx, 
                   2512:               double (*f)(double), double tol, double *xmin); 
                   2513:   double f1dim(double x); 
                   2514:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2515:              double *fc, double (*func)(double)); 
                   2516:   int j; 
                   2517:   double xx,xmin,bx,ax; 
                   2518:   double fx,fb,fa;
1.187     brouard  2519: 
1.203     brouard  2520: #ifdef LINMINORIGINAL
                   2521: #else
                   2522:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2523: #endif
                   2524:   
1.126     brouard  2525:   ncom=n; 
                   2526:   pcom=vector(1,n); 
                   2527:   xicom=vector(1,n); 
                   2528:   nrfunc=func; 
                   2529:   for (j=1;j<=n;j++) { 
                   2530:     pcom[j]=p[j]; 
1.202     brouard  2531:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2532:   } 
1.187     brouard  2533: 
1.203     brouard  2534: #ifdef LINMINORIGINAL
                   2535:   xx=1.;
                   2536: #else
                   2537:   axs=0.0;
                   2538:   xxs=1.;
                   2539:   do{
                   2540:     xx= xxs;
                   2541: #endif
1.187     brouard  2542:     ax=0.;
                   2543:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2544:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2545:     /* 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))   */
                   2546:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2547:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2548:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2549:     /* 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  2550: #ifdef LINMINORIGINAL
                   2551: #else
                   2552:     if (fx != fx){
1.224     brouard  2553:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2554:                        printf("|");
                   2555:                        fprintf(ficlog,"|");
1.203     brouard  2556: #ifdef DEBUGLINMIN
1.224     brouard  2557:                        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  2558: #endif
                   2559:     }
1.224     brouard  2560:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2561: #endif
                   2562:   
1.191     brouard  2563: #ifdef DEBUGLINMIN
                   2564:   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  2565:   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  2566: #endif
1.224     brouard  2567: #ifdef LINMINORIGINAL
                   2568: #else
1.317     brouard  2569:   if(fb == fx){ /* Flat function in the direction */
                   2570:     xmin=xx;
1.224     brouard  2571:     *flat=1;
1.317     brouard  2572:   }else{
1.224     brouard  2573:     *flat=0;
                   2574: #endif
                   2575:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2576:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2577:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2578:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2579:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2580:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2581: #ifdef DEBUG
1.224     brouard  2582:   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);
                   2583:   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);
                   2584: #endif
                   2585: #ifdef LINMINORIGINAL
                   2586: #else
                   2587:                        }
1.126     brouard  2588: #endif
1.191     brouard  2589: #ifdef DEBUGLINMIN
                   2590:   printf("linmin end ");
1.202     brouard  2591:   fprintf(ficlog,"linmin end ");
1.191     brouard  2592: #endif
1.126     brouard  2593:   for (j=1;j<=n;j++) { 
1.203     brouard  2594: #ifdef LINMINORIGINAL
                   2595:     xi[j] *= xmin; 
                   2596: #else
                   2597: #ifdef DEBUGLINMIN
                   2598:     if(xxs <1.0)
                   2599:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2600: #endif
                   2601:     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) */
                   2602: #ifdef DEBUGLINMIN
                   2603:     if(xxs <1.0)
                   2604:       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 );
                   2605: #endif
                   2606: #endif
1.187     brouard  2607:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2608:   } 
1.191     brouard  2609: #ifdef DEBUGLINMIN
1.203     brouard  2610:   printf("\n");
1.191     brouard  2611:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2612:   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  2613:   for (j=1;j<=n;j++) { 
1.202     brouard  2614:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2615:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2616:     if(j % ncovmodel == 0){
1.191     brouard  2617:       printf("\n");
1.202     brouard  2618:       fprintf(ficlog,"\n");
                   2619:     }
1.191     brouard  2620:   }
1.203     brouard  2621: #else
1.191     brouard  2622: #endif
1.126     brouard  2623:   free_vector(xicom,1,n); 
                   2624:   free_vector(pcom,1,n); 
                   2625: } 
                   2626: 
                   2627: 
                   2628: /*************** powell ************************/
1.162     brouard  2629: /*
1.317     brouard  2630: Minimization of a function func of n variables. Input consists in an initial starting point
                   2631: p[1..n] ; an initial matrix xi[1..n][1..n]  whose columns contain the initial set of di-
                   2632: rections (usually the n unit vectors); and ftol, the fractional tolerance in the function value
                   2633: such that failure to decrease by more than this amount in one iteration signals doneness. On
1.162     brouard  2634: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2635: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2636:  */
1.224     brouard  2637: #ifdef LINMINORIGINAL
                   2638: #else
                   2639:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2640:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2641: #endif
1.126     brouard  2642: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2643:            double (*func)(double [])) 
                   2644: { 
1.224     brouard  2645: #ifdef LINMINORIGINAL
                   2646:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2647:              double (*func)(double [])); 
1.224     brouard  2648: #else 
1.241     brouard  2649:  void linmin(double p[], double xi[], int n, double *fret,
                   2650:             double (*func)(double []),int *flat); 
1.224     brouard  2651: #endif
1.239     brouard  2652:  int i,ibig,j,jk,k; 
1.126     brouard  2653:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2654:   double directest;
1.126     brouard  2655:   double fp,fptt;
                   2656:   double *xits;
                   2657:   int niterf, itmp;
1.349     brouard  2658:   int Bigter=0, nBigterf=1;
                   2659:   
1.126     brouard  2660:   pt=vector(1,n); 
                   2661:   ptt=vector(1,n); 
                   2662:   xit=vector(1,n); 
                   2663:   xits=vector(1,n); 
                   2664:   *fret=(*func)(p); 
                   2665:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.338     brouard  2666:   rcurr_time = time(NULL);
                   2667:   fp=(*fret); /* Initialisation */
1.126     brouard  2668:   for (*iter=1;;++(*iter)) { 
                   2669:     ibig=0; 
                   2670:     del=0.0; 
1.157     brouard  2671:     rlast_time=rcurr_time;
1.349     brouard  2672:     rlast_btime=rcurr_time;
1.157     brouard  2673:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2674:     rcurr_time = time(NULL);  
                   2675:     curr_time = *localtime(&rcurr_time);
1.337     brouard  2676:     /* 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); */
                   2677:     /* 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); */
1.349     brouard  2678:     Bigter=(*iter - *iter % ncovmodel)/ncovmodel +1; /* Big iteration, i.e on ncovmodel cycle */
                   2679:     printf("\nPowell iter=%d Big Iter=%d -2*LL=%.12f gain=%.3lg %ld sec. %ld sec.",*iter,Bigter,*fret,fp-*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   2680:     fprintf(ficlog,"\nPowell iter=%d Big Iter=%d -2*LL=%.12f gain=%.3lg %ld sec. %ld sec.",*iter,Bigter,*fret,fp-*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   2681:     fprintf(ficrespow,"%d %d %.12f %d",*iter,Bigter, *fret,curr_time.tm_sec-start_time.tm_sec);
1.324     brouard  2682:     fp=(*fret); /* From former iteration or initial value */
1.192     brouard  2683:     for (i=1;i<=n;i++) {
1.126     brouard  2684:       fprintf(ficrespow," %.12lf", p[i]);
                   2685:     }
1.239     brouard  2686:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2687:     printf("\n#model=  1      +     age ");
                   2688:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2689:     if(nagesqr==1){
1.241     brouard  2690:        printf("  + age*age  ");
                   2691:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2692:     }
                   2693:     for(j=1;j <=ncovmodel-2;j++){
                   2694:       if(Typevar[j]==0) {
                   2695:        printf("  +      V%d  ",Tvar[j]);
                   2696:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2697:       }else if(Typevar[j]==1) {
                   2698:        printf("  +    V%d*age ",Tvar[j]);
                   2699:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2700:       }else if(Typevar[j]==2) {
                   2701:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2702:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  2703:       }else if(Typevar[j]==3) {
                   2704:        printf("  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2705:        fprintf(ficlog,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.239     brouard  2706:       }
                   2707:     }
1.126     brouard  2708:     printf("\n");
1.239     brouard  2709: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2710: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2711:     fprintf(ficlog,"\n");
1.239     brouard  2712:     for(i=1,jk=1; i <=nlstate; i++){
                   2713:       for(k=1; k <=(nlstate+ndeath); k++){
                   2714:        if (k != i) {
                   2715:          printf("%d%d ",i,k);
                   2716:          fprintf(ficlog,"%d%d ",i,k);
                   2717:          for(j=1; j <=ncovmodel; j++){
                   2718:            printf("%12.7f ",p[jk]);
                   2719:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2720:            jk++; 
                   2721:          }
                   2722:          printf("\n");
                   2723:          fprintf(ficlog,"\n");
                   2724:        }
                   2725:       }
                   2726:     }
1.241     brouard  2727:     if(*iter <=3 && *iter >1){
1.157     brouard  2728:       tml = *localtime(&rcurr_time);
                   2729:       strcpy(strcurr,asctime(&tml));
                   2730:       rforecast_time=rcurr_time; 
1.126     brouard  2731:       itmp = strlen(strcurr);
                   2732:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2733:        strcurr[itmp-1]='\0';
1.162     brouard  2734:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2735:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.349     brouard  2736:       for(nBigterf=1;nBigterf<=31;nBigterf+=10){
                   2737:        niterf=nBigterf*ncovmodel;
                   2738:        /* rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time); */
1.241     brouard  2739:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2740:        forecast_time = *localtime(&rforecast_time);
                   2741:        strcpy(strfor,asctime(&forecast_time));
                   2742:        itmp = strlen(strfor);
                   2743:        if(strfor[itmp-1]=='\n')
                   2744:          strfor[itmp-1]='\0';
1.349     brouard  2745:        printf("   - if your program needs %d BIG iterations (%d iterations) to converge, convergence will be \n   reached in %s i.e.\n   on %s (current time is %s);\n",nBigterf, niterf, asc_diff_time(rforecast_time-rcurr_time,tmpout),strfor,strcurr);
                   2746:        fprintf(ficlog,"   - if your program needs %d BIG iterations  (%d iterations) to converge, convergence will be \n   reached in %s i.e.\n   on %s (current time is %s);\n",nBigterf, niterf, asc_diff_time(rforecast_time-rcurr_time,tmpout),strfor,strcurr);
1.126     brouard  2747:       }
                   2748:     }
1.187     brouard  2749:     for (i=1;i<=n;i++) { /* For each direction i */
                   2750:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2751:       fptt=(*fret); 
                   2752: #ifdef DEBUG
1.203     brouard  2753:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2754:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2755: #endif
1.203     brouard  2756:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2757:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2758: #ifdef LINMINORIGINAL
1.357   ! brouard  2759:       linmin(p,xit,n,fret,func); /* New point i minimizing in direction i has coordinates p[j].*/
        !          2760:       /* xit[j] gives the n coordinates of direction i as input.*/
        !          2761:       /* *fret gives the maximum value on direction xit */
1.224     brouard  2762: #else
                   2763:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2764:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2765: #endif
                   2766:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2767:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2768:                                /* because that direction will be replaced unless the gain del is small */
                   2769:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2770:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2771:                                /* with the new direction. */
                   2772:                                del=fabs(fptt-(*fret)); 
                   2773:                                ibig=i; 
1.126     brouard  2774:       } 
                   2775: #ifdef DEBUG
                   2776:       printf("%d %.12e",i,(*fret));
                   2777:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2778:       for (j=1;j<=n;j++) {
1.224     brouard  2779:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2780:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2781:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2782:       }
                   2783:       for(j=1;j<=n;j++) {
1.225     brouard  2784:                                printf(" p(%d)=%.12e",j,p[j]);
                   2785:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2786:       }
                   2787:       printf("\n");
                   2788:       fprintf(ficlog,"\n");
                   2789: #endif
1.187     brouard  2790:     } /* end loop on each direction i */
1.357   ! brouard  2791:     /* Convergence test will use last linmin estimation (fret) and compare to former iteration (fp) */ 
1.188     brouard  2792:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.319     brouard  2793:     for(j=1;j<=n;j++) {
                   2794:       if(flatdir[j] >0){
                   2795:         printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2796:         fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
1.302     brouard  2797:       }
1.319     brouard  2798:       /* printf("\n"); */
                   2799:       /* fprintf(ficlog,"\n"); */
                   2800:     }
1.243     brouard  2801:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2802:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2803:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2804:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2805:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2806:       /* decreased of more than 3.84  */
                   2807:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2808:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2809:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2810:                        
1.188     brouard  2811:       /* Starting the program with initial values given by a former maximization will simply change */
                   2812:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2813:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2814:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2815: #ifdef DEBUG
                   2816:       int k[2],l;
                   2817:       k[0]=1;
                   2818:       k[1]=-1;
                   2819:       printf("Max: %.12e",(*func)(p));
                   2820:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2821:       for (j=1;j<=n;j++) {
                   2822:        printf(" %.12e",p[j]);
                   2823:        fprintf(ficlog," %.12e",p[j]);
                   2824:       }
                   2825:       printf("\n");
                   2826:       fprintf(ficlog,"\n");
                   2827:       for(l=0;l<=1;l++) {
                   2828:        for (j=1;j<=n;j++) {
                   2829:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2830:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2831:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2832:        }
                   2833:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2834:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2835:       }
                   2836: #endif
                   2837: 
                   2838:       free_vector(xit,1,n); 
                   2839:       free_vector(xits,1,n); 
                   2840:       free_vector(ptt,1,n); 
                   2841:       free_vector(pt,1,n); 
                   2842:       return; 
1.192     brouard  2843:     } /* enough precision */ 
1.240     brouard  2844:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2845:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2846:       ptt[j]=2.0*p[j]-pt[j]; 
                   2847:       xit[j]=p[j]-pt[j]; 
                   2848:       pt[j]=p[j]; 
                   2849:     } 
1.181     brouard  2850:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2851: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2852:                if (*iter <=4) {
1.225     brouard  2853: #else
                   2854: #endif
1.224     brouard  2855: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2856: #else
1.161     brouard  2857:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2858: #endif
1.162     brouard  2859:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2860:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2861:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2862:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2863:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2864:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2865:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2866:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2867:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2868:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2869:       /* mu² and del² are equal when f3=f1 */
                   2870:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2871:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2872:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2873:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2874: #ifdef NRCORIGINAL
                   2875:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2876: #else
                   2877:       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  2878:       t= t- del*SQR(fp-fptt);
1.183     brouard  2879: #endif
1.202     brouard  2880:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2881: #ifdef DEBUG
1.181     brouard  2882:       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);
                   2883:       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  2884:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2885:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2886:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2887:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2888:       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);
                   2889:       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);
                   2890: #endif
1.183     brouard  2891: #ifdef POWELLORIGINAL
                   2892:       if (t < 0.0) { /* Then we use it for new direction */
                   2893: #else
1.182     brouard  2894:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2895:                                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  2896:         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  2897:         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  2898:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2899:       } 
1.181     brouard  2900:       if (directest < 0.0) { /* Then we use it for new direction */
                   2901: #endif
1.191     brouard  2902: #ifdef DEBUGLINMIN
1.234     brouard  2903:        printf("Before linmin in direction P%d-P0\n",n);
                   2904:        for (j=1;j<=n;j++) {
                   2905:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2906:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2907:          if(j % ncovmodel == 0){
                   2908:            printf("\n");
                   2909:            fprintf(ficlog,"\n");
                   2910:          }
                   2911:        }
1.224     brouard  2912: #endif
                   2913: #ifdef LINMINORIGINAL
1.234     brouard  2914:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2915: #else
1.234     brouard  2916:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2917:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2918: #endif
1.234     brouard  2919:        
1.191     brouard  2920: #ifdef DEBUGLINMIN
1.234     brouard  2921:        for (j=1;j<=n;j++) { 
                   2922:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2923:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2924:          if(j % ncovmodel == 0){
                   2925:            printf("\n");
                   2926:            fprintf(ficlog,"\n");
                   2927:          }
                   2928:        }
1.224     brouard  2929: #endif
1.357   ! brouard  2930: #ifdef POWELLORIGINCONJUGATE
1.234     brouard  2931:        for (j=1;j<=n;j++) { 
                   2932:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2933:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2934:        }
1.357   ! brouard  2935: #else
        !          2936:        for (j=1;j<=n-1;j++) { 
        !          2937:          xi[j][1]=xi[j][j+1]; /* Standard method of conjugate directions */
        !          2938:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
        !          2939:        }
        !          2940: #endif
1.224     brouard  2941: #ifdef LINMINORIGINAL
                   2942: #else
1.234     brouard  2943:        for (j=1, flatd=0;j<=n;j++) {
                   2944:          if(flatdir[j]>0)
                   2945:            flatd++;
                   2946:        }
                   2947:        if(flatd >0){
1.255     brouard  2948:          printf("%d flat directions: ",flatd);
                   2949:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  2950:          for (j=1;j<=n;j++) { 
                   2951:            if(flatdir[j]>0){
                   2952:              printf("%d ",j);
                   2953:              fprintf(ficlog,"%d ",j);
                   2954:            }
                   2955:          }
                   2956:          printf("\n");
                   2957:          fprintf(ficlog,"\n");
1.319     brouard  2958: #ifdef FLATSUP
                   2959:           free_vector(xit,1,n); 
                   2960:           free_vector(xits,1,n); 
                   2961:           free_vector(ptt,1,n); 
                   2962:           free_vector(pt,1,n); 
                   2963:           return;
                   2964: #endif
1.234     brouard  2965:        }
1.191     brouard  2966: #endif
1.234     brouard  2967:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2968:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.357   ! brouard  2969:   /* The minimization in direction $\xi_1$ gives $P_1$. From $P_1$ minimization in direction $\xi_2$ gives */
        !          2970:   /* $P_2$. Minimization of line $P_2-P_1$ gives new starting point $P^{(1)}_0$ and direction $\xi_1$ is dropped and replaced by second */
        !          2971:   /* direction $\xi_1^{(1)}=\xi_2$. Also second direction is replaced by new direction $\xi^{(1)}_2=P_2-P_0$. */
        !          2972: 
        !          2973:   /* At the second iteration, starting from $P_0^{(1)}$, minimization amongst $\xi^{(1)}_1$ gives point $P^{(1)}_1$. */
        !          2974:   /* Minimization amongst $\xi^{(1)}_2=(P_2-P_0)$ gives point $P^{(1)}_2$.  As $P^{(2)}_1$ and */
        !          2975:   /* $P^{(1)}_0$ are minimizing in the same direction $P^{(1)}_2 - P^{(1)}_1= P_2-P_0$, directions $P^{(1)}_2-P^{(1)}_0$ */
        !          2976:   /* and $P_2-P_0$ (parallel to $\xi$ and $\xi^c$) are conjugate.  } */
        !          2977: 
1.234     brouard  2978:        
1.126     brouard  2979: #ifdef DEBUG
1.234     brouard  2980:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2981:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2982:        for(j=1;j<=n;j++){
                   2983:          printf(" %lf",xit[j]);
                   2984:          fprintf(ficlog," %lf",xit[j]);
                   2985:        }
                   2986:        printf("\n");
                   2987:        fprintf(ficlog,"\n");
1.126     brouard  2988: #endif
1.192     brouard  2989:       } /* end of t or directest negative */
1.224     brouard  2990: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2991: #else
1.234     brouard  2992:       } /* end if (fptt < fp)  */
1.192     brouard  2993: #endif
1.225     brouard  2994: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2995:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2996: #else
1.224     brouard  2997: #endif
1.234     brouard  2998:                } /* loop iteration */ 
1.126     brouard  2999: } 
1.234     brouard  3000:   
1.126     brouard  3001: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  3002:   
1.235     brouard  3003:   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  3004:   {
1.338     brouard  3005:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij . Nicely done
1.279     brouard  3006:      *   (and selected quantitative values in nres)
                   3007:      *  by left multiplying the unit
                   3008:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   3009:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   3010:      * Wx is row vector: population in state 1, population in state 2, population dead
                   3011:      * or prevalence in state 1, prevalence in state 2, 0
                   3012:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   3013:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   3014:      * Output is prlim.
                   3015:      * Initial matrix pimij 
                   3016:      */
1.206     brouard  3017:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   3018:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   3019:   /*  0,                   0                  , 1} */
                   3020:   /*
                   3021:    * and after some iteration: */
                   3022:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   3023:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   3024:   /*  0,                   0                  , 1} */
                   3025:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   3026:   /* {0.51571254859325999, 0.4842874514067399, */
                   3027:   /*  0.51326036147820708, 0.48673963852179264} */
                   3028:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  3029:     
1.332     brouard  3030:     int i, ii,j,k, k1;
1.209     brouard  3031:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  3032:   /* double **matprod2(); */ /* test */
1.218     brouard  3033:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  3034:   double **newm;
1.209     brouard  3035:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  3036:   int ncvloop=0;
1.288     brouard  3037:   int first=0;
1.169     brouard  3038:   
1.209     brouard  3039:   min=vector(1,nlstate);
                   3040:   max=vector(1,nlstate);
                   3041:   meandiff=vector(1,nlstate);
                   3042: 
1.218     brouard  3043:        /* Starting with matrix unity */
1.126     brouard  3044:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   3045:     for (j=1;j<=nlstate+ndeath;j++){
                   3046:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3047:     }
1.169     brouard  3048:   
                   3049:   cov[1]=1.;
                   3050:   
                   3051:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  3052:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  3053:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  3054:     ncvloop++;
1.126     brouard  3055:     newm=savm;
                   3056:     /* Covariates have to be included here again */
1.138     brouard  3057:     cov[2]=agefin;
1.319     brouard  3058:      if(nagesqr==1){
                   3059:       cov[3]= agefin*agefin;
                   3060:      }
1.332     brouard  3061:      /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   3062:      /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   3063:      for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  3064:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  3065:         cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   3066:        }else{
                   3067:         cov[2+nagesqr+k1]=precov[nres][k1];
                   3068:        }
                   3069:      }/* End of loop on model equation */
                   3070:      
                   3071: /* Start of old code (replaced by a loop on position in the model equation */
                   3072:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only of the model *\/ */
                   3073:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   3074:     /*   /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; *\/ */
                   3075:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TnsdVar[TvarsD[k]])]; */
                   3076:     /*   /\* model = 1 +age + V1*V3 + age*V1 + V2 + V1 + age*V2 + V3 + V3*age + V1*V2  */
                   3077:     /*    * k                  1        2      3    4      5      6     7        8 */
                   3078:     /*    *cov[]   1    2      3        4      5    6      7      8     9       10 */
                   3079:     /*    *TypeVar[k]          2        1      0    0      1      0     1        2 */
                   3080:     /*    *Dummy[k]            0        2      0    0      2      0     2        0 */
                   3081:     /*    *Tvar[k]             4        1      2    1      2      3     3        5 */
                   3082:     /*    *nsd=3                              (1)  (2)           (3) */
                   3083:     /*    *TvarsD[nsd]                      [1]=2    1             3 */
                   3084:     /*    *TnsdVar                          [2]=2 [1]=1         [3]=3 */
                   3085:     /*    *TvarsDind[nsd](=k)               [1]=3 [2]=4         [3]=6 */
                   3086:     /*    *Tage[]                  [1]=1                  [2]=2      [3]=3 */
                   3087:     /*    *Tvard[]       [1][1]=1                                           [2][1]=1 */
                   3088:     /*    *                   [1][2]=3                                           [2][2]=2 */
                   3089:     /*    *Tprod[](=k)     [1]=1                                              [2]=8 */
                   3090:     /*    *TvarsDp(=Tvar)   [1]=1            [2]=2             [3]=3          [4]=5 */
                   3091:     /*    *TvarD (=k)       [1]=1            [2]=3 [3]=4       [3]=6          [4]=6 */
                   3092:     /*    *TvarsDpType */
                   3093:     /*    *si model= 1 + age + V3 + V2*age + V2 + V3*age */
                   3094:     /*    * nsd=1              (1)           (2) */
                   3095:     /*    *TvarsD[nsd]          3             2 */
                   3096:     /*    *TnsdVar           (3)=1          (2)=2 */
                   3097:     /*    *TvarsDind[nsd](=k)  [1]=1        [2]=3 */
                   3098:     /*    *Tage[]                  [1]=2           [2]= 3    */
                   3099:     /*    *\/ */
                   3100:     /*   /\* cov[++k1]=nbcode[TvarsD[k]][codtabm(ij,k)]; *\/ */
                   3101:     /*   /\* 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)); *\/ */
                   3102:     /* } */
                   3103:     /* for (k=1; k<=nsq;k++) { /\* For single quantitative varying covariates only of the model *\/ */
                   3104:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3105:     /*   /\* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 *\/ */
                   3106:     /*   /\* cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   3107:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][resultmodel[nres][k1]] */
                   3108:     /*   /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   3109:     /*   /\* 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]); *\/ */
                   3110:     /* } */
                   3111:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   3112:     /*   if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   3113:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3114:     /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   3115:     /*   } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   3116:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   3117:     /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   3118:     /*   } */
                   3119:     /*   /\* 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]); *\/ */
                   3120:     /* } */
                   3121:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   3122:     /*   /\* 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]); *\/ */
                   3123:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3124:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3125:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3126:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3127:     /*         }else{ */
                   3128:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3129:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   3130:     /*         } */
                   3131:     /*   }else{ */
                   3132:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3133:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3134:     /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   3135:     /*         }else{ */
                   3136:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3137:     /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   3138:     /*         } */
                   3139:     /*   } */
                   3140:     /* } /\* End product without age *\/ */
                   3141: /* ENd of old code */
1.138     brouard  3142:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3143:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3144:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  3145:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3146:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.319     brouard  3147:     /* age and covariate values of ij are in 'cov' */
1.142     brouard  3148:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  3149:     
1.126     brouard  3150:     savm=oldm;
                   3151:     oldm=newm;
1.209     brouard  3152: 
                   3153:     for(j=1; j<=nlstate; j++){
                   3154:       max[j]=0.;
                   3155:       min[j]=1.;
                   3156:     }
                   3157:     for(i=1;i<=nlstate;i++){
                   3158:       sumnew=0;
                   3159:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   3160:       for(j=1; j<=nlstate; j++){ 
                   3161:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   3162:        max[j]=FMAX(max[j],prlim[i][j]);
                   3163:        min[j]=FMIN(min[j],prlim[i][j]);
                   3164:       }
                   3165:     }
                   3166: 
1.126     brouard  3167:     maxmax=0.;
1.209     brouard  3168:     for(j=1; j<=nlstate; j++){
                   3169:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   3170:       maxmax=FMAX(maxmax,meandiff[j]);
                   3171:       /* 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  3172:     } /* j loop */
1.203     brouard  3173:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  3174:     /* 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  3175:     if(maxmax < ftolpl){
1.209     brouard  3176:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   3177:       free_vector(min,1,nlstate);
                   3178:       free_vector(max,1,nlstate);
                   3179:       free_vector(meandiff,1,nlstate);
1.126     brouard  3180:       return prlim;
                   3181:     }
1.288     brouard  3182:   } /* agefin loop */
1.208     brouard  3183:     /* After some age loop it doesn't converge */
1.288     brouard  3184:   if(!first){
                   3185:     first=1;
                   3186:     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  3187:     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);
                   3188:   }else if (first >=1 && first <10){
                   3189:     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);
                   3190:     first++;
                   3191:   }else if (first ==10){
                   3192:     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);
                   3193:     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");
                   3194:     fprintf(ficlog,"Warning: the stable prevalence no convergence; too many cases, giving up noticing, even in log file\n");
                   3195:     first++;
1.288     brouard  3196:   }
                   3197: 
1.209     brouard  3198:   /* 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); */
                   3199:   free_vector(min,1,nlstate);
                   3200:   free_vector(max,1,nlstate);
                   3201:   free_vector(meandiff,1,nlstate);
1.208     brouard  3202:   
1.169     brouard  3203:   return prlim; /* should not reach here */
1.126     brouard  3204: }
                   3205: 
1.217     brouard  3206: 
                   3207:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   3208: 
1.218     brouard  3209:  /* 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) */
                   3210:  /* 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  3211:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  3212: {
1.264     brouard  3213:   /* 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  3214:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   3215:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   3216:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   3217:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   3218:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   3219:   /* Initial matrix pimij */
                   3220:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   3221:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   3222:   /*  0,                   0                  , 1} */
                   3223:   /*
                   3224:    * and after some iteration: */
                   3225:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   3226:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   3227:   /*  0,                   0                  , 1} */
                   3228:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   3229:   /* {0.51571254859325999, 0.4842874514067399, */
                   3230:   /*  0.51326036147820708, 0.48673963852179264} */
                   3231:   /* If we start from prlim again, prlim tends to a constant matrix */
                   3232: 
1.332     brouard  3233:   int i, ii,j,k, k1;
1.247     brouard  3234:   int first=0;
1.217     brouard  3235:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   3236:   /* double **matprod2(); */ /* test */
                   3237:   double **out, cov[NCOVMAX+1], **bmij();
                   3238:   double **newm;
1.218     brouard  3239:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   3240:   double        **oldm, **savm;  /* for use */
                   3241: 
1.217     brouard  3242:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   3243:   int ncvloop=0;
                   3244:   
                   3245:   min=vector(1,nlstate);
                   3246:   max=vector(1,nlstate);
                   3247:   meandiff=vector(1,nlstate);
                   3248: 
1.266     brouard  3249:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   3250:   oldm=oldms; savm=savms;
                   3251:   
                   3252:   /* Starting with matrix unity */
                   3253:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   3254:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  3255:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3256:     }
                   3257:   
                   3258:   cov[1]=1.;
                   3259:   
                   3260:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3261:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  3262:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  3263:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   3264:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  3265:     ncvloop++;
1.218     brouard  3266:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   3267:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  3268:     /* Covariates have to be included here again */
                   3269:     cov[2]=agefin;
1.319     brouard  3270:     if(nagesqr==1){
1.217     brouard  3271:       cov[3]= agefin*agefin;;
1.319     brouard  3272:     }
1.332     brouard  3273:     for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  3274:       if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  3275:        cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.242     brouard  3276:       }else{
1.332     brouard  3277:        cov[2+nagesqr+k1]=precov[nres][k1];
1.242     brouard  3278:       }
1.332     brouard  3279:     }/* End of loop on model equation */
                   3280: 
                   3281: /* Old code */ 
                   3282: 
                   3283:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   3284:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   3285:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; */
                   3286:     /*   /\* 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)); *\/ */
                   3287:     /* } */
                   3288:     /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   3289:     /* /\*   /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3290:     /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3291:     /* /\*   /\\* 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])]); *\\/ *\/ */
                   3292:     /* /\* } *\/ */
                   3293:     /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3294:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3295:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3296:     /*   /\* 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]); *\/ */
                   3297:     /* } */
                   3298:     /* /\* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; *\/ */
                   3299:     /* /\* for (k=1; k<=cptcovprod;k++) /\\* Useless *\\/ *\/ */
                   3300:     /* /\*   /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\\/ *\/ */
                   3301:     /* /\*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3302:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   3303:     /*   /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age *\\/ ERROR ???*\/ */
                   3304:     /*   if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3305:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3306:     /*   } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3307:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   3308:     /*   } */
                   3309:     /*   /\* 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]); *\/ */
                   3310:     /* } */
                   3311:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   3312:     /*   /\* 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]); *\/ */
                   3313:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3314:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3315:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3316:     /*         }else{ */
                   3317:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3318:     /*         } */
                   3319:     /*   }else{ */
                   3320:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3321:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3322:     /*         }else{ */
                   3323:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3324:     /*         } */
                   3325:     /*   } */
                   3326:     /* } */
1.217     brouard  3327:     
                   3328:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3329:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3330:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   3331:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3332:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  3333:                /* ij should be linked to the correct index of cov */
                   3334:                /* age and covariate values ij are in 'cov', but we need to pass
                   3335:                 * ij for the observed prevalence at age and status and covariate
                   3336:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   3337:                 */
                   3338:     /* 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 *\/ */
                   3339:     /* 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 *\/ */
                   3340:     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  3341:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  3342:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   3343:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   3344:     /*         printf("%d newm= ",i); */
                   3345:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3346:     /*           printf("%f ",newm[i][j]); */
                   3347:     /*         } */
                   3348:     /*         printf("oldm * "); */
                   3349:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3350:     /*           printf("%f ",oldm[i][j]); */
                   3351:     /*         } */
1.268     brouard  3352:     /*         printf(" bmmij "); */
1.266     brouard  3353:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3354:     /*           printf("%f ",pmmij[i][j]); */
                   3355:     /*         } */
                   3356:     /*         printf("\n"); */
                   3357:     /*   } */
                   3358:     /* } */
1.217     brouard  3359:     savm=oldm;
                   3360:     oldm=newm;
1.266     brouard  3361: 
1.217     brouard  3362:     for(j=1; j<=nlstate; j++){
                   3363:       max[j]=0.;
                   3364:       min[j]=1.;
                   3365:     }
                   3366:     for(j=1; j<=nlstate; j++){ 
                   3367:       for(i=1;i<=nlstate;i++){
1.234     brouard  3368:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   3369:        bprlim[i][j]= newm[i][j];
                   3370:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   3371:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  3372:       }
                   3373:     }
1.218     brouard  3374:                
1.217     brouard  3375:     maxmax=0.;
                   3376:     for(i=1; i<=nlstate; i++){
1.318     brouard  3377:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column, could be nan! */
1.217     brouard  3378:       maxmax=FMAX(maxmax,meandiff[i]);
                   3379:       /* 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  3380:     } /* i loop */
1.217     brouard  3381:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  3382:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3383:     if(maxmax < ftolpl){
1.220     brouard  3384:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3385:       free_vector(min,1,nlstate);
                   3386:       free_vector(max,1,nlstate);
                   3387:       free_vector(meandiff,1,nlstate);
                   3388:       return bprlim;
                   3389:     }
1.288     brouard  3390:   } /* agefin loop */
1.217     brouard  3391:     /* After some age loop it doesn't converge */
1.288     brouard  3392:   if(!first){
1.247     brouard  3393:     first=1;
                   3394:     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\
                   3395: 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);
                   3396:   }
                   3397:   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  3398: 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);
                   3399:   /* 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); */
                   3400:   free_vector(min,1,nlstate);
                   3401:   free_vector(max,1,nlstate);
                   3402:   free_vector(meandiff,1,nlstate);
                   3403:   
                   3404:   return bprlim; /* should not reach here */
                   3405: }
                   3406: 
1.126     brouard  3407: /*************** transition probabilities ***************/ 
                   3408: 
                   3409: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   3410: {
1.138     brouard  3411:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  3412:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  3413:      model to the ncovmodel covariates (including constant and age).
                   3414:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3415:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3416:      ncth covariate in the global vector x is given by the formula:
                   3417:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3418:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3419:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3420:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  3421:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  3422:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  3423:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  3424:   */
                   3425:   double s1, lnpijopii;
1.126     brouard  3426:   /*double t34;*/
1.164     brouard  3427:   int i,j, nc, ii, jj;
1.126     brouard  3428: 
1.223     brouard  3429:   for(i=1; i<= nlstate; i++){
                   3430:     for(j=1; j<i;j++){
                   3431:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3432:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3433:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3434:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3435:       }
                   3436:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3437:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3438:     }
                   3439:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3440:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3441:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3442:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3443:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3444:       }
                   3445:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3446:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3447:     }
                   3448:   }
1.218     brouard  3449:   
1.223     brouard  3450:   for(i=1; i<= nlstate; i++){
                   3451:     s1=0;
                   3452:     for(j=1; j<i; j++){
1.339     brouard  3453:       /* printf("debug1 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  3454:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3455:     }
                   3456:     for(j=i+1; j<=nlstate+ndeath; j++){
1.339     brouard  3457:       /* printf("debug2 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  3458:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3459:     }
                   3460:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3461:     ps[i][i]=1./(s1+1.);
                   3462:     /* Computing other pijs */
                   3463:     for(j=1; j<i; j++)
1.325     brouard  3464:       ps[i][j]= exp(ps[i][j])*ps[i][i];/* Bug valgrind */
1.223     brouard  3465:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3466:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3467:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3468:   } /* end i */
1.218     brouard  3469:   
1.223     brouard  3470:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3471:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3472:       ps[ii][jj]=0;
                   3473:       ps[ii][ii]=1;
                   3474:     }
                   3475:   }
1.294     brouard  3476: 
                   3477: 
1.223     brouard  3478:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3479:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3480:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3481:   /*   } */
                   3482:   /*   printf("\n "); */
                   3483:   /* } */
                   3484:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3485:   /*
                   3486:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  3487:                goto end;*/
1.266     brouard  3488:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  3489: }
                   3490: 
1.218     brouard  3491: /*************** backward transition probabilities ***************/ 
                   3492: 
                   3493:  /* 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 ) */
                   3494: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   3495:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   3496: {
1.302     brouard  3497:   /* 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  3498:    * 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  3499:    */
1.218     brouard  3500:   int i, ii, j,k;
1.222     brouard  3501:   
                   3502:   double **out, **pmij();
                   3503:   double sumnew=0.;
1.218     brouard  3504:   double agefin;
1.292     brouard  3505:   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  3506:   double **dnewm, **dsavm, **doldm;
                   3507:   double **bbmij;
                   3508:   
1.218     brouard  3509:   doldm=ddoldms; /* global pointers */
1.222     brouard  3510:   dnewm=ddnewms;
                   3511:   dsavm=ddsavms;
1.318     brouard  3512: 
                   3513:   /* Debug */
                   3514:   /* printf("Bmij ij=%d, cov[2}=%f\n", ij, cov[2]); */
1.222     brouard  3515:   agefin=cov[2];
1.268     brouard  3516:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  3517:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  3518:      the observed prevalence (with this covariate ij) at beginning of transition */
                   3519:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  3520: 
                   3521:   /* P_x */
1.325     brouard  3522:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm *//* Bug valgrind */
1.268     brouard  3523:   /* outputs pmmij which is a stochastic matrix in row */
                   3524: 
                   3525:   /* Diag(w_x) */
1.292     brouard  3526:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  3527:   sumnew=0.;
1.269     brouard  3528:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  3529:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  3530:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  3531:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   3532:   }
                   3533:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   3534:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3535:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  3536:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  3537:     }
                   3538:   }else{
                   3539:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3540:       for (j=1;j<=nlstate+ndeath;j++)
                   3541:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   3542:     }
                   3543:     /* if(sumnew <0.9){ */
                   3544:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   3545:     /* } */
                   3546:   }
                   3547:   k3=0.0;  /* We put the last diagonal to 0 */
                   3548:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   3549:       doldm[ii][ii]= k3;
                   3550:   }
                   3551:   /* End doldm, At the end doldm is diag[(w_i)] */
                   3552:   
1.292     brouard  3553:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   3554:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  3555: 
1.292     brouard  3556:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  3557:   /* 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  3558:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  3559:     sumnew=0.;
1.222     brouard  3560:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  3561:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  3562:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  3563:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  3564:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  3565:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  3566:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3567:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  3568:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3569:        /* }else */
1.268     brouard  3570:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   3571:     } /*End ii */
                   3572:   } /* 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 */
                   3573: 
1.292     brouard  3574:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  3575:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  3576:   /* end bmij */
1.266     brouard  3577:   return ps; /*pointer is unchanged */
1.218     brouard  3578: }
1.217     brouard  3579: /*************** transition probabilities ***************/ 
                   3580: 
1.218     brouard  3581: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  3582: {
                   3583:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3584:      computes the probability to be observed in state j being in state i by appying the
                   3585:      model to the ncovmodel covariates (including constant and age).
                   3586:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3587:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3588:      ncth covariate in the global vector x is given by the formula:
                   3589:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3590:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3591:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3592:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3593:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   3594:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3595:   */
                   3596:   double s1, lnpijopii;
                   3597:   /*double t34;*/
                   3598:   int i,j, nc, ii, jj;
                   3599: 
1.234     brouard  3600:   for(i=1; i<= nlstate; i++){
                   3601:     for(j=1; j<i;j++){
                   3602:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3603:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3604:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3605:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3606:       }
                   3607:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3608:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3609:     }
                   3610:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3611:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3612:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3613:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3614:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3615:       }
                   3616:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3617:     }
                   3618:   }
                   3619:   
                   3620:   for(i=1; i<= nlstate; i++){
                   3621:     s1=0;
                   3622:     for(j=1; j<i; j++){
                   3623:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3624:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3625:     }
                   3626:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3627:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3628:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3629:     }
                   3630:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3631:     ps[i][i]=1./(s1+1.);
                   3632:     /* Computing other pijs */
                   3633:     for(j=1; j<i; j++)
                   3634:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3635:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3636:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3637:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3638:   } /* end i */
                   3639:   
                   3640:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3641:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3642:       ps[ii][jj]=0;
                   3643:       ps[ii][ii]=1;
                   3644:     }
                   3645:   }
1.296     brouard  3646:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  3647:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3648:     s1=0.;
                   3649:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   3650:       s1+=ps[ii][jj];
                   3651:     }
                   3652:     for(ii=1; ii<= nlstate; ii++){
                   3653:       ps[ii][jj]=ps[ii][jj]/s1;
                   3654:     }
                   3655:   }
                   3656:   /* Transposition */
                   3657:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3658:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   3659:       s1=ps[ii][jj];
                   3660:       ps[ii][jj]=ps[jj][ii];
                   3661:       ps[jj][ii]=s1;
                   3662:     }
                   3663:   }
                   3664:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3665:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3666:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3667:   /*   } */
                   3668:   /*   printf("\n "); */
                   3669:   /* } */
                   3670:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3671:   /*
                   3672:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3673:     goto end;*/
                   3674:   return ps;
1.217     brouard  3675: }
                   3676: 
                   3677: 
1.126     brouard  3678: /**************** Product of 2 matrices ******************/
                   3679: 
1.145     brouard  3680: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  3681: {
                   3682:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3683:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3684:   /* in, b, out are matrice of pointers which should have been initialized 
                   3685:      before: only the contents of out is modified. The function returns
                   3686:      a pointer to pointers identical to out */
1.145     brouard  3687:   int i, j, k;
1.126     brouard  3688:   for(i=nrl; i<= nrh; i++)
1.145     brouard  3689:     for(k=ncolol; k<=ncoloh; k++){
                   3690:       out[i][k]=0.;
                   3691:       for(j=ncl; j<=nch; j++)
                   3692:        out[i][k] +=in[i][j]*b[j][k];
                   3693:     }
1.126     brouard  3694:   return out;
                   3695: }
                   3696: 
                   3697: 
                   3698: /************* Higher Matrix Product ***************/
                   3699: 
1.235     brouard  3700: 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  3701: {
1.336     brouard  3702:   /* Already optimized with precov.
                   3703:      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  3704:      'nhstepm*hstepm*stepm' months (i.e. until
                   3705:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3706:      nhstepm*hstepm matrices. 
                   3707:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3708:      (typically every 2 years instead of every month which is too big 
                   3709:      for the memory).
                   3710:      Model is determined by parameters x and covariates have to be 
                   3711:      included manually here. 
                   3712: 
                   3713:      */
                   3714: 
1.330     brouard  3715:   int i, j, d, h, k, k1;
1.131     brouard  3716:   double **out, cov[NCOVMAX+1];
1.126     brouard  3717:   double **newm;
1.187     brouard  3718:   double agexact;
1.214     brouard  3719:   double agebegin, ageend;
1.126     brouard  3720: 
                   3721:   /* Hstepm could be zero and should return the unit matrix */
                   3722:   for (i=1;i<=nlstate+ndeath;i++)
                   3723:     for (j=1;j<=nlstate+ndeath;j++){
                   3724:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3725:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3726:     }
                   3727:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3728:   for(h=1; h <=nhstepm; h++){
                   3729:     for(d=1; d <=hstepm; d++){
                   3730:       newm=savm;
                   3731:       /* Covariates have to be included here again */
                   3732:       cov[1]=1.;
1.214     brouard  3733:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3734:       cov[2]=agexact;
1.319     brouard  3735:       if(nagesqr==1){
1.227     brouard  3736:        cov[3]= agexact*agexact;
1.319     brouard  3737:       }
1.330     brouard  3738:       /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   3739:       /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   3740:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  3741:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  3742:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   3743:        }else{
                   3744:          cov[2+nagesqr+k1]=precov[nres][k1];
                   3745:        }
                   3746:       }/* End of loop on model equation */
                   3747:        /* Old code */ 
                   3748: /*     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /\* Single dummy  *\/ */
                   3749: /* /\*    V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) *\/ */
                   3750: /* /\*       for (k=1; k<=nsd;k++) { /\\* For single dummy covariates only *\\/ *\/ */
                   3751: /* /\* /\\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\\/ *\/ */
                   3752: /*     /\* codtabm(ij,k)  (1 & (ij-1) >> (k-1))+1 *\/ */
                   3753: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3754: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3755: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
                   3756: /* /\*    nsd         1   2                              3 *\/ /\* Counting single dummies covar fixed or tv *\/ */
                   3757: /* /\*TvarsD[nsd]     4   3                              1 *\/ /\* ID of single dummy cova fixed or timevary*\/ */
                   3758: /* /\*TvarsDind[k]    2   3                              9 *\/ /\* position K of single dummy cova *\/ */
                   3759: /*       /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];or [codtabm(ij,TnsdVar[TvarsD[k]] *\/ */
                   3760: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]]; */
                   3761: /*       /\* 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]])); *\/ */
                   3762: /*       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); */
                   3763: /*       printf("hpxij new Dummy precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3764: /*     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /\* Single quantitative variables  *\/ */
                   3765: /*       /\* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline *\/ */
                   3766: /*       cov[2+nagesqr+k1]=Tqresult[nres][resultmodel[nres][k1]];  */
                   3767: /*       /\* for (k=1; k<=nsq;k++) { /\\* For single varying covariates only *\\/ *\/ */
                   3768: /*       /\*   /\\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\\/ *\/ */
                   3769: /*       /\*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   3770: /*       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]]); */
                   3771: /*       printf("hpxij new Quanti precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3772: /*     }else if( Dummy[k1]==2 ){ /\* For dummy with age product *\/ */
                   3773: /*       /\* Tvar[k1] Variable in the age product age*V1 is 1 *\/ */
                   3774: /*       /\* [Tinvresult[nres][V1] is its value in the resultline nres *\/ */
                   3775: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvar[k1]]*cov[2]; */
                   3776: /*       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]); */
                   3777: /*       printf("hpxij new Dummy with age product precov[nres=%d][k1=%d]=%.4f * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3778: 
                   3779: /*       /\* cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];    *\/ */
                   3780: /*       /\* for (k=1; k<=cptcovage;k++){ /\\* For product with age V1+V1*age +V4 +age*V3 *\\/ *\/ */
                   3781: /*       /\* 1+2 Tage[1]=2 TVar[2]=1 Dummy[2]=2, Tage[2]=4 TVar[4]=3 Dummy[4]=3 quant*\/ */
                   3782: /*       /\* *\/ */
1.330     brouard  3783: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3784: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3785: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
1.332     brouard  3786: /* /\*cptcovage=2                   1               2      *\/ */
                   3787: /* /\*Tage[k]=                      5               8      *\/  */
                   3788: /*     }else if( Dummy[k1]==3 ){ /\* For quant with age product *\/ */
                   3789: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];        */
                   3790: /*       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]]); */
                   3791: /*       printf("hpxij new Quanti with age product precov[nres=%d][k1=%d] * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3792: /*       /\* if(Dummy[Tage[k]]== 2){ /\\* dummy with age *\\/ *\/ */
                   3793: /*       /\* /\\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\\* dummy with age *\\\/ *\\/ *\/ */
                   3794: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\\/ *\/ */
                   3795: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\\/ *\/ */
                   3796: /*       /\*   cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\/ */
                   3797: /*       /\*   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); *\/ */
                   3798: /*       /\* } else if(Dummy[Tage[k]]== 3){ /\\* quantitative with age *\\/ *\/ */
                   3799: /*       /\*   cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; *\/ */
                   3800: /*       /\* } *\/ */
                   3801: /*       /\* 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]); *\/ */
                   3802: /*     }else if(Typevar[k1]==2 ){ /\* For product (not with age) *\/ */
                   3803: /* /\*       for (k=1; k<=cptcovprod;k++){ /\\*  For product without age *\\/ *\/ */
                   3804: /* /\* /\\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\\/ *\/ */
                   3805: /* /\* /\\*    k        1  2   3   4     5    6    7     8    9 *\\/ *\/ */
                   3806: /* /\* /\\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\\/ *\/ */
                   3807: /* /\* /\\*cptcovprod=1            1               2            *\\/ *\/ */
                   3808: /* /\* /\\*Tprod[]=                4               7            *\\/ *\/ */
                   3809: /* /\* /\\*Tvard[][1]             4               1             *\\/ *\/ */
                   3810: /* /\* /\\*Tvard[][2]               3               2           *\\/ *\/ */
1.330     brouard  3811:          
1.332     brouard  3812: /*       /\* 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])]); *\/ */
                   3813: /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3814: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];     */
                   3815: /*       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]]); */
                   3816: /*       printf("hpxij new Product no age product precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3817: 
                   3818: /*       /\* if(Dummy[Tvardk[k1][1]]==0){ *\/ */
                   3819: /*       /\*   if(Dummy[Tvardk[k1][2]]==0){ /\\* Product of dummies *\\/ *\/ */
                   3820: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3821: /*           /\* cov[2+nagesqr+k1]=Tinvresult[nres][Tvardk[k1][1]] * Tinvresult[nres][Tvardk[k1][2]];   *\/ */
                   3822: /*           /\* 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]])]; *\/ */
                   3823: /*         /\* }else{ /\\* Product of dummy by quantitative *\\/ *\/ */
                   3824: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,TnsdVar[Tvard[k][1]])] * Tqresult[nres][k]; *\/ */
                   3825: /*           /\* cov[2+nagesqr+k1]=Tresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]; *\/ */
                   3826: /*       /\*   } *\/ */
                   3827: /*       /\* }else{ /\\* Product of quantitative by...*\\/ *\/ */
                   3828: /*       /\*   if(Dummy[Tvard[k][2]]==0){  /\\* quant by dummy *\\/ *\/ */
                   3829: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][Tvard[k][1]]; *\\/ *\/ */
                   3830: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3831: /*       /\*   }else{ /\\* Product of two quant *\\/ *\/ */
                   3832: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\\/ *\/ */
                   3833: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3834: /*       /\*   } *\/ */
                   3835: /*       /\* }/\\*end of products quantitative *\\/ *\/ */
                   3836: /*     }/\*end of products *\/ */
                   3837:       /* } /\* End of loop on model equation *\/ */
1.235     brouard  3838:       /* for (k=1; k<=cptcovn;k++)  */
                   3839:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3840:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3841:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3842:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3843:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3844:       
                   3845:       
1.126     brouard  3846:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3847:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.319     brouard  3848:       /* right multiplication of oldm by the current matrix */
1.126     brouard  3849:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3850:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3851:       /* if((int)age == 70){ */
                   3852:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3853:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3854:       /*         printf("%d pmmij ",i); */
                   3855:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3856:       /*           printf("%f ",pmmij[i][j]); */
                   3857:       /*         } */
                   3858:       /*         printf(" oldm "); */
                   3859:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3860:       /*           printf("%f ",oldm[i][j]); */
                   3861:       /*         } */
                   3862:       /*         printf("\n"); */
                   3863:       /*       } */
                   3864:       /* } */
1.126     brouard  3865:       savm=oldm;
                   3866:       oldm=newm;
                   3867:     }
                   3868:     for(i=1; i<=nlstate+ndeath; i++)
                   3869:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  3870:        po[i][j][h]=newm[i][j];
                   3871:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3872:       }
1.128     brouard  3873:     /*printf("h=%d ",h);*/
1.126     brouard  3874:   } /* end h */
1.267     brouard  3875:   /*     printf("\n H=%d \n",h); */
1.126     brouard  3876:   return po;
                   3877: }
                   3878: 
1.217     brouard  3879: /************* Higher Back Matrix Product ***************/
1.218     brouard  3880: /* 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  3881: 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  3882: {
1.332     brouard  3883:   /* For dummy covariates given in each resultline (for historical, computes the corresponding combination ij),
                   3884:      computes the transition matrix starting at age 'age' over
1.217     brouard  3885:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3886:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3887:      nhstepm*hstepm matrices.
                   3888:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3889:      (typically every 2 years instead of every month which is too big
1.217     brouard  3890:      for the memory).
1.218     brouard  3891:      Model is determined by parameters x and covariates have to be
1.266     brouard  3892:      included manually here. Then we use a call to bmij(x and cov)
                   3893:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  3894:   */
1.217     brouard  3895: 
1.332     brouard  3896:   int i, j, d, h, k, k1;
1.266     brouard  3897:   double **out, cov[NCOVMAX+1], **bmij();
                   3898:   double **newm, ***newmm;
1.217     brouard  3899:   double agexact;
                   3900:   double agebegin, ageend;
1.222     brouard  3901:   double **oldm, **savm;
1.217     brouard  3902: 
1.266     brouard  3903:   newmm=po; /* To be saved */
                   3904:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  3905:   /* Hstepm could be zero and should return the unit matrix */
                   3906:   for (i=1;i<=nlstate+ndeath;i++)
                   3907:     for (j=1;j<=nlstate+ndeath;j++){
                   3908:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3909:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3910:     }
                   3911:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3912:   for(h=1; h <=nhstepm; h++){
                   3913:     for(d=1; d <=hstepm; d++){
                   3914:       newm=savm;
                   3915:       /* Covariates have to be included here again */
                   3916:       cov[1]=1.;
1.271     brouard  3917:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  3918:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
1.318     brouard  3919:         /* Debug */
                   3920:       /* printf("hBxij age=%lf, agexact=%lf\n", age, agexact); */
1.217     brouard  3921:       cov[2]=agexact;
1.332     brouard  3922:       if(nagesqr==1){
1.222     brouard  3923:        cov[3]= agexact*agexact;
1.332     brouard  3924:       }
                   3925:       /** New code */
                   3926:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  3927:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  3928:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.325     brouard  3929:        }else{
1.332     brouard  3930:          cov[2+nagesqr+k1]=precov[nres][k1];
1.325     brouard  3931:        }
1.332     brouard  3932:       }/* End of loop on model equation */
                   3933:       /** End of new code */
                   3934:   /** This was old code */
                   3935:       /* for (k=1; k<=nsd;k++){ /\* For single dummy covariates only *\//\* cptcovn error *\/ */
                   3936:       /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3937:       /* /\* /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3938:       /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])];/\* Bug valgrind *\/ */
                   3939:       /*   /\* 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)); *\/ */
                   3940:       /* } */
                   3941:       /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3942:       /*       /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3943:       /*       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3944:       /*       /\* 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]); *\/ */
                   3945:       /* } */
                   3946:       /* for (k=1; k<=cptcovage;k++){ /\* Should start at cptcovn+1 *\//\* For product with age *\/ */
                   3947:       /*       /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age error!!!*\\/ *\/ */
                   3948:       /*       if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3949:       /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3950:       /*       } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3951:       /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];  */
                   3952:       /*       } */
                   3953:       /*       /\* 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]); *\/ */
                   3954:       /* } */
                   3955:       /* for (k=1; k<=cptcovprod;k++){ /\* Useless because included in cptcovn *\/ */
                   3956:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3957:       /*       if(Dummy[Tvard[k][1]]==0){ */
                   3958:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3959:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][1])]; */
                   3960:       /*         }else{ */
                   3961:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3962:       /*         } */
                   3963:       /*       }else{ */
                   3964:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3965:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3966:       /*         }else{ */
                   3967:       /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3968:       /*         } */
                   3969:       /*       } */
                   3970:       /* }                      */
                   3971:       /* /\*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*\/ */
                   3972:       /* /\*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*\/ */
                   3973: /** End of old code */
                   3974:       
1.218     brouard  3975:       /* Careful transposed matrix */
1.266     brouard  3976:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  3977:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3978:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3979:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.325     brouard  3980:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);/* Bug valgrind */
1.217     brouard  3981:       /* if((int)age == 70){ */
                   3982:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3983:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3984:       /*         printf("%d pmmij ",i); */
                   3985:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3986:       /*           printf("%f ",pmmij[i][j]); */
                   3987:       /*         } */
                   3988:       /*         printf(" oldm "); */
                   3989:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3990:       /*           printf("%f ",oldm[i][j]); */
                   3991:       /*         } */
                   3992:       /*         printf("\n"); */
                   3993:       /*       } */
                   3994:       /* } */
                   3995:       savm=oldm;
                   3996:       oldm=newm;
                   3997:     }
                   3998:     for(i=1; i<=nlstate+ndeath; i++)
                   3999:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  4000:        po[i][j][h]=newm[i][j];
1.268     brouard  4001:        /* if(h==nhstepm) */
                   4002:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  4003:       }
1.268     brouard  4004:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  4005:   } /* end h */
1.268     brouard  4006:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  4007:   return po;
                   4008: }
                   4009: 
                   4010: 
1.162     brouard  4011: #ifdef NLOPT
                   4012:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   4013:   double fret;
                   4014:   double *xt;
                   4015:   int j;
                   4016:   myfunc_data *d2 = (myfunc_data *) pd;
                   4017: /* xt = (p1-1); */
                   4018:   xt=vector(1,n); 
                   4019:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   4020: 
                   4021:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   4022:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   4023:   printf("Function = %.12lf ",fret);
                   4024:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   4025:   printf("\n");
                   4026:  free_vector(xt,1,n);
                   4027:   return fret;
                   4028: }
                   4029: #endif
1.126     brouard  4030: 
                   4031: /*************** log-likelihood *************/
                   4032: double func( double *x)
                   4033: {
1.336     brouard  4034:   int i, ii, j, k, mi, d, kk, kf=0;
1.226     brouard  4035:   int ioffset=0;
1.339     brouard  4036:   int ipos=0,iposold=0,ncovv=0;
                   4037: 
1.340     brouard  4038:   double cotvarv, cotvarvold;
1.226     brouard  4039:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   4040:   double **out;
                   4041:   double lli; /* Individual log likelihood */
                   4042:   int s1, s2;
1.228     brouard  4043:   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  4044: 
1.226     brouard  4045:   double bbh, survp;
                   4046:   double agexact;
1.336     brouard  4047:   double agebegin, ageend;
1.226     brouard  4048:   /*extern weight */
                   4049:   /* We are differentiating ll according to initial status */
                   4050:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   4051:   /*for(i=1;i<imx;i++) 
                   4052:     printf(" %d\n",s[4][i]);
                   4053:   */
1.162     brouard  4054: 
1.226     brouard  4055:   ++countcallfunc;
1.162     brouard  4056: 
1.226     brouard  4057:   cov[1]=1.;
1.126     brouard  4058: 
1.226     brouard  4059:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  4060:   ioffset=0;
1.226     brouard  4061:   if(mle==1){
                   4062:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4063:       /* Computes the values of the ncovmodel covariates of the model
                   4064:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   4065:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   4066:         to be observed in j being in i according to the model.
                   4067:       */
1.243     brouard  4068:       ioffset=2+nagesqr ;
1.233     brouard  4069:    /* Fixed */
1.345     brouard  4070:       for (kf=1; kf<=ncovf;kf++){ /* For each fixed covariate dummy or quant or prod */
1.319     brouard  4071:        /* # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi */
                   4072:         /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   4073:        /*  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  4074:         /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.336     brouard  4075:        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  4076:        /* V1*V2 (7)  TvarFind[2]=7, TvarFind[3]=9 */
1.234     brouard  4077:       }
1.226     brouard  4078:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.319     brouard  4079:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
1.226     brouard  4080:         has been calculated etc */
                   4081:       /* For an individual i, wav[i] gives the number of effective waves */
                   4082:       /* We compute the contribution to Likelihood of each effective transition
                   4083:         mw[mi][i] is real wave of the mi th effectve wave */
                   4084:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   4085:         s2=s[mw[mi+1][i]][i];
1.341     brouard  4086:         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  4087:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   4088:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   4089:       */
1.336     brouard  4090:       for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
                   4091:       /* Wave varying (but not age varying) */
1.339     brouard  4092:        /* 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*\/ */
                   4093:        /*   /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; but where is the crossproduct? *\/ */
                   4094:        /*   cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   4095:        /* } */
1.340     brouard  4096:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age )*/
                   4097:          itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   4098:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
1.345     brouard  4099:          if(FixedV[itv]!=0){ /* Not a fixed covariate */
1.341     brouard  4100:            cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* cotvar[wav][ncovcol+nqv+iv][i] */
1.340     brouard  4101:          }else{ /* fixed covariate */
1.345     brouard  4102:            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  4103:          }
1.339     brouard  4104:          if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  4105:            cotvarvold=cotvarv;
                   4106:          }else{ /* A second product */
                   4107:            cotvarv=cotvarv*cotvarvold;
1.339     brouard  4108:          }
                   4109:          iposold=ipos;
1.340     brouard  4110:          cov[ioffset+ipos]=cotvarv;
1.234     brouard  4111:        }
1.339     brouard  4112:        /* for products of time varying to be done */
1.234     brouard  4113:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4114:          for (j=1;j<=nlstate+ndeath;j++){
                   4115:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4116:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4117:          }
1.336     brouard  4118: 
                   4119:        agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4120:        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  4121:        for(d=0; d<dh[mi][i]; d++){
                   4122:          newm=savm;
                   4123:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4124:          cov[2]=agexact;
                   4125:          if(nagesqr==1)
                   4126:            cov[3]= agexact*agexact;  /* Should be changed here */
1.349     brouard  4127:          /* for (kk=1; kk<=cptcovage;kk++) { */
                   4128:          /*   if(!FixedV[Tvar[Tage[kk]]]) */
                   4129:          /*     cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /\* Tage[kk] gives the data-covariate associated with age *\/ */
                   4130:          /*   else */
                   4131:          /*     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) *\/  */
                   4132:          /* } */
                   4133:          for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   4134:            itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   4135:            ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4136:            if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   4137:              cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   4138:            }else{ /* fixed covariate */
                   4139:              cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   4140:            }
                   4141:            if(ipos!=iposold){ /* Not a product or first of a product */
                   4142:              cotvarvold=cotvarv;
                   4143:            }else{ /* A second product */
                   4144:              cotvarv=cotvarv*cotvarvold;
                   4145:            }
                   4146:            iposold=ipos;
                   4147:            cov[ioffset+ipos]=cotvarv*agexact;
                   4148:            /* For products */
1.234     brouard  4149:          }
1.349     brouard  4150:          
1.234     brouard  4151:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4152:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4153:          savm=oldm;
                   4154:          oldm=newm;
                   4155:        } /* end mult */
                   4156:        
                   4157:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   4158:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   4159:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   4160:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   4161:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   4162:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   4163:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   4164:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  4165:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   4166:                                 * -stepm/2 to stepm/2 .
                   4167:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   4168:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   4169:                                 */
1.234     brouard  4170:        s1=s[mw[mi][i]][i];
                   4171:        s2=s[mw[mi+1][i]][i];
                   4172:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4173:        /* bias bh is positive if real duration
                   4174:         * is higher than the multiple of stepm and negative otherwise.
                   4175:         */
                   4176:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   4177:        if( s2 > nlstate){ 
                   4178:          /* i.e. if s2 is a death state and if the date of death is known 
                   4179:             then the contribution to the likelihood is the probability to 
                   4180:             die between last step unit time and current  step unit time, 
                   4181:             which is also equal to probability to die before dh 
                   4182:             minus probability to die before dh-stepm . 
                   4183:             In version up to 0.92 likelihood was computed
                   4184:             as if date of death was unknown. Death was treated as any other
                   4185:             health state: the date of the interview describes the actual state
                   4186:             and not the date of a change in health state. The former idea was
                   4187:             to consider that at each interview the state was recorded
                   4188:             (healthy, disable or death) and IMaCh was corrected; but when we
                   4189:             introduced the exact date of death then we should have modified
                   4190:             the contribution of an exact death to the likelihood. This new
                   4191:             contribution is smaller and very dependent of the step unit
                   4192:             stepm. It is no more the probability to die between last interview
                   4193:             and month of death but the probability to survive from last
                   4194:             interview up to one month before death multiplied by the
                   4195:             probability to die within a month. Thanks to Chris
                   4196:             Jackson for correcting this bug.  Former versions increased
                   4197:             mortality artificially. The bad side is that we add another loop
                   4198:             which slows down the processing. The difference can be up to 10%
                   4199:             lower mortality.
                   4200:          */
                   4201:          /* If, at the beginning of the maximization mostly, the
                   4202:             cumulative probability or probability to be dead is
                   4203:             constant (ie = 1) over time d, the difference is equal to
                   4204:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   4205:             s1 at precedent wave, to be dead a month before current
                   4206:             wave is equal to probability, being at state s1 at
                   4207:             precedent wave, to be dead at mont of the current
                   4208:             wave. Then the observed probability (that this person died)
                   4209:             is null according to current estimated parameter. In fact,
                   4210:             it should be very low but not zero otherwise the log go to
                   4211:             infinity.
                   4212:          */
1.183     brouard  4213: /* #ifdef INFINITYORIGINAL */
                   4214: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4215: /* #else */
                   4216: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   4217: /*         lli=log(mytinydouble); */
                   4218: /*       else */
                   4219: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4220: /* #endif */
1.226     brouard  4221:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4222:          
1.226     brouard  4223:        } else if  ( s2==-1 ) { /* alive */
                   4224:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4225:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4226:          /*survp += out[s1][j]; */
                   4227:          lli= log(survp);
                   4228:        }
1.336     brouard  4229:        /* else if  (s2==-4) {  */
                   4230:        /*   for (j=3,survp=0. ; j<=nlstate; j++)   */
                   4231:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4232:        /*   lli= log(survp);  */
                   4233:        /* }  */
                   4234:        /* else if  (s2==-5) {  */
                   4235:        /*   for (j=1,survp=0. ; j<=2; j++)   */
                   4236:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4237:        /*   lli= log(survp);  */
                   4238:        /* }  */
1.226     brouard  4239:        else{
                   4240:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4241:          /*  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 */
                   4242:        } 
                   4243:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   4244:        /*if(lli ==000.0)*/
1.340     brouard  4245:        /* 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  4246:        ipmx +=1;
                   4247:        sw += weight[i];
                   4248:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4249:        /* if (lli < log(mytinydouble)){ */
                   4250:        /*   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); */
                   4251:        /*   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]); */
                   4252:        /* } */
                   4253:       } /* end of wave */
                   4254:     } /* end of individual */
                   4255:   }  else if(mle==2){
                   4256:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.319     brouard  4257:       ioffset=2+nagesqr ;
                   4258:       for (k=1; k<=ncovf;k++)
                   4259:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];
1.226     brouard  4260:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  4261:        for(k=1; k <= ncovv ; k++){
1.341     brouard  4262:          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  4263:        }
1.226     brouard  4264:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4265:          for (j=1;j<=nlstate+ndeath;j++){
                   4266:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4267:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4268:          }
                   4269:        for(d=0; d<=dh[mi][i]; d++){
                   4270:          newm=savm;
                   4271:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4272:          cov[2]=agexact;
                   4273:          if(nagesqr==1)
                   4274:            cov[3]= agexact*agexact;
                   4275:          for (kk=1; kk<=cptcovage;kk++) {
                   4276:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4277:          }
                   4278:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4279:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4280:          savm=oldm;
                   4281:          oldm=newm;
                   4282:        } /* end mult */
                   4283:       
                   4284:        s1=s[mw[mi][i]][i];
                   4285:        s2=s[mw[mi+1][i]][i];
                   4286:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4287:        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 */
                   4288:        ipmx +=1;
                   4289:        sw += weight[i];
                   4290:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4291:       } /* end of wave */
                   4292:     } /* end of individual */
                   4293:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   4294:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4295:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4296:       for(mi=1; mi<= wav[i]-1; mi++){
                   4297:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4298:          for (j=1;j<=nlstate+ndeath;j++){
                   4299:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4300:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4301:          }
                   4302:        for(d=0; d<dh[mi][i]; d++){
                   4303:          newm=savm;
                   4304:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4305:          cov[2]=agexact;
                   4306:          if(nagesqr==1)
                   4307:            cov[3]= agexact*agexact;
                   4308:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  4309:            if(!FixedV[Tvar[Tage[kk]]])
                   4310:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4311:            else
1.341     brouard  4312:              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  4313:          }
                   4314:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4315:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4316:          savm=oldm;
                   4317:          oldm=newm;
                   4318:        } /* end mult */
                   4319:       
                   4320:        s1=s[mw[mi][i]][i];
                   4321:        s2=s[mw[mi+1][i]][i];
                   4322:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4323:        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 */
                   4324:        ipmx +=1;
                   4325:        sw += weight[i];
                   4326:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4327:       } /* end of wave */
                   4328:     } /* end of individual */
                   4329:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   4330:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4331:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4332:       for(mi=1; mi<= wav[i]-1; mi++){
                   4333:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4334:          for (j=1;j<=nlstate+ndeath;j++){
                   4335:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4336:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4337:          }
                   4338:        for(d=0; d<dh[mi][i]; d++){
                   4339:          newm=savm;
                   4340:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4341:          cov[2]=agexact;
                   4342:          if(nagesqr==1)
                   4343:            cov[3]= agexact*agexact;
                   4344:          for (kk=1; kk<=cptcovage;kk++) {
                   4345:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4346:          }
1.126     brouard  4347:        
1.226     brouard  4348:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4349:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4350:          savm=oldm;
                   4351:          oldm=newm;
                   4352:        } /* end mult */
                   4353:       
                   4354:        s1=s[mw[mi][i]][i];
                   4355:        s2=s[mw[mi+1][i]][i];
                   4356:        if( s2 > nlstate){ 
                   4357:          lli=log(out[s1][s2] - savm[s1][s2]);
                   4358:        } else if  ( s2==-1 ) { /* alive */
                   4359:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4360:            survp += out[s1][j];
                   4361:          lli= log(survp);
                   4362:        }else{
                   4363:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4364:        }
                   4365:        ipmx +=1;
                   4366:        sw += weight[i];
                   4367:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.343     brouard  4368:        /* 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  4369:       } /* end of wave */
                   4370:     } /* end of individual */
                   4371:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   4372:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4373:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4374:       for(mi=1; mi<= wav[i]-1; mi++){
                   4375:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4376:          for (j=1;j<=nlstate+ndeath;j++){
                   4377:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4378:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4379:          }
                   4380:        for(d=0; d<dh[mi][i]; d++){
                   4381:          newm=savm;
                   4382:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4383:          cov[2]=agexact;
                   4384:          if(nagesqr==1)
                   4385:            cov[3]= agexact*agexact;
                   4386:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  4387:            if(!FixedV[Tvar[Tage[kk]]])
                   4388:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4389:            else
1.341     brouard  4390:              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  4391:          }
1.126     brouard  4392:        
1.226     brouard  4393:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4394:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4395:          savm=oldm;
                   4396:          oldm=newm;
                   4397:        } /* end mult */
                   4398:       
                   4399:        s1=s[mw[mi][i]][i];
                   4400:        s2=s[mw[mi+1][i]][i];
                   4401:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4402:        ipmx +=1;
                   4403:        sw += weight[i];
                   4404:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4405:        /*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]);*/
                   4406:       } /* end of wave */
                   4407:     } /* end of individual */
                   4408:   } /* End of if */
                   4409:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   4410:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   4411:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4412:   return -l;
1.126     brouard  4413: }
                   4414: 
                   4415: /*************** log-likelihood *************/
                   4416: double funcone( double *x)
                   4417: {
1.228     brouard  4418:   /* Same as func but slower because of a lot of printf and if */
1.349     brouard  4419:   int i, ii, j, k, mi, d, kk, kv=0, kf=0;
1.228     brouard  4420:   int ioffset=0;
1.339     brouard  4421:   int ipos=0,iposold=0,ncovv=0;
                   4422: 
1.340     brouard  4423:   double cotvarv, cotvarvold;
1.131     brouard  4424:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  4425:   double **out;
                   4426:   double lli; /* Individual log likelihood */
                   4427:   double llt;
                   4428:   int s1, s2;
1.228     brouard  4429:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   4430: 
1.126     brouard  4431:   double bbh, survp;
1.187     brouard  4432:   double agexact;
1.214     brouard  4433:   double agebegin, ageend;
1.126     brouard  4434:   /*extern weight */
                   4435:   /* We are differentiating ll according to initial status */
                   4436:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   4437:   /*for(i=1;i<imx;i++) 
                   4438:     printf(" %d\n",s[4][i]);
                   4439:   */
                   4440:   cov[1]=1.;
                   4441: 
                   4442:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  4443:   ioffset=0;
                   4444:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.336     brouard  4445:     /* Computes the values of the ncovmodel covariates of the model
                   4446:        depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   4447:        Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   4448:        to be observed in j being in i according to the model.
                   4449:     */
1.243     brouard  4450:     /* ioffset=2+nagesqr+cptcovage; */
                   4451:     ioffset=2+nagesqr;
1.232     brouard  4452:     /* Fixed */
1.224     brouard  4453:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  4454:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
1.349     brouard  4455:     for (kf=1; kf<=ncovf;kf++){ /*  V2  +  V3  +  V4  Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
1.339     brouard  4456:       /* printf("Debug3 TvarFind[%d]=%d",kf, TvarFind[kf]); */
                   4457:       /* printf(" Tvar[TvarFind[kf]]=%d", Tvar[TvarFind[kf]]); */
                   4458:       /* printf(" i=%d covar[Tvar[TvarFind[kf]]][i]=%f\n",i,covar[Tvar[TvarFind[kf]]][i]); */
1.335     brouard  4459:       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  4460: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   4461: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   4462: /*    cov[2+6]=covar[2][i]; V2  */
                   4463: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   4464: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   4465: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   4466: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   4467: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   4468: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  4469:     }
1.336     brouard  4470:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   4471:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
                   4472:         has been calculated etc */
                   4473:       /* For an individual i, wav[i] gives the number of effective waves */
                   4474:       /* We compute the contribution to Likelihood of each effective transition
                   4475:         mw[mi][i] is real wave of the mi th effectve wave */
                   4476:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   4477:         s2=s[mw[mi+1][i]][i];
1.341     brouard  4478:         And the iv th varying covariate in the DATA is the cotvar[mw[mi+1][i]][ncovcol+nqv+iv][i]
1.336     brouard  4479:       */
                   4480:     /* This part may be useless now because everythin should be in covar */
1.232     brouard  4481:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   4482:     /*   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?)*\/ */
                   4483:     /* } */
1.231     brouard  4484:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   4485:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   4486:     /* } */
1.225     brouard  4487:     
1.233     brouard  4488: 
                   4489:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.339     brouard  4490:       /* 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 */
                   4491:       /* for(k=1; k <= ncovv ; k++){ /\* Varying  covariates (single and product but no age )*\/ */
                   4492:       /*       /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; *\/ */
                   4493:       /*       cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   4494:       /* } */
                   4495:       
                   4496:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   4497:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   4498:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   4499:       /*  TvarVV[1]=V3 (first time varying in the model equation, TvarVV[2]=V1 (in V1*V3) TvarVV[3]=3(V3)  */
                   4500:       /* We need the position of the time varying or product in the model */
                   4501:       /* 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 */            
                   4502:       /* TvarVV gives the variable name */
1.340     brouard  4503:       /* Other example V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   4504:       *      k=         1   2     3     4         5        6        7       8        9
                   4505:       *  varying            1     2                                 3       4        5
                   4506:       *  ncovv              1     2                                3 4     5 6      7 8
1.343     brouard  4507:       * TvarVV[ncovv]      V3     5                                1 3     3 5      1 5
1.340     brouard  4508:       * TvarVVind           2     3                                7 7     8 8      9 9
                   4509:       * TvarFind[k]     1   0     0     0         0        0        0       0        0
                   4510:       */
1.345     brouard  4511:       /* Other model ncovcol=5 nqv=0 ntv=3 nqtv=0 nlstate=3
1.349     brouard  4512:        * 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[(v6*V2)6]=9
1.345     brouard  4513:        * FixedV[ncovcol+qv+ntv+nqtv]       V5
1.349     brouard  4514:        * 3           V1  V2     V3    V4   V5 V6     V7  V8 V3*V2 V7*V2  V6*V3 V7*V3 V6*V4 V7*V4
                   4515:        *             0   0      0      0    0  1      1   1  0, 0, 1,1,   1, 0, 1, 0, 1, 0, 1, 0}
                   4516:        * 3           0   0      0      0    0  1      1   1  0,     1      1    1      1    1}
                   4517:        * model=          V2  +  V3  +  V4  +  V6  +  V7  +  V6*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   4518:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   4519:         *                +age*V6*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   4520:        * model2=          V2  +  V3  +  V4  +  V6  +  V7  +  V3*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   4521:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   4522:         *                +age*V3*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   4523:        * model3=          V2  +  V3  +  V4  +  V6  +  V7  + age*V3*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   4524:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   4525:         *                +V3*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   4526:        * kmodel           1     2      3      4      5        6         7         8         9        10        11    
                   4527:        *                  12       13      14      15       16
                   4528:        *                    17        18         19        20         21
                   4529:        * Tvar[kmodel]     2     3      4      6      7        9        10        11        12        13        14
                   4530:        *                   2       3        4       6        7
                   4531:        *                     9         11          12        13         14            
                   4532:        * cptcovage=5+5 total of covariates with age 
                   4533:        * Tage[cptcovage] age*V2=12      13      14      15       16
                   4534:        *1                   17            18         19        20         21 gives the position in model of covariates associated with age
                   4535:        *3 Tage[cptcovage] age*V3*V2=6  
                   4536:        *3                age*V2=12         13      14      15       16
                   4537:        *3                age*V6*V3=18      19    20   21
                   4538:        * Tvar[Tage[cptcovage]]    Tvar[12]=2      3      4       6         Tvar[16]=7(age*V7)
                   4539:        *     Tvar[17]age*V6*V2=9      Tvar[18]age*V6*V3=11  age*V7*V3=12         age*V6*V4=13        Tvar[21]age*V7*V4=14
                   4540:        * 2   Tvar[17]age*V3*V2=9      Tvar[18]age*V6*V3=11  age*V7*V3=12         age*V6*V4=13        Tvar[21]age*V7*V4=14
                   4541:        * 3 Tvar[Tage[cptcovage]]    Tvar[6]=9      Tvar[12]=2      3     4       6         Tvar[16]=7(age*V7)
                   4542:        * 3     Tvar[18]age*V6*V3=11  age*V7*V3=12         age*V6*V4=13        Tvar[21]age*V7*V4=14
                   4543:        * 3 Tage[cptcovage] age*V3*V2=6   age*V2=12 age*V3 13    14      15       16
                   4544:        *                    age*V6*V3=18         19        20         21 gives the position in model of covariates associated with age
                   4545:        * 3   Tvar[17]age*V3*V2=9      Tvar[18]age*V6*V3=11  age*V7*V3=12         age*V6*V4=13        Tvar[21]age*V7*V4=14
                   4546:        * Tvar=                {2, 3, 4, 6, 7,
                   4547:        *                       9, 10, 11, 12, 13, 14,
                   4548:        *              Tvar[12]=2, 3, 4, 6, 7,
                   4549:        *              Tvar[17]=9, 11, 12, 13, 14}
                   4550:        * Typevar[1]@21 = {0, 0, 0, 0, 0,
                   4551:        *                  2, 2, 2, 2, 2, 2,
                   4552:        * 3                3, 2, 2, 2, 2, 2,
                   4553:        *                  1, 1, 1, 1, 1, 
                   4554:        *                  3, 3, 3, 3, 3}
                   4555:        * 3                 2, 3, 3, 3, 3}
                   4556:        * p Tposprod[1]@21 {0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 1, 3, 4, 5, 6} Id of the prod at position k in the model
                   4557:        * p Tprod[1]@21 {6, 7, 8, 9, 10, 11, 0 <repeats 15 times>}
                   4558:        * 3 Tposprod[1]@21 {0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 1, 3, 4, 5, 6}
                   4559:        * 3 Tprod[1]@21 {17, 7, 8, 9, 10, 11, 0 <repeats 15 times>}
                   4560:        * cptcovprod=11 (6+5)
                   4561:        * FixedV[Tvar[Tage[cptcovage]]]]  FixedV[2]=0      FixedV[3]=0      0      1          (age*V7)Tvar[16]=1 FixedV[absolute] not [kmodel]
                   4562:        *   FixedV[Tvar[17]=FixedV[age*V6*V2]=FixedV[9]=1        1         1          1         1  
                   4563:        * 3 FixedV[Tvar[17]=FixedV[age*V3*V2]=FixedV[9]=0        [11]=1         1          1         1  
                   4564:        * FixedV[]          V1=0     V2=0   V3=0  v4=0    V5=0  V6=1    V7=1 v8=1  OK then model dependent
                   4565:        *                   9=1  [V7*V2]=[10]=1 11=1  12=1  13=1  14=1
                   4566:        * 3                 9=0  [V7*V2]=[10]=1 11=1  12=1  13=1  14=1
                   4567:        * cptcovdageprod=5  for gnuplot printing
                   4568:        * cptcovprodvage=6 
                   4569:        * ncova=15           1        2       3       4       5
                   4570:        *                      6 7        8 9      10 11        12 13     14 15
                   4571:        * TvarA              2        3       4       6       7
                   4572:        *                      6 2        6 7       7 3          6 4       7 4
                   4573:        * TvaAind             12 12      13 13     14 14      15 15       16 16        
1.345     brouard  4574:        * ncovf            1     2      3
1.349     brouard  4575:        *                                    V6       V7      V6*V2     V7*V2     V6*V3     V7*V3     V6*V4     V7*V4
                   4576:        * ncovvt=14                            1      2        3 4       5 6       7 8       9 10     11 12     13 14     
                   4577:        * TvarVV[1]@14 = itv               {V6=6,     7, V6*V2=6, 2,     7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
                   4578:        * TvarVVind[1]@14=                    {4,     5,       6, 6,     7, 7,     8, 8,      9, 9,   10, 10,   11, 11}
                   4579:        * 3 ncovvt=12                        V6       V7      V7*V2     V6*V3     V7*V3     V6*V4     V7*V4
                   4580:        * 3 TvarVV[1]@12 = itv                {6,     7, V7*V2=7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
                   4581:        * 3                                    1      2        3  4      5  6      7  8      9 10     11 12
                   4582:        * TvarVVind[1]@12=         {V6 is in k=4,     5,  7,(4isV2)=7,   8, 8,      9, 9,   10,10,    11,11}TvarVVind[12]=k=11
                   4583:        * TvarV              6, 7, 9, 10, 11, 12, 13, 14
                   4584:        * 3 cptcovprodvage=6
                   4585:        * 3 ncovta=15    +age*V3*V2+age*V2+agev3+ageV4 +age*V6 + age*V7 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   4586:        * 3 TvarAVVA[1]@15= itva 3 2    2      3    4        6       7        6 3         7 3         6 4         7 4 
                   4587:        * 3 ncovta             1 2      3      4    5        6       7        8 9       10 11       12 13        14 15
1.354     brouard  4588:        *?TvarAVVAind[1]@15= V3 is in k=2 1 1  2    3        4       5        4,2         5,2,      4,3           5 3}TvarVVAind[]
1.349     brouard  4589:        * TvarAVVAind[1]@15= V3 is in k=6 6 12  13   14      15      16       18 18       19,19,     20,20        21,21}TvarVVAind[]
                   4590:        * 3 ncovvta=10     +age*V6 + age*V7 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   4591:        * 3 we want to compute =cotvar[mw[mi][i]][TvarVVA[ncovva]][i] at position TvarVVAind[ncovva]
                   4592:        * 3 TvarVVA[1]@10= itva   6       7        6 3         7 3         6 4         7 4 
                   4593:        * 3 ncovva                1       2        3 4         5 6         7 8         9 10
                   4594:        * TvarVVAind[1]@10= V6 is in k=4  5        8,8         9, 9,      10,10        11 11}TvarVVAind[]
                   4595:        * TvarVVAind[1]@10=       15       16     18,18        19,19,      20,20        21 21}TvarVVAind[]
                   4596:        * TvarVA              V3*V2=6 6 , 1, 2, 11, 12, 13, 14
1.345     brouard  4597:        * TvarFind[1]@14= {1,    2,     3,     0 <repeats 12 times>}
1.349     brouard  4598:        * Tvar[1]@21=     {2,    3,     4,    6,      7,      9,      10,        11,       12,      13,       14,
                   4599:        *                   2, 3, 4, 6, 7,
                   4600:        *                     6, 8, 9, 10, 11}
1.345     brouard  4601:        * TvarFind[itv]                        0      0       0
                   4602:        * FixedV[itv]                          1      1       1  0      1 0       1 0       1 0       0
1.354     brouard  4603:        *? FixedV[itv]                          1      1       1  0      1 0       1 0       1 0      1 0     1 0
1.345     brouard  4604:        * Tvar[TvarFind[ncovf]]=[1]=2 [2]=3 [4]=4
                   4605:        * Tvar[TvarFind[itv]]                [0]=?      ?ncovv 1 à ncovvt]
                   4606:        *   Not a fixed cotvar[mw][itv][i]     6       7      6  2      7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
1.349     brouard  4607:        *   fixed covar[itv]                  [6]     [7]    [6][2] 
1.345     brouard  4608:        */
                   4609: 
1.349     brouard  4610:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /*  V6       V7      V7*V2     V6*V3     V7*V3     V6*V4     V7*V4 Time varying  covariates (single and extended product but no age) including individual from products, product is computed dynamically */
                   4611:        itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, or fixed covariate of a varying product after exploding product Vn*Vm into Vn and then Vm  */
1.340     brouard  4612:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
1.345     brouard  4613:        /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   4614:        if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
1.354     brouard  4615:          /* printf("DEBUG ncovv=%d, Varying TvarVV[ncovv]=%d\n",ncovv, TvarVV[ncovv]); */
1.345     brouard  4616:          cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
1.354     brouard  4617:          /* printf("DEBUG Varying cov[ioffset+ipos=%d]=%g \n",ioffset+ipos,cotvarv); */
1.340     brouard  4618:        }else{ /* fixed covariate */
1.345     brouard  4619:          /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
1.354     brouard  4620:          /* printf("DEBUG ncovv=%d, Fixed TvarVV[ncovv]=%d\n",ncovv, TvarVV[ncovv]); */
1.349     brouard  4621:          cotvarv=covar[itv][i];  /* Good: In V6*V3, 3 is fixed at position of the data */
1.354     brouard  4622:          /* printf("DEBUG Fixed cov[ioffset+ipos=%d]=%g \n",ioffset+ipos,cotvarv); */
1.340     brouard  4623:        }
1.339     brouard  4624:        if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  4625:          cotvarvold=cotvarv;
                   4626:        }else{ /* A second product */
                   4627:          cotvarv=cotvarv*cotvarvold;
1.339     brouard  4628:        }
                   4629:        iposold=ipos;
1.340     brouard  4630:        cov[ioffset+ipos]=cotvarv;
1.354     brouard  4631:        /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
1.339     brouard  4632:        /* For products */
                   4633:       }
                   4634:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates single *\/ */
                   4635:       /*       iv=TvarVDind[itv]; /\* iv, position in the model equation of time varying covariate itv *\/ */
                   4636:       /*       /\*         "V1+V3+age*V1+age*V3+V1*V3" with V3 time varying *\/ */
                   4637:       /*       /\*           1  2   3      4      5                         *\/ */
                   4638:       /*       /\*itv           1                                           *\/ */
                   4639:       /*       /\* TvarVInd[1]= 2                                           *\/ */
                   4640:       /*       /\* iv= Tvar[Tmodelind[itv]]-ncovcol-nqv;  /\\* Counting the # varying covariate from 1 to ntveff *\\/ *\/ */
                   4641:       /*       /\* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; *\/ */
                   4642:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; *\/ */
                   4643:       /*       /\* k=ioffset-2-nagesqr-cptcovage+itv; /\\* position in simple model *\\/ *\/ */
                   4644:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; *\/ */
                   4645:       /*       cov[ioffset+iv]=cotvar[mw[mi][i]][itv][i]; */
                   4646:       /*       /\* 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]); *\/ */
                   4647:       /* } */
1.232     brouard  4648:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  4649:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4650:       /*       /\* 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]); *\/ */
                   4651:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  4652:       /* } */
1.126     brouard  4653:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  4654:        for (j=1;j<=nlstate+ndeath;j++){
                   4655:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4656:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4657:        }
1.214     brouard  4658:       
                   4659:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4660:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   4661:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  4662:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  4663:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4664:          and mw[mi+1][i]. dh depends on stepm.*/
                   4665:        newm=savm;
1.247     brouard  4666:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  4667:        cov[2]=agexact;
                   4668:        if(nagesqr==1)
                   4669:          cov[3]= agexact*agexact;
1.349     brouard  4670:        for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   4671:          itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   4672:          ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4673:          /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   4674:          if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   4675:            /* printf("DEBUG  ncovva=%d, Varying TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   4676:            cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   4677:          }else{ /* fixed covariate */
                   4678:            /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
                   4679:            /* printf("DEBUG ncovva=%d, Fixed TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   4680:            cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   4681:          }
                   4682:          if(ipos!=iposold){ /* Not a product or first of a product */
                   4683:            cotvarvold=cotvarv;
                   4684:          }else{ /* A second product */
                   4685:            /* printf("DEBUG * \n"); */
                   4686:            cotvarv=cotvarv*cotvarvold;
                   4687:          }
                   4688:          iposold=ipos;
                   4689:          /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
                   4690:          cov[ioffset+ipos]=cotvarv*agexact;
                   4691:          /* For products */
1.242     brouard  4692:        }
1.349     brouard  4693: 
1.242     brouard  4694:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   4695:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4696:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4697:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4698:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   4699:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   4700:        savm=oldm;
                   4701:        oldm=newm;
1.126     brouard  4702:       } /* end mult */
1.336     brouard  4703:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   4704:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   4705:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   4706:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   4707:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   4708:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   4709:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   4710:         * probability in order to take into account the bias as a fraction of the way
                   4711:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   4712:                                 * -stepm/2 to stepm/2 .
                   4713:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   4714:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   4715:                                 */
1.126     brouard  4716:       s1=s[mw[mi][i]][i];
                   4717:       s2=s[mw[mi+1][i]][i];
1.217     brouard  4718:       /* if(s2==-1){ */
1.268     brouard  4719:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  4720:       /*       /\* exit(1); *\/ */
                   4721:       /* } */
1.126     brouard  4722:       bbh=(double)bh[mi][i]/(double)stepm; 
                   4723:       /* bias is positive if real duration
                   4724:        * is higher than the multiple of stepm and negative otherwise.
                   4725:        */
                   4726:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  4727:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4728:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  4729:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   4730:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4731:        lli= log(survp);
1.126     brouard  4732:       }else if (mle==1){
1.242     brouard  4733:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  4734:       } else if(mle==2){
1.242     brouard  4735:        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  4736:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  4737:        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  4738:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  4739:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  4740:       } else{  /* mle=0 back to 1 */
1.242     brouard  4741:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4742:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  4743:       } /* End of if */
                   4744:       ipmx +=1;
                   4745:       sw += weight[i];
                   4746:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.342     brouard  4747:       /* Printing covariates values for each contribution for checking */
1.343     brouard  4748:       /* 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  4749:       if(globpr){
1.246     brouard  4750:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  4751:  %11.6f %11.6f %11.6f ", \
1.242     brouard  4752:                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  4753:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.343     brouard  4754:        /*      printf("%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\ */
                   4755:        /* %11.6f %11.6f %11.6f ", \ */
                   4756:        /*              num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw, */
                   4757:        /*              2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
1.242     brouard  4758:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   4759:          llt +=ll[k]*gipmx/gsw;
                   4760:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
1.335     brouard  4761:          /* printf(" %10.6f",-ll[k]*gipmx/gsw); */
1.242     brouard  4762:        }
1.343     brouard  4763:        fprintf(ficresilk," %10.6f ", -llt);
1.335     brouard  4764:        /* printf(" %10.6f\n", -llt); */
1.342     brouard  4765:        /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
1.343     brouard  4766:        /* fprintf(ficresilk,"%09ld ", num[i]); */ /* not necessary */
                   4767:        for (kf=1; kf<=ncovf;kf++){ /* Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
                   4768:          fprintf(ficresilk," %g",covar[Tvar[TvarFind[kf]]][i]);
                   4769:        }
                   4770:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age) including individual from products */
                   4771:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4772:          if(ipos!=iposold){ /* Not a product or first of a product */
                   4773:            fprintf(ficresilk," %g",cov[ioffset+ipos]);
                   4774:            /* printf(" %g",cov[ioffset+ipos]); */
                   4775:          }else{
                   4776:            fprintf(ficresilk,"*");
                   4777:            /* printf("*"); */
1.342     brouard  4778:          }
1.343     brouard  4779:          iposold=ipos;
                   4780:        }
1.349     brouard  4781:        /* for (kk=1; kk<=cptcovage;kk++) { */
                   4782:        /*   if(!FixedV[Tvar[Tage[kk]]]){ */
                   4783:        /*     fprintf(ficresilk," %g*age",covar[Tvar[Tage[kk]]][i]); */
                   4784:        /*     /\* printf(" %g*age",covar[Tvar[Tage[kk]]][i]); *\/ */
                   4785:        /*   }else{ */
                   4786:        /*     fprintf(ficresilk," %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
                   4787:        /*     /\* printf(" %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\\/  *\/ */
                   4788:        /*   } */
                   4789:        /* } */
                   4790:        for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   4791:          itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   4792:          ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4793:          /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   4794:          if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   4795:            /* printf("DEBUG  ncovva=%d, Varying TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   4796:            cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   4797:          }else{ /* fixed covariate */
                   4798:            /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
                   4799:            /* printf("DEBUG ncovva=%d, Fixed TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   4800:            cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   4801:          }
                   4802:          if(ipos!=iposold){ /* Not a product or first of a product */
                   4803:            cotvarvold=cotvarv;
                   4804:          }else{ /* A second product */
                   4805:            /* printf("DEBUG * \n"); */
                   4806:            cotvarv=cotvarv*cotvarvold;
1.342     brouard  4807:          }
1.349     brouard  4808:          cotvarv=cotvarv*agexact;
                   4809:          fprintf(ficresilk," %g*age",cotvarv);
                   4810:          iposold=ipos;
                   4811:          /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
                   4812:          cov[ioffset+ipos]=cotvarv;
                   4813:          /* For products */
1.343     brouard  4814:        }
                   4815:        /* printf("\n"); */
1.342     brouard  4816:        /* } /\*  End debugILK *\/ */
                   4817:        fprintf(ficresilk,"\n");
                   4818:       } /* End if globpr */
1.335     brouard  4819:     } /* end of wave */
                   4820:   } /* end of individual */
                   4821:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
1.232     brouard  4822: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
1.335     brouard  4823:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4824:   if(globpr==0){ /* First time we count the contributions and weights */
                   4825:     gipmx=ipmx;
                   4826:     gsw=sw;
                   4827:   }
1.343     brouard  4828:   return -l;
1.126     brouard  4829: }
                   4830: 
                   4831: 
                   4832: /*************** function likelione ***********/
1.292     brouard  4833: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  4834: {
                   4835:   /* This routine should help understanding what is done with 
                   4836:      the selection of individuals/waves and
                   4837:      to check the exact contribution to the likelihood.
                   4838:      Plotting could be done.
1.342     brouard  4839:   */
                   4840:   void pstamp(FILE *ficres);
1.343     brouard  4841:   int k, kf, kk, kvar, ncovv, iposold, ipos;
1.126     brouard  4842: 
                   4843:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  4844:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  4845:     strcat(fileresilk,fileresu);
1.126     brouard  4846:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   4847:       printf("Problem with resultfile: %s\n", fileresilk);
                   4848:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   4849:     }
1.342     brouard  4850:     pstamp(ficresilk);fprintf(ficresilk,"# model=1+age+%s\n",model);
1.214     brouard  4851:     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");
                   4852:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  4853:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   4854:     for(k=1; k<=nlstate; k++) 
                   4855:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
1.342     brouard  4856:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total) ");
                   4857: 
                   4858:     /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
                   4859:       for(kf=1;kf <= ncovf; kf++){
                   4860:        fprintf(ficresilk,"V%d",Tvar[TvarFind[kf]]);
                   4861:        /* printf("V%d",Tvar[TvarFind[kf]]); */
                   4862:       }
                   4863:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){
1.343     brouard  4864:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
1.342     brouard  4865:        if(ipos!=iposold){ /* Not a product or first of a product */
                   4866:          /* printf(" %d",ipos); */
                   4867:          fprintf(ficresilk," V%d",TvarVV[ncovv]);
                   4868:        }else{
                   4869:          /* printf("*"); */
                   4870:          fprintf(ficresilk,"*");
1.343     brouard  4871:        }
1.342     brouard  4872:        iposold=ipos;
                   4873:       }
                   4874:       for (kk=1; kk<=cptcovage;kk++) {
                   4875:        if(!FixedV[Tvar[Tage[kk]]]){
                   4876:          /* printf(" %d*age(Fixed)",Tvar[Tage[kk]]); */
                   4877:          fprintf(ficresilk," %d*age(Fixed)",Tvar[Tage[kk]]);
                   4878:        }else{
                   4879:          fprintf(ficresilk," %d*age(Varying)",Tvar[Tage[kk]]);/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
                   4880:          /* printf(" %d*age(Varying)",Tvar[Tage[kk]]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
                   4881:        }
                   4882:       }
                   4883:     /* } /\* End if debugILK *\/ */
                   4884:     /* printf("\n"); */
                   4885:     fprintf(ficresilk,"\n");
                   4886:   } /* End glogpri */
1.126     brouard  4887: 
1.292     brouard  4888:   *fretone=(*func)(p);
1.126     brouard  4889:   if(*globpri !=0){
                   4890:     fclose(ficresilk);
1.205     brouard  4891:     if (mle ==0)
                   4892:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   4893:     else if(mle >=1)
                   4894:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   4895:     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  4896:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  4897:       
1.207     brouard  4898:     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  4899: <img src=\"%s-ori.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4900:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.343     brouard  4901: <img src=\"%s-dest.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
                   4902:     
                   4903:     for (k=1; k<= nlstate ; k++) {
                   4904:       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 \
                   4905: <img src=\"%s-p%dj.png\">\n",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   4906:       for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
1.350     brouard  4907:         kvar=Tvar[TvarFind[kf]];  /* variable */
                   4908:         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): ",k,k,Tvar[TvarFind[kf]],Tvar[TvarFind[kf]],Tvar[TvarFind[kf]]);
                   4909:         fprintf(fichtm,"<a href=\"%s-p%dj-%d.png\">%s-p%dj-%d.png</a><br>",subdirf2(optionfilefiname,"ILK_"),k,kvar,subdirf2(optionfilefiname,"ILK_"),k,kvar);
                   4910:         fprintf(fichtm,"<img src=\"%s-p%dj-%d.png\">",subdirf2(optionfilefiname,"ILK_"),k,Tvar[TvarFind[kf]]);
1.343     brouard  4911:       }
                   4912:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Loop on the time varying extended covariates (with extension of Vn*Vm */
                   4913:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   4914:        kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   4915:        /* 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]); */
                   4916:        if(ipos!=iposold){ /* Not a product or first of a product */
                   4917:          /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   4918:          /* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); */
                   4919:          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)  */
                   4920:            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> \
                   4921: <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);
                   4922:          } /* End only for dummies time varying (single?) */
                   4923:        }else{ /* Useless product */
                   4924:          /* printf("*"); */
                   4925:          /* fprintf(ficresilk,"*"); */ 
                   4926:        }
                   4927:        iposold=ipos;
                   4928:       } /* For each time varying covariate */
                   4929:     } /* End loop on states */
                   4930: 
                   4931: /*     if(debugILK){ */
                   4932: /*       for(kf=1; kf <= ncovf; kf++){ /\* For each simple dummy covariate of the model *\/ */
                   4933: /*     /\* kvar=Tvar[TvarFind[kf]]; *\/ /\* variable *\/ */
                   4934: /*     for (k=1; k<= nlstate ; k++) { */
                   4935: /*       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> \ */
                   4936: /* <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]]); */
                   4937: /*     } */
                   4938: /*       } */
                   4939: /*       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /\* Loop on the time varying extended covariates (with extension of Vn*Vm *\/ */
                   4940: /*     ipos=TvarVVind[ncovv]; /\* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate *\/ */
                   4941: /*     kvar=TvarVV[ncovv]; /\*  TvarVV={3, 1, 3} gives the name of each varying covariate *\/ */
                   4942: /*     /\* 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]); *\/ */
                   4943: /*     if(ipos!=iposold){ /\* Not a product or first of a product *\/ */
                   4944: /*       /\* fprintf(ficresilk," V%d",TvarVV[ncovv]); *\/ */
                   4945: /*       /\* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); *\/ */
                   4946: /*       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)  *\/ */
                   4947: /*         for (k=1; k<= nlstate ; k++) { */
                   4948: /*           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> \ */
                   4949: /* <img src=\"%s-p%dj-%d.png\">",k,k,kvar,kvar,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,kvar); */
                   4950: /*         } /\* End state *\/ */
                   4951: /*       } /\* End only for dummies time varying (single?) *\/ */
                   4952: /*     }else{ /\* Useless product *\/ */
                   4953: /*       /\* printf("*"); *\/ */
                   4954: /*       /\* fprintf(ficresilk,"*"); *\/  */
                   4955: /*     } */
                   4956: /*     iposold=ipos; */
                   4957: /*       } /\* For each time varying covariate *\/ */
                   4958: /*     }/\* End debugILK *\/ */
1.207     brouard  4959:     fflush(fichtm);
1.343     brouard  4960:   }/* End globpri */
1.126     brouard  4961:   return;
                   4962: }
                   4963: 
                   4964: 
                   4965: /*********** Maximum Likelihood Estimation ***************/
                   4966: 
                   4967: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   4968: {
1.319     brouard  4969:   int i,j,k, jk, jkk=0, iter=0;
1.126     brouard  4970:   double **xi;
                   4971:   double fret;
                   4972:   double fretone; /* Only one call to likelihood */
                   4973:   /*  char filerespow[FILENAMELENGTH];*/
1.354     brouard  4974:   
                   4975:   double * p1; /* Shifted parameters from 0 instead of 1 */
1.162     brouard  4976: #ifdef NLOPT
                   4977:   int creturn;
                   4978:   nlopt_opt opt;
                   4979:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   4980:   double *lb;
                   4981:   double minf; /* the minimum objective value, upon return */
1.354     brouard  4982: 
1.162     brouard  4983:   myfunc_data dinst, *d = &dinst;
                   4984: #endif
                   4985: 
                   4986: 
1.126     brouard  4987:   xi=matrix(1,npar,1,npar);
1.357   ! brouard  4988:   for (i=1;i<=npar;i++)  /* Starting with canonical directions j=1,n xi[i=1,n][j] */
1.126     brouard  4989:     for (j=1;j<=npar;j++)
                   4990:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   4991:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  4992:   strcpy(filerespow,"POW_"); 
1.126     brouard  4993:   strcat(filerespow,fileres);
                   4994:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   4995:     printf("Problem with resultfile: %s\n", filerespow);
                   4996:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   4997:   }
                   4998:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   4999:   for (i=1;i<=nlstate;i++)
                   5000:     for(j=1;j<=nlstate+ndeath;j++)
                   5001:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   5002:   fprintf(ficrespow,"\n");
1.162     brouard  5003: #ifdef POWELL
1.319     brouard  5004: #ifdef LINMINORIGINAL
                   5005: #else /* LINMINORIGINAL */
                   5006:   
                   5007:   flatdir=ivector(1,npar); 
                   5008:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   5009: #endif /*LINMINORIGINAL */
                   5010: 
                   5011: #ifdef FLATSUP
                   5012:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   5013:   /* reorganizing p by suppressing flat directions */
                   5014:   for(i=1, jk=1; i <=nlstate; i++){
                   5015:     for(k=1; k <=(nlstate+ndeath); k++){
                   5016:       if (k != i) {
                   5017:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   5018:         if(flatdir[jk]==1){
                   5019:           printf(" To be skipped %d%d flatdir[%d]=%d ",i,k,jk, flatdir[jk]);
                   5020:         }
                   5021:         for(j=1; j <=ncovmodel; j++){
                   5022:           printf("%12.7f ",p[jk]);
                   5023:           jk++; 
                   5024:         }
                   5025:         printf("\n");
                   5026:       }
                   5027:     }
                   5028:   }
                   5029: /* skipping */
                   5030:   /* for(i=1, jk=1, jkk=1;(flatdir[jk]==0)&& (i <=nlstate); i++){ */
                   5031:   for(i=1, jk=1, jkk=1;i <=nlstate; i++){
                   5032:     for(k=1; k <=(nlstate+ndeath); k++){
                   5033:       if (k != i) {
                   5034:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   5035:         if(flatdir[jk]==1){
                   5036:           printf(" To be skipped %d%d flatdir[%d]=%d jk=%d p[%d] ",i,k,jk, flatdir[jk],jk, jk);
                   5037:           for(j=1; j <=ncovmodel;  jk++,j++){
                   5038:             printf(" p[%d]=%12.7f",jk, p[jk]);
                   5039:             /*q[jjk]=p[jk];*/
                   5040:           }
                   5041:         }else{
                   5042:           printf(" To be kept %d%d flatdir[%d]=%d jk=%d q[%d]=p[%d] ",i,k,jk, flatdir[jk],jk, jkk, jk);
                   5043:           for(j=1; j <=ncovmodel;  jk++,jkk++,j++){
                   5044:             printf(" p[%d]=%12.7f=q[%d]",jk, p[jk],jkk);
                   5045:             /*q[jjk]=p[jk];*/
                   5046:           }
                   5047:         }
                   5048:         printf("\n");
                   5049:       }
                   5050:       fflush(stdout);
                   5051:     }
                   5052:   }
                   5053:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   5054: #else  /* FLATSUP */
1.126     brouard  5055:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.319     brouard  5056: #endif  /* FLATSUP */
                   5057: 
                   5058: #ifdef LINMINORIGINAL
                   5059: #else
                   5060:       free_ivector(flatdir,1,npar); 
                   5061: #endif  /* LINMINORIGINAL*/
                   5062: #endif /* POWELL */
1.126     brouard  5063: 
1.162     brouard  5064: #ifdef NLOPT
                   5065: #ifdef NEWUOA
                   5066:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   5067: #else
                   5068:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   5069: #endif
                   5070:   lb=vector(0,npar-1);
                   5071:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   5072:   nlopt_set_lower_bounds(opt, lb);
                   5073:   nlopt_set_initial_step1(opt, 0.1);
                   5074:   
                   5075:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   5076:   d->function = func;
                   5077:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   5078:   nlopt_set_min_objective(opt, myfunc, d);
                   5079:   nlopt_set_xtol_rel(opt, ftol);
                   5080:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   5081:     printf("nlopt failed! %d\n",creturn); 
                   5082:   }
                   5083:   else {
                   5084:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   5085:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   5086:     iter=1; /* not equal */
                   5087:   }
                   5088:   nlopt_destroy(opt);
                   5089: #endif
1.319     brouard  5090: #ifdef FLATSUP
                   5091:   /* npared = npar -flatd/ncovmodel; */
                   5092:   /* xired= matrix(1,npared,1,npared); */
                   5093:   /* paramred= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */
                   5094:   /* powell(pred,xired,npared,ftol,&iter,&fret,flatdir,func); */
                   5095:   /* free_matrix(xire,1,npared,1,npared); */
                   5096: #else  /* FLATSUP */
                   5097: #endif /* FLATSUP */
1.126     brouard  5098:   free_matrix(xi,1,npar,1,npar);
                   5099:   fclose(ficrespow);
1.203     brouard  5100:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   5101:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  5102:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  5103: 
                   5104: }
                   5105: 
                   5106: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  5107: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  5108: {
                   5109:   double  **a,**y,*x,pd;
1.203     brouard  5110:   /* double **hess; */
1.164     brouard  5111:   int i, j;
1.126     brouard  5112:   int *indx;
                   5113: 
                   5114:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  5115:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  5116:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   5117:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   5118:   double gompertz(double p[]);
1.203     brouard  5119:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  5120: 
                   5121:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   5122:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   5123:   for (i=1;i<=npar;i++){
1.203     brouard  5124:     printf("%d-",i);fflush(stdout);
                   5125:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  5126:    
                   5127:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   5128:     
                   5129:     /*  printf(" %f ",p[i]);
                   5130:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   5131:   }
                   5132:   
                   5133:   for (i=1;i<=npar;i++) {
                   5134:     for (j=1;j<=npar;j++)  {
                   5135:       if (j>i) { 
1.203     brouard  5136:        printf(".%d-%d",i,j);fflush(stdout);
                   5137:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   5138:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  5139:        
                   5140:        hess[j][i]=hess[i][j];    
                   5141:        /*printf(" %lf ",hess[i][j]);*/
                   5142:       }
                   5143:     }
                   5144:   }
                   5145:   printf("\n");
                   5146:   fprintf(ficlog,"\n");
                   5147: 
                   5148:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   5149:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   5150:   
                   5151:   a=matrix(1,npar,1,npar);
                   5152:   y=matrix(1,npar,1,npar);
                   5153:   x=vector(1,npar);
                   5154:   indx=ivector(1,npar);
                   5155:   for (i=1;i<=npar;i++)
                   5156:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   5157:   ludcmp(a,npar,indx,&pd);
                   5158: 
                   5159:   for (j=1;j<=npar;j++) {
                   5160:     for (i=1;i<=npar;i++) x[i]=0;
                   5161:     x[j]=1;
                   5162:     lubksb(a,npar,indx,x);
                   5163:     for (i=1;i<=npar;i++){ 
                   5164:       matcov[i][j]=x[i];
                   5165:     }
                   5166:   }
                   5167: 
                   5168:   printf("\n#Hessian matrix#\n");
                   5169:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   5170:   for (i=1;i<=npar;i++) { 
                   5171:     for (j=1;j<=npar;j++) { 
1.203     brouard  5172:       printf("%.6e ",hess[i][j]);
                   5173:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  5174:     }
                   5175:     printf("\n");
                   5176:     fprintf(ficlog,"\n");
                   5177:   }
                   5178: 
1.203     brouard  5179:   /* printf("\n#Covariance matrix#\n"); */
                   5180:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   5181:   /* for (i=1;i<=npar;i++) {  */
                   5182:   /*   for (j=1;j<=npar;j++) {  */
                   5183:   /*     printf("%.6e ",matcov[i][j]); */
                   5184:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   5185:   /*   } */
                   5186:   /*   printf("\n"); */
                   5187:   /*   fprintf(ficlog,"\n"); */
                   5188:   /* } */
                   5189: 
1.126     brouard  5190:   /* Recompute Inverse */
1.203     brouard  5191:   /* for (i=1;i<=npar;i++) */
                   5192:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   5193:   /* ludcmp(a,npar,indx,&pd); */
                   5194: 
                   5195:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   5196: 
                   5197:   /* for (j=1;j<=npar;j++) { */
                   5198:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   5199:   /*   x[j]=1; */
                   5200:   /*   lubksb(a,npar,indx,x); */
                   5201:   /*   for (i=1;i<=npar;i++){  */
                   5202:   /*     y[i][j]=x[i]; */
                   5203:   /*     printf("%.3e ",y[i][j]); */
                   5204:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   5205:   /*   } */
                   5206:   /*   printf("\n"); */
                   5207:   /*   fprintf(ficlog,"\n"); */
                   5208:   /* } */
                   5209: 
                   5210:   /* Verifying the inverse matrix */
                   5211: #ifdef DEBUGHESS
                   5212:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  5213: 
1.203     brouard  5214:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   5215:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  5216: 
                   5217:   for (j=1;j<=npar;j++) {
                   5218:     for (i=1;i<=npar;i++){ 
1.203     brouard  5219:       printf("%.2f ",y[i][j]);
                   5220:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  5221:     }
                   5222:     printf("\n");
                   5223:     fprintf(ficlog,"\n");
                   5224:   }
1.203     brouard  5225: #endif
1.126     brouard  5226: 
                   5227:   free_matrix(a,1,npar,1,npar);
                   5228:   free_matrix(y,1,npar,1,npar);
                   5229:   free_vector(x,1,npar);
                   5230:   free_ivector(indx,1,npar);
1.203     brouard  5231:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  5232: 
                   5233: 
                   5234: }
                   5235: 
                   5236: /*************** hessian matrix ****************/
                   5237: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  5238: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  5239:   int i;
                   5240:   int l=1, lmax=20;
1.203     brouard  5241:   double k1,k2, res, fx;
1.132     brouard  5242:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  5243:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   5244:   int k=0,kmax=10;
                   5245:   double l1;
                   5246: 
                   5247:   fx=func(x);
                   5248:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  5249:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  5250:     l1=pow(10,l);
                   5251:     delts=delt;
                   5252:     for(k=1 ; k <kmax; k=k+1){
                   5253:       delt = delta*(l1*k);
                   5254:       p2[theta]=x[theta] +delt;
1.145     brouard  5255:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  5256:       p2[theta]=x[theta]-delt;
                   5257:       k2=func(p2)-fx;
                   5258:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  5259:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  5260:       
1.203     brouard  5261: #ifdef DEBUGHESSII
1.126     brouard  5262:       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);
                   5263:       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);
                   5264: #endif
                   5265:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   5266:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   5267:        k=kmax;
                   5268:       }
                   5269:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  5270:        k=kmax; l=lmax*10;
1.126     brouard  5271:       }
                   5272:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   5273:        delts=delt;
                   5274:       }
1.203     brouard  5275:     } /* End loop k */
1.126     brouard  5276:   }
                   5277:   delti[theta]=delts;
                   5278:   return res; 
                   5279:   
                   5280: }
                   5281: 
1.203     brouard  5282: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  5283: {
                   5284:   int i;
1.164     brouard  5285:   int l=1, lmax=20;
1.126     brouard  5286:   double k1,k2,k3,k4,res,fx;
1.132     brouard  5287:   double p2[MAXPARM+1];
1.203     brouard  5288:   int k, kmax=1;
                   5289:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  5290: 
                   5291:   int firstime=0;
1.203     brouard  5292:   
1.126     brouard  5293:   fx=func(x);
1.203     brouard  5294:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  5295:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  5296:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   5297:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  5298:     k1=func(p2)-fx;
                   5299:   
1.203     brouard  5300:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   5301:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  5302:     k2=func(p2)-fx;
                   5303:   
1.203     brouard  5304:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   5305:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  5306:     k3=func(p2)-fx;
                   5307:   
1.203     brouard  5308:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   5309:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  5310:     k4=func(p2)-fx;
1.203     brouard  5311:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   5312:     if(k1*k2*k3*k4 <0.){
1.208     brouard  5313:       firstime=1;
1.203     brouard  5314:       kmax=kmax+10;
1.208     brouard  5315:     }
                   5316:     if(kmax >=10 || firstime ==1){
1.354     brouard  5317:       /* What are the thetai and thetaj? thetai/ncovmodel thetai=(thetai-thetai%ncovmodel)/ncovmodel +thetai%ncovmodel=(line,pos)  */
1.246     brouard  5318:       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);
                   5319:       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  5320:       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);
                   5321:       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);
                   5322:     }
                   5323: #ifdef DEBUGHESSIJ
                   5324:     v1=hess[thetai][thetai];
                   5325:     v2=hess[thetaj][thetaj];
                   5326:     cv12=res;
                   5327:     /* Computing eigen value of Hessian matrix */
                   5328:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5329:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5330:     if ((lc2 <0) || (lc1 <0) ){
                   5331:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   5332:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   5333:       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);
                   5334:       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);
                   5335:     }
1.126     brouard  5336: #endif
                   5337:   }
                   5338:   return res;
                   5339: }
                   5340: 
1.203     brouard  5341:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   5342: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   5343: /* { */
                   5344: /*   int i; */
                   5345: /*   int l=1, lmax=20; */
                   5346: /*   double k1,k2,k3,k4,res,fx; */
                   5347: /*   double p2[MAXPARM+1]; */
                   5348: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   5349: /*   int k=0,kmax=10; */
                   5350: /*   double l1; */
                   5351:   
                   5352: /*   fx=func(x); */
                   5353: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   5354: /*     l1=pow(10,l); */
                   5355: /*     delts=delt; */
                   5356: /*     for(k=1 ; k <kmax; k=k+1){ */
                   5357: /*       delt = delti*(l1*k); */
                   5358: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   5359: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   5360: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   5361: /*       k1=func(p2)-fx; */
                   5362:       
                   5363: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   5364: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   5365: /*       k2=func(p2)-fx; */
                   5366:       
                   5367: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   5368: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   5369: /*       k3=func(p2)-fx; */
                   5370:       
                   5371: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   5372: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   5373: /*       k4=func(p2)-fx; */
                   5374: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   5375: /* #ifdef DEBUGHESSIJ */
                   5376: /*       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); */
                   5377: /*       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); */
                   5378: /* #endif */
                   5379: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   5380: /*     k=kmax; */
                   5381: /*       } */
                   5382: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   5383: /*     k=kmax; l=lmax*10; */
                   5384: /*       } */
                   5385: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   5386: /*     delts=delt; */
                   5387: /*       } */
                   5388: /*     } /\* End loop k *\/ */
                   5389: /*   } */
                   5390: /*   delti[theta]=delts; */
                   5391: /*   return res;  */
                   5392: /* } */
                   5393: 
                   5394: 
1.126     brouard  5395: /************** Inverse of matrix **************/
                   5396: void ludcmp(double **a, int n, int *indx, double *d) 
                   5397: { 
                   5398:   int i,imax,j,k; 
                   5399:   double big,dum,sum,temp; 
                   5400:   double *vv; 
                   5401:  
                   5402:   vv=vector(1,n); 
                   5403:   *d=1.0; 
                   5404:   for (i=1;i<=n;i++) { 
                   5405:     big=0.0; 
                   5406:     for (j=1;j<=n;j++) 
                   5407:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  5408:     if (big == 0.0){
                   5409:       printf(" Singular Hessian matrix at row %d:\n",i);
                   5410:       for (j=1;j<=n;j++) {
                   5411:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   5412:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   5413:       }
                   5414:       fflush(ficlog);
                   5415:       fclose(ficlog);
                   5416:       nrerror("Singular matrix in routine ludcmp"); 
                   5417:     }
1.126     brouard  5418:     vv[i]=1.0/big; 
                   5419:   } 
                   5420:   for (j=1;j<=n;j++) { 
                   5421:     for (i=1;i<j;i++) { 
                   5422:       sum=a[i][j]; 
                   5423:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   5424:       a[i][j]=sum; 
                   5425:     } 
                   5426:     big=0.0; 
                   5427:     for (i=j;i<=n;i++) { 
                   5428:       sum=a[i][j]; 
                   5429:       for (k=1;k<j;k++) 
                   5430:        sum -= a[i][k]*a[k][j]; 
                   5431:       a[i][j]=sum; 
                   5432:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   5433:        big=dum; 
                   5434:        imax=i; 
                   5435:       } 
                   5436:     } 
                   5437:     if (j != imax) { 
                   5438:       for (k=1;k<=n;k++) { 
                   5439:        dum=a[imax][k]; 
                   5440:        a[imax][k]=a[j][k]; 
                   5441:        a[j][k]=dum; 
                   5442:       } 
                   5443:       *d = -(*d); 
                   5444:       vv[imax]=vv[j]; 
                   5445:     } 
                   5446:     indx[j]=imax; 
                   5447:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   5448:     if (j != n) { 
                   5449:       dum=1.0/(a[j][j]); 
                   5450:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   5451:     } 
                   5452:   } 
                   5453:   free_vector(vv,1,n);  /* Doesn't work */
                   5454: ;
                   5455: } 
                   5456: 
                   5457: void lubksb(double **a, int n, int *indx, double b[]) 
                   5458: { 
                   5459:   int i,ii=0,ip,j; 
                   5460:   double sum; 
                   5461:  
                   5462:   for (i=1;i<=n;i++) { 
                   5463:     ip=indx[i]; 
                   5464:     sum=b[ip]; 
                   5465:     b[ip]=b[i]; 
                   5466:     if (ii) 
                   5467:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   5468:     else if (sum) ii=i; 
                   5469:     b[i]=sum; 
                   5470:   } 
                   5471:   for (i=n;i>=1;i--) { 
                   5472:     sum=b[i]; 
                   5473:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   5474:     b[i]=sum/a[i][i]; 
                   5475:   } 
                   5476: } 
                   5477: 
                   5478: void pstamp(FILE *fichier)
                   5479: {
1.196     brouard  5480:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  5481: }
                   5482: 
1.297     brouard  5483: void date2dmy(double date,double *day, double *month, double *year){
                   5484:   double yp=0., yp1=0., yp2=0.;
                   5485:   
                   5486:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   5487:                        fractional in yp1 */
                   5488:   *year=yp;
                   5489:   yp2=modf((yp1*12),&yp);
                   5490:   *month=yp;
                   5491:   yp1=modf((yp2*30.5),&yp);
                   5492:   *day=yp;
                   5493:   if(*day==0) *day=1;
                   5494:   if(*month==0) *month=1;
                   5495: }
                   5496: 
1.253     brouard  5497: 
                   5498: 
1.126     brouard  5499: /************ Frequencies ********************/
1.251     brouard  5500: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  5501:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   5502:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  5503: {  /* Some frequencies as well as proposing some starting values */
1.332     brouard  5504:   /* Frequencies of any combination of dummy covariate used in the model equation */ 
1.265     brouard  5505:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  5506:   int iind=0, iage=0;
                   5507:   int mi; /* Effective wave */
                   5508:   int first;
                   5509:   double ***freq; /* Frequencies */
1.268     brouard  5510:   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 */
                   5511:   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  5512:   double *meanq, *stdq, *idq;
1.226     brouard  5513:   double **meanqt;
                   5514:   double *pp, **prop, *posprop, *pospropt;
                   5515:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   5516:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   5517:   double agebegin, ageend;
                   5518:     
                   5519:   pp=vector(1,nlstate);
1.251     brouard  5520:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  5521:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   5522:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   5523:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   5524:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  5525:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  5526:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  5527:   meanqt=matrix(1,lastpass,1,nqtveff);
                   5528:   strcpy(fileresp,"P_");
                   5529:   strcat(fileresp,fileresu);
                   5530:   /*strcat(fileresphtm,fileresu);*/
                   5531:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   5532:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   5533:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   5534:     exit(0);
                   5535:   }
1.240     brouard  5536:   
1.226     brouard  5537:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   5538:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   5539:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5540:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5541:     fflush(ficlog);
                   5542:     exit(70); 
                   5543:   }
                   5544:   else{
                   5545:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  5546: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  5547: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5548:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5549:   }
1.319     brouard  5550:   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  5551:   
1.226     brouard  5552:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   5553:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   5554:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5555:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5556:     fflush(ficlog);
                   5557:     exit(70); 
1.240     brouard  5558:   } else{
1.226     brouard  5559:     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  5560: ,<hr size=\"2\" color=\"#EC5E5E\"> \n                                  \
1.214     brouard  5561: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5562:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5563:   }
1.319     brouard  5564:   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  5565:   
1.253     brouard  5566:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   5567:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  5568:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  5569:   j1=0;
1.126     brouard  5570:   
1.227     brouard  5571:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
1.335     brouard  5572:   j=cptcoveff;  /* Only simple dummy covariates used in the model */
1.330     brouard  5573:   /* j=cptcovn;  /\* Only dummy covariates of the model *\/ */
1.226     brouard  5574:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  5575:   
                   5576:   
1.226     brouard  5577:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   5578:      reference=low_education V1=0,V2=0
                   5579:      med_educ                V1=1 V2=0, 
                   5580:      high_educ               V1=0 V2=1
1.330     brouard  5581:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcovn 
1.226     brouard  5582:   */
1.249     brouard  5583:   dateintsum=0;
                   5584:   k2cpt=0;
                   5585: 
1.253     brouard  5586:   if(cptcoveff == 0 )
1.265     brouard  5587:     nl=1;  /* Constant and age model only */
1.253     brouard  5588:   else
                   5589:     nl=2;
1.265     brouard  5590: 
                   5591:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   5592:   /* Loop on nj=1 or 2 if dummy covariates j!=0
1.335     brouard  5593:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
1.265     brouard  5594:    *     freq[s1][s2][iage] =0.
                   5595:    *     Loop on iind
                   5596:    *       ++freq[s1][s2][iage] weighted
                   5597:    *     end iind
                   5598:    *     if covariate and j!0
                   5599:    *       headers Variable on one line
                   5600:    *     endif cov j!=0
                   5601:    *     header of frequency table by age
                   5602:    *     Loop on age
                   5603:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   5604:    *       pos+=freq[s1][s2][iage] weighted
                   5605:    *       Loop on s1 initial state
                   5606:    *         fprintf(ficresp
                   5607:    *       end s1
                   5608:    *     end age
                   5609:    *     if j!=0 computes starting values
                   5610:    *     end compute starting values
                   5611:    *   end j1
                   5612:    * end nl 
                   5613:    */
1.253     brouard  5614:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   5615:     if(nj==1)
                   5616:       j=0;  /* First pass for the constant */
1.265     brouard  5617:     else{
1.335     brouard  5618:       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  5619:     }
1.251     brouard  5620:     first=1;
1.332     brouard  5621:     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  5622:       posproptt=0.;
1.330     brouard  5623:       /*printf("cptcovn=%d Tvaraff=%d", cptcovn,Tvaraff[1]);
1.251     brouard  5624:        scanf("%d", i);*/
                   5625:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  5626:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  5627:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  5628:            freq[i][s2][m]=0;
1.251     brouard  5629:       
                   5630:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  5631:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  5632:          prop[i][m]=0;
                   5633:        posprop[i]=0;
                   5634:        pospropt[i]=0;
                   5635:       }
1.283     brouard  5636:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  5637:         idq[z1]=0.;
                   5638:         meanq[z1]=0.;
                   5639:         stdq[z1]=0.;
1.283     brouard  5640:       }
                   5641:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  5642:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  5643:       /*         meanqt[m][z1]=0.; */
                   5644:       /*       } */
                   5645:       /* }       */
1.251     brouard  5646:       /* dateintsum=0; */
                   5647:       /* k2cpt=0; */
                   5648:       
1.265     brouard  5649:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  5650:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   5651:        bool=1;
                   5652:        if(j !=0){
                   5653:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.335     brouard  5654:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   5655:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
1.251     brouard  5656:                /* if(Tvaraff[z1] ==-20){ */
                   5657:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   5658:                /* }else  if(Tvaraff[z1] ==-10){ */
                   5659:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
1.330     brouard  5660:                /* }else  */ /* TODO TODO codtabm(j1,z1) or codtabm(j1,Tvaraff[z1]]z1)*/
1.335     brouard  5661:                /* 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); */
                   5662:                if(Tvaraff[z1]<1 || Tvaraff[z1]>=NCOVMAX)
1.338     brouard  5663:                  printf("Error Tvaraff[z1]=%d<1 or >=%d, cptcoveff=%d model=1+age+%s\n",Tvaraff[z1],NCOVMAX, cptcoveff, model);
1.332     brouard  5664:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]){ /* for combination j1 of covariates */
1.265     brouard  5665:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  5666:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
1.332     brouard  5667:                  /* 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", */
                   5668:                  /*   bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),*/
                   5669:                   /*   j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
1.251     brouard  5670:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   5671:                } /* Onlyf fixed */
                   5672:              } /* end z1 */
1.335     brouard  5673:            } /* cptcoveff > 0 */
1.251     brouard  5674:          } /* end any */
                   5675:        }/* end j==0 */
1.265     brouard  5676:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  5677:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  5678:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  5679:            m=mw[mi][iind];
                   5680:            if(j!=0){
                   5681:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
1.335     brouard  5682:                for (z1=1; z1<=cptcoveff; z1++) {
1.251     brouard  5683:                  if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  5684:                    /* iv= Tvar[Tmodelind[z1]]-ncovcol-nqv; /\* Good *\/ */
                   5685:                    iv= Tvar[Tmodelind[z1]]; /* Good *//* because cotvar starts now at first at ncovcol+nqv+ntv */ 
1.332     brouard  5686:                    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  5687:                                                                                      value is -1, we don't select. It differs from the 
                   5688:                                                                                      constant and age model which counts them. */
                   5689:                      bool=0; /* not selected */
                   5690:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
1.334     brouard  5691:                    /* i1=Tvaraff[z1]; */
                   5692:                    /* i2=TnsdVar[i1]; */
                   5693:                    /* i3=nbcode[i1][i2]; */
                   5694:                    /* i4=covar[i1][iind]; */
                   5695:                    /* if(i4 != i3){ */
                   5696:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) { /* Bug valgrind */
1.251     brouard  5697:                      bool=0;
                   5698:                    }
                   5699:                  }
                   5700:                }
                   5701:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   5702:            } /* end j==0 */
                   5703:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  5704:            if(bool==1){ /*Selected */
1.251     brouard  5705:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   5706:                 and mw[mi+1][iind]. dh depends on stepm. */
                   5707:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   5708:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   5709:              if(m >=firstpass && m <=lastpass){
                   5710:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   5711:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   5712:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   5713:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   5714:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   5715:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   5716:                if (m<lastpass) {
                   5717:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   5718:                  /*   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]); */
                   5719:                  if(s[m][iind]==-1)
                   5720:                    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.));
                   5721:                  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  5722:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
                   5723:                    if(!isnan(covar[ncovcol+z1][iind])){
1.332     brouard  5724:                      idq[z1]=idq[z1]+weight[iind];
                   5725:                      meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   5726:                      /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
                   5727:                      stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
1.311     brouard  5728:                    }
1.284     brouard  5729:                  }
1.251     brouard  5730:                  /* if((int)agev[m][iind] == 55) */
                   5731:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   5732:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   5733:                  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  5734:                }
1.251     brouard  5735:              } /* end if between passes */  
                   5736:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   5737:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   5738:                k2cpt++;
                   5739:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  5740:              }
1.251     brouard  5741:            }else{
                   5742:              bool=1;
                   5743:            }/* end bool 2 */
                   5744:          } /* end m */
1.284     brouard  5745:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   5746:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   5747:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   5748:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   5749:          /* } */
1.251     brouard  5750:        } /* end bool */
                   5751:       } /* end iind = 1 to imx */
1.319     brouard  5752:       /* prop[s][age] is fed for any initial and valid live state as well as
1.251     brouard  5753:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   5754:       
                   5755:       
                   5756:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.335     brouard  5757:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
1.265     brouard  5758:         pstamp(ficresp);
1.335     brouard  5759:       if  (cptcoveff>0 && j!=0){
1.265     brouard  5760:         pstamp(ficresp);
1.251     brouard  5761:        printf( "\n#********** Variable "); 
                   5762:        fprintf(ficresp, "\n#********** Variable "); 
                   5763:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   5764:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   5765:        fprintf(ficlog, "\n#********** Variable "); 
1.340     brouard  5766:        for (z1=1; z1<=cptcoveff; z1++){
1.251     brouard  5767:          if(!FixedV[Tvaraff[z1]]){
1.330     brouard  5768:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5769:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5770:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5771:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5772:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.250     brouard  5773:          }else{
1.330     brouard  5774:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5775:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5776:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5777:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5778:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.251     brouard  5779:          }
                   5780:        }
                   5781:        printf( "**********\n#");
                   5782:        fprintf(ficresp, "**********\n#");
                   5783:        fprintf(ficresphtm, "**********</h3>\n");
                   5784:        fprintf(ficresphtmfr, "**********</h3>\n");
                   5785:        fprintf(ficlog, "**********\n");
                   5786:       }
1.284     brouard  5787:       /*
                   5788:        Printing means of quantitative variables if any
                   5789:       */
                   5790:       for (z1=1; z1<= nqfveff; z1++) {
1.311     brouard  5791:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.312     brouard  5792:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
1.284     brouard  5793:        if(weightopt==1){
                   5794:          printf(" Weighted mean and standard deviation of");
                   5795:          fprintf(ficlog," Weighted mean and standard deviation of");
                   5796:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   5797:        }
1.311     brouard  5798:        /* mu = \frac{w x}{\sum w}
                   5799:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
                   5800:        */
                   5801:        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]));
                   5802:        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]));
                   5803:        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  5804:       }
                   5805:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   5806:       /*       for(m=1;m<=lastpass;m++){ */
                   5807:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   5808:       /*   } */
                   5809:       /* } */
1.283     brouard  5810: 
1.251     brouard  5811:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.335     brouard  5812:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
1.265     brouard  5813:         fprintf(ficresp, " Age");
1.335     brouard  5814:       if(nj==2) for (z1=1; z1<=cptcoveff; z1++) {
                   5815:          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]]);
                   5816:          fprintf(ficresp, " V%d=%d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5817:        }
1.251     brouard  5818:       for(i=1; i<=nlstate;i++) {
1.335     brouard  5819:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  5820:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   5821:       }
1.335     brouard  5822:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  5823:       fprintf(ficresphtm, "\n");
                   5824:       
                   5825:       /* Header of frequency table by age */
                   5826:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   5827:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  5828:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  5829:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5830:          if(s2!=0 && m!=0)
                   5831:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  5832:        }
1.226     brouard  5833:       }
1.251     brouard  5834:       fprintf(ficresphtmfr, "\n");
                   5835:     
                   5836:       /* For each age */
                   5837:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   5838:        fprintf(ficresphtm,"<tr>");
                   5839:        if(iage==iagemax+1){
                   5840:          fprintf(ficlog,"1");
                   5841:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   5842:        }else if(iage==iagemax+2){
                   5843:          fprintf(ficlog,"0");
                   5844:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   5845:        }else if(iage==iagemax+3){
                   5846:          fprintf(ficlog,"Total");
                   5847:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   5848:        }else{
1.240     brouard  5849:          if(first==1){
1.251     brouard  5850:            first=0;
                   5851:            printf("See log file for details...\n");
                   5852:          }
                   5853:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   5854:          fprintf(ficlog,"Age %d", iage);
                   5855:        }
1.265     brouard  5856:        for(s1=1; s1 <=nlstate ; s1++){
                   5857:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   5858:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  5859:        }
1.265     brouard  5860:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5861:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  5862:            pos += freq[s1][m][iage];
                   5863:          if(pp[s1]>=1.e-10){
1.251     brouard  5864:            if(first==1){
1.265     brouard  5865:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5866:            }
1.265     brouard  5867:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5868:          }else{
                   5869:            if(first==1)
1.265     brouard  5870:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   5871:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  5872:          }
                   5873:        }
                   5874:       
1.265     brouard  5875:        for(s1=1; s1 <=nlstate ; s1++){ 
                   5876:          /* posprop[s1]=0; */
                   5877:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   5878:            pp[s1] += freq[s1][m][iage];
                   5879:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   5880:       
                   5881:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   5882:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   5883:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5884:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5885:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5886:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5887:        }
                   5888:        
                   5889:        /* Writing ficresp */
1.335     brouard  5890:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5891:           if( iage <= iagemax){
                   5892:            fprintf(ficresp," %d",iage);
                   5893:           }
                   5894:         }else if( nj==2){
                   5895:           if( iage <= iagemax){
                   5896:            fprintf(ficresp," %d",iage);
1.335     brouard  5897:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.265     brouard  5898:           }
1.240     brouard  5899:        }
1.265     brouard  5900:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  5901:          if(pos>=1.e-5){
1.251     brouard  5902:            if(first==1)
1.265     brouard  5903:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   5904:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  5905:          }else{
                   5906:            if(first==1)
1.265     brouard  5907:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   5908:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  5909:          }
                   5910:          if( iage <= iagemax){
                   5911:            if(pos>=1.e-5){
1.335     brouard  5912:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5913:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5914:               }else if( nj==2){
                   5915:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5916:               }
                   5917:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5918:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   5919:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   5920:            } else{
1.335     brouard  5921:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
1.265     brouard  5922:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  5923:            }
1.240     brouard  5924:          }
1.265     brouard  5925:          pospropt[s1] +=posprop[s1];
                   5926:        } /* end loop s1 */
1.251     brouard  5927:        /* pospropt=0.; */
1.265     brouard  5928:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  5929:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5930:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  5931:              if(first==1){
1.265     brouard  5932:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5933:              }
1.265     brouard  5934:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   5935:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5936:            }
1.265     brouard  5937:            if(s1!=0 && m!=0)
                   5938:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  5939:          }
1.265     brouard  5940:        } /* end loop s1 */
1.251     brouard  5941:        posproptt=0.; 
1.265     brouard  5942:        for(s1=1; s1 <=nlstate; s1++){
                   5943:          posproptt += pospropt[s1];
1.251     brouard  5944:        }
                   5945:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  5946:        fprintf(ficresphtm,"</tr>\n");
1.335     brouard  5947:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
1.265     brouard  5948:          if(iage <= iagemax)
                   5949:            fprintf(ficresp,"\n");
1.240     brouard  5950:        }
1.251     brouard  5951:        if(first==1)
                   5952:          printf("Others in log...\n");
                   5953:        fprintf(ficlog,"\n");
                   5954:       } /* end loop age iage */
1.265     brouard  5955:       
1.251     brouard  5956:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  5957:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5958:        if(posproptt < 1.e-5){
1.265     brouard  5959:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  5960:        }else{
1.265     brouard  5961:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  5962:        }
1.226     brouard  5963:       }
1.251     brouard  5964:       fprintf(ficresphtm,"</tr>\n");
                   5965:       fprintf(ficresphtm,"</table>\n");
                   5966:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  5967:       if(posproptt < 1.e-5){
1.251     brouard  5968:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   5969:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  5970:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   5971:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  5972:        invalidvarcomb[j1]=1;
1.226     brouard  5973:       }else{
1.338     brouard  5974:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced (or no resultline).</p>",j1);
1.251     brouard  5975:        invalidvarcomb[j1]=0;
1.226     brouard  5976:       }
1.251     brouard  5977:       fprintf(ficresphtmfr,"</table>\n");
                   5978:       fprintf(ficlog,"\n");
                   5979:       if(j!=0){
                   5980:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  5981:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5982:          for(k=1; k <=(nlstate+ndeath); k++){
                   5983:            if (k != i) {
1.265     brouard  5984:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  5985:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  5986:                  if(j1==1){ /* All dummy covariates to zero */
                   5987:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   5988:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  5989:                    printf("%d%d ",i,k);
                   5990:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5991:                    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]));
                   5992:                    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]));
                   5993:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  5994:                  }
1.253     brouard  5995:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   5996:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   5997:                    x[iage]= (double)iage;
                   5998:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  5999:                    /* 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  6000:                  }
1.268     brouard  6001:                  /* Some are not finite, but linreg will ignore these ages */
                   6002:                  no=0;
1.253     brouard  6003:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  6004:                  pstart[s1]=b;
                   6005:                  pstart[s1-1]=a;
1.252     brouard  6006:                }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 */ 
                   6007:                  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]);
                   6008:                  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  6009:                  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  6010:                  printf("%d%d ",i,k);
                   6011:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  6012:                  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  6013:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   6014:                  ;
                   6015:                }
                   6016:                /* printf("%12.7f )", param[i][jj][k]); */
                   6017:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  6018:                s1++; 
1.251     brouard  6019:              } /* end jj */
                   6020:            } /* end k!= i */
                   6021:          } /* end k */
1.265     brouard  6022:        } /* end i, s1 */
1.251     brouard  6023:       } /* end j !=0 */
                   6024:     } /* end selected combination of covariate j1 */
                   6025:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   6026:       printf("#Freqsummary: Starting values for the constants:\n");
                   6027:       fprintf(ficlog,"\n");
1.265     brouard  6028:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  6029:        for(k=1; k <=(nlstate+ndeath); k++){
                   6030:          if (k != i) {
                   6031:            printf("%d%d ",i,k);
                   6032:            fprintf(ficlog,"%d%d ",i,k);
                   6033:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  6034:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  6035:              if(jj==1){ /* Age has to be done */
1.265     brouard  6036:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   6037:                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]));
                   6038:                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  6039:              }
                   6040:              /* printf("%12.7f )", param[i][jj][k]); */
                   6041:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  6042:              s1++; 
1.250     brouard  6043:            }
1.251     brouard  6044:            printf("\n");
                   6045:            fprintf(ficlog,"\n");
1.250     brouard  6046:          }
                   6047:        }
1.284     brouard  6048:       } /* end of state i */
1.251     brouard  6049:       printf("#Freqsummary\n");
                   6050:       fprintf(ficlog,"\n");
1.265     brouard  6051:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   6052:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   6053:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   6054:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   6055:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   6056:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   6057:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   6058:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  6059:          /* } */
                   6060:        }
1.265     brouard  6061:       } /* end loop s1 */
1.251     brouard  6062:       
                   6063:       printf("\n");
                   6064:       fprintf(ficlog,"\n");
                   6065:     } /* end j=0 */
1.249     brouard  6066:   } /* end j */
1.252     brouard  6067: 
1.253     brouard  6068:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  6069:     for(i=1, jk=1; i <=nlstate; i++){
                   6070:       for(j=1; j <=nlstate+ndeath; j++){
                   6071:        if(j!=i){
                   6072:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   6073:          printf("%1d%1d",i,j);
                   6074:          fprintf(ficparo,"%1d%1d",i,j);
                   6075:          for(k=1; k<=ncovmodel;k++){
                   6076:            /*    printf(" %lf",param[i][j][k]); */
                   6077:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   6078:            p[jk]=pstart[jk];
                   6079:            printf(" %f ",pstart[jk]);
                   6080:            fprintf(ficparo," %f ",pstart[jk]);
                   6081:            jk++;
                   6082:          }
                   6083:          printf("\n");
                   6084:          fprintf(ficparo,"\n");
                   6085:        }
                   6086:       }
                   6087:     }
                   6088:   } /* end mle=-2 */
1.226     brouard  6089:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  6090:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  6091:   
1.226     brouard  6092:   fclose(ficresp);
                   6093:   fclose(ficresphtm);
                   6094:   fclose(ficresphtmfr);
1.283     brouard  6095:   free_vector(idq,1,nqfveff);
1.226     brouard  6096:   free_vector(meanq,1,nqfveff);
1.284     brouard  6097:   free_vector(stdq,1,nqfveff);
1.226     brouard  6098:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  6099:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   6100:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  6101:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  6102:   free_vector(pospropt,1,nlstate);
                   6103:   free_vector(posprop,1,nlstate);
1.251     brouard  6104:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  6105:   free_vector(pp,1,nlstate);
                   6106:   /* End of freqsummary */
                   6107: }
1.126     brouard  6108: 
1.268     brouard  6109: /* Simple linear regression */
                   6110: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   6111: 
                   6112:   /* y=a+bx regression */
                   6113:   double   sumx = 0.0;                        /* sum of x                      */
                   6114:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   6115:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   6116:   double   sumy = 0.0;                        /* sum of y                      */
                   6117:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   6118:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   6119:   double yhat;
                   6120:   
                   6121:   double denom=0;
                   6122:   int i;
                   6123:   int ne=*no;
                   6124:   
                   6125:   for ( i=ifi, ne=0;i<=ila;i++) {
                   6126:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   6127:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   6128:       continue;
                   6129:     }
                   6130:     ne=ne+1;
                   6131:     sumx  += x[i];       
                   6132:     sumx2 += x[i]*x[i];  
                   6133:     sumxy += x[i] * y[i];
                   6134:     sumy  += y[i];      
                   6135:     sumy2 += y[i]*y[i]; 
                   6136:     denom = (ne * sumx2 - sumx*sumx);
                   6137:     /* 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); */
                   6138:   } 
                   6139:   
                   6140:   denom = (ne * sumx2 - sumx*sumx);
                   6141:   if (denom == 0) {
                   6142:     // vertical, slope m is infinity
                   6143:     *b = INFINITY;
                   6144:     *a = 0;
                   6145:     if (r) *r = 0;
                   6146:     return 1;
                   6147:   }
                   6148:   
                   6149:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   6150:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   6151:   if (r!=NULL) {
                   6152:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   6153:       sqrt((sumx2 - sumx*sumx/ne) *
                   6154:           (sumy2 - sumy*sumy/ne));
                   6155:   }
                   6156:   *no=ne;
                   6157:   for ( i=ifi, ne=0;i<=ila;i++) {
                   6158:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   6159:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   6160:       continue;
                   6161:     }
                   6162:     ne=ne+1;
                   6163:     yhat = y[i] - *a -*b* x[i];
                   6164:     sume2  += yhat * yhat ;       
                   6165:     
                   6166:     denom = (ne * sumx2 - sumx*sumx);
                   6167:     /* 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); */
                   6168:   } 
                   6169:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   6170:   *sa= *sb * sqrt(sumx2/ne);
                   6171:   
                   6172:   return 0; 
                   6173: }
                   6174: 
1.126     brouard  6175: /************ Prevalence ********************/
1.227     brouard  6176: 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)
                   6177: {  
                   6178:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   6179:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   6180:      We still use firstpass and lastpass as another selection.
                   6181:   */
1.126     brouard  6182:  
1.227     brouard  6183:   int i, m, jk, j1, bool, z1,j, iv;
                   6184:   int mi; /* Effective wave */
                   6185:   int iage;
                   6186:   double agebegin, ageend;
                   6187: 
                   6188:   double **prop;
                   6189:   double posprop; 
                   6190:   double  y2; /* in fractional years */
                   6191:   int iagemin, iagemax;
                   6192:   int first; /** to stop verbosity which is redirected to log file */
                   6193: 
                   6194:   iagemin= (int) agemin;
                   6195:   iagemax= (int) agemax;
                   6196:   /*pp=vector(1,nlstate);*/
1.251     brouard  6197:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  6198:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   6199:   j1=0;
1.222     brouard  6200:   
1.227     brouard  6201:   /*j=cptcoveff;*/
                   6202:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  6203:   
1.288     brouard  6204:   first=0;
1.335     brouard  6205:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of simple dummy covariates */
1.227     brouard  6206:     for (i=1; i<=nlstate; i++)  
1.251     brouard  6207:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  6208:        prop[i][iage]=0.0;
                   6209:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   6210:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   6211:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   6212:     
                   6213:     for (i=1; i<=imx; i++) { /* Each individual */
                   6214:       bool=1;
                   6215:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   6216:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   6217:        m=mw[mi][i];
                   6218:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   6219:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   6220:        for (z1=1; z1<=cptcoveff; z1++){
                   6221:          if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  6222:            iv= Tvar[Tmodelind[z1]];/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
1.332     brouard  6223:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality */
1.227     brouard  6224:              bool=0;
                   6225:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
1.332     brouard  6226:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) {
1.227     brouard  6227:              bool=0;
                   6228:            }
                   6229:        }
                   6230:        if(bool==1){ /* Otherwise we skip that wave/person */
                   6231:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   6232:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   6233:          if(m >=firstpass && m <=lastpass){
                   6234:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   6235:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   6236:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   6237:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  6238:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  6239:                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); 
                   6240:                exit(1);
                   6241:              }
                   6242:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   6243:                /*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]]);*/
                   6244:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   6245:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   6246:              } /* end valid statuses */ 
                   6247:            } /* end selection of dates */
                   6248:          } /* end selection of waves */
                   6249:        } /* end bool */
                   6250:       } /* end wave */
                   6251:     } /* end individual */
                   6252:     for(i=iagemin; i <= iagemax+3; i++){  
                   6253:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   6254:        posprop += prop[jk][i]; 
                   6255:       } 
                   6256:       
                   6257:       for(jk=1; jk <=nlstate ; jk++){      
                   6258:        if( i <=  iagemax){ 
                   6259:          if(posprop>=1.e-5){ 
                   6260:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   6261:          } else{
1.288     brouard  6262:            if(!first){
                   6263:              first=1;
1.266     brouard  6264:              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]);
                   6265:            }else{
1.288     brouard  6266:              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  6267:            }
                   6268:          }
                   6269:        } 
                   6270:       }/* end jk */ 
                   6271:     }/* end i */ 
1.222     brouard  6272:      /*} *//* end i1 */
1.227     brouard  6273:   } /* end j1 */
1.222     brouard  6274:   
1.227     brouard  6275:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   6276:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  6277:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  6278: }  /* End of prevalence */
1.126     brouard  6279: 
                   6280: /************* Waves Concatenation ***************/
                   6281: 
                   6282: 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)
                   6283: {
1.298     brouard  6284:   /* 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  6285:      Death is a valid wave (if date is known).
                   6286:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   6287:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  6288:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  6289:   */
1.126     brouard  6290: 
1.224     brouard  6291:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  6292:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   6293:      double sum=0., jmean=0.;*/
1.224     brouard  6294:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  6295:   int j, k=0,jk, ju, jl;
                   6296:   double sum=0.;
                   6297:   first=0;
1.214     brouard  6298:   firstwo=0;
1.217     brouard  6299:   firsthree=0;
1.218     brouard  6300:   firstfour=0;
1.164     brouard  6301:   jmin=100000;
1.126     brouard  6302:   jmax=-1;
                   6303:   jmean=0.;
1.224     brouard  6304: 
                   6305: /* Treating live states */
1.214     brouard  6306:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  6307:     mi=0;  /* First valid wave */
1.227     brouard  6308:     mli=0; /* Last valid wave */
1.309     brouard  6309:     m=firstpass;  /* Loop on waves */
                   6310:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
1.227     brouard  6311:       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 */
                   6312:        mli=m-1;/* mw[++mi][i]=m-1; */
                   6313:       }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  6314:        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  6315:        mli=m;
1.224     brouard  6316:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   6317:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  6318:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  6319:       }
1.309     brouard  6320:       else{ /* m = lastpass, eventual special issue with warning */
1.224     brouard  6321: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  6322:        break;
1.224     brouard  6323: #else
1.317     brouard  6324:        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  6325:          if(firsthree == 0){
1.302     brouard  6326:            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  6327:            firsthree=1;
1.317     brouard  6328:          }else if(firsthree >=1 && firsthree < 10){
                   6329:            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);
                   6330:            firsthree++;
                   6331:          }else if(firsthree == 10){
                   6332:            printf("Information, too many Information flags: no more reported to log either\n");
                   6333:            fprintf(ficlog,"Information, too many Information flags: no more reported to log either\n");
                   6334:            firsthree++;
                   6335:          }else{
                   6336:            firsthree++;
1.227     brouard  6337:          }
1.309     brouard  6338:          mw[++mi][i]=m; /* Valid transition with unknown status */
1.227     brouard  6339:          mli=m;
                   6340:        }
                   6341:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   6342:          nbwarn++;
1.309     brouard  6343:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
1.227     brouard  6344:            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);
                   6345:            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);
                   6346:          }
                   6347:          break;
                   6348:        }
                   6349:        break;
1.224     brouard  6350: #endif
1.227     brouard  6351:       }/* End m >= lastpass */
1.126     brouard  6352:     }/* end while */
1.224     brouard  6353: 
1.227     brouard  6354:     /* 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  6355:     /* After last pass */
1.224     brouard  6356: /* Treating death states */
1.214     brouard  6357:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  6358:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   6359:       /* } */
1.126     brouard  6360:       mi++;    /* Death is another wave */
                   6361:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  6362:       /* Only death is a correct wave */
1.126     brouard  6363:       mw[mi][i]=m;
1.257     brouard  6364:     } /* else not in a death state */
1.224     brouard  6365: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  6366:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  6367:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.309     brouard  6368:        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  6369:          nbwarn++;
                   6370:          if(firstfiv==0){
1.309     brouard  6371:            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  6372:            firstfiv=1;
                   6373:          }else{
1.309     brouard  6374:            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  6375:          }
1.309     brouard  6376:            s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
                   6377:        }else{ /* Month of Death occured afer last wave month, potential bias */
1.227     brouard  6378:          nberr++;
                   6379:          if(firstwo==0){
1.309     brouard  6380:            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  6381:            firstwo=1;
                   6382:          }
1.309     brouard  6383:          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  6384:        }
1.257     brouard  6385:       }else{ /* if date of interview is unknown */
1.227     brouard  6386:        /* death is known but not confirmed by death status at any wave */
                   6387:        if(firstfour==0){
1.309     brouard  6388:          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  6389:          firstfour=1;
                   6390:        }
1.309     brouard  6391:        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  6392:       }
1.224     brouard  6393:     } /* end if date of death is known */
                   6394: #endif
1.309     brouard  6395:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
                   6396:     /* wav[i]=mw[mi][i];   */
1.126     brouard  6397:     if(mi==0){
                   6398:       nbwarn++;
                   6399:       if(first==0){
1.227     brouard  6400:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   6401:        first=1;
1.126     brouard  6402:       }
                   6403:       if(first==1){
1.227     brouard  6404:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  6405:       }
                   6406:     } /* end mi==0 */
                   6407:   } /* End individuals */
1.214     brouard  6408:   /* wav and mw are no more changed */
1.223     brouard  6409:        
1.317     brouard  6410:   printf("Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   6411:   fprintf(ficlog,"Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   6412: 
                   6413: 
1.126     brouard  6414:   for(i=1; i<=imx; i++){
                   6415:     for(mi=1; mi<wav[i];mi++){
                   6416:       if (stepm <=0)
1.227     brouard  6417:        dh[mi][i]=1;
1.126     brouard  6418:       else{
1.260     brouard  6419:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  6420:          if (agedc[i] < 2*AGESUP) {
                   6421:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   6422:            if(j==0) j=1;  /* Survives at least one month after exam */
                   6423:            else if(j<0){
                   6424:              nberr++;
                   6425:              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]);
                   6426:              j=1; /* Temporary Dangerous patch */
                   6427:              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);
                   6428:              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]);
                   6429:              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);
                   6430:            }
                   6431:            k=k+1;
                   6432:            if (j >= jmax){
                   6433:              jmax=j;
                   6434:              ijmax=i;
                   6435:            }
                   6436:            if (j <= jmin){
                   6437:              jmin=j;
                   6438:              ijmin=i;
                   6439:            }
                   6440:            sum=sum+j;
                   6441:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   6442:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   6443:          }
                   6444:        }
                   6445:        else{
                   6446:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  6447: /*       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  6448:                                        
1.227     brouard  6449:          k=k+1;
                   6450:          if (j >= jmax) {
                   6451:            jmax=j;
                   6452:            ijmax=i;
                   6453:          }
                   6454:          else if (j <= jmin){
                   6455:            jmin=j;
                   6456:            ijmin=i;
                   6457:          }
                   6458:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   6459:          /*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]);*/
                   6460:          if(j<0){
                   6461:            nberr++;
                   6462:            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]);
                   6463:            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]);
                   6464:          }
                   6465:          sum=sum+j;
                   6466:        }
                   6467:        jk= j/stepm;
                   6468:        jl= j -jk*stepm;
                   6469:        ju= j -(jk+1)*stepm;
                   6470:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   6471:          if(jl==0){
                   6472:            dh[mi][i]=jk;
                   6473:            bh[mi][i]=0;
                   6474:          }else{ /* We want a negative bias in order to only have interpolation ie
                   6475:                  * to avoid the price of an extra matrix product in likelihood */
                   6476:            dh[mi][i]=jk+1;
                   6477:            bh[mi][i]=ju;
                   6478:          }
                   6479:        }else{
                   6480:          if(jl <= -ju){
                   6481:            dh[mi][i]=jk;
                   6482:            bh[mi][i]=jl;       /* bias is positive if real duration
                   6483:                                 * is higher than the multiple of stepm and negative otherwise.
                   6484:                                 */
                   6485:          }
                   6486:          else{
                   6487:            dh[mi][i]=jk+1;
                   6488:            bh[mi][i]=ju;
                   6489:          }
                   6490:          if(dh[mi][i]==0){
                   6491:            dh[mi][i]=1; /* At least one step */
                   6492:            bh[mi][i]=ju; /* At least one step */
                   6493:            /*  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);*/
                   6494:          }
                   6495:        } /* end if mle */
1.126     brouard  6496:       }
                   6497:     } /* end wave */
                   6498:   }
                   6499:   jmean=sum/k;
                   6500:   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  6501:   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  6502: }
1.126     brouard  6503: 
                   6504: /*********** Tricode ****************************/
1.220     brouard  6505:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  6506:  {
                   6507:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   6508:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   6509:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   6510:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   6511:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   6512:     */
1.130     brouard  6513: 
1.242     brouard  6514:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   6515:    int modmaxcovj=0; /* Modality max of covariates j */
                   6516:    int cptcode=0; /* Modality max of covariates j */
                   6517:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  6518: 
                   6519: 
1.242     brouard  6520:    /* cptcoveff=0;  */
                   6521:    /* *cptcov=0; */
1.126     brouard  6522:  
1.242     brouard  6523:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  6524:    for (k=1; k <= maxncov; k++)
                   6525:      for(j=1; j<=2; j++)
                   6526:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  6527: 
1.242     brouard  6528:    /* Loop on covariates without age and products and no quantitative variable */
1.335     brouard  6529:    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  6530:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
1.343     brouard  6531:      /* printf("Testing k=%d, cptcovt=%d\n",k, cptcovt); */
1.349     brouard  6532:      if(Dummy[k]==0 && Typevar[k] !=1 && Typevar[k] != 3  && Typevar[k] != 2){ /* Dummy covariate and not age product nor fixed product */ 
1.242     brouard  6533:        switch(Fixed[k]) {
                   6534:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.311     brouard  6535:         modmaxcovj=0;
                   6536:         modmincovj=0;
1.242     brouard  6537:         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  6538:           /* 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  6539:           ij=(int)(covar[Tvar[k]][i]);
                   6540:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   6541:            * If product of Vn*Vm, still boolean *:
                   6542:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   6543:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   6544:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   6545:              modality of the nth covariate of individual i. */
                   6546:           if (ij > modmaxcovj)
                   6547:             modmaxcovj=ij; 
                   6548:           else if (ij < modmincovj) 
                   6549:             modmincovj=ij; 
1.287     brouard  6550:           if (ij <0 || ij >1 ){
1.311     brouard  6551:             printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6552:             fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6553:             fflush(ficlog);
                   6554:             exit(1);
1.287     brouard  6555:           }
                   6556:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  6557:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   6558:             exit(1);
                   6559:           }else
                   6560:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   6561:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   6562:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   6563:           /* getting the maximum value of the modality of the covariate
                   6564:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   6565:              female ies 1, then modmaxcovj=1.
                   6566:           */
                   6567:         } /* end for loop on individuals i */
                   6568:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6569:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6570:         cptcode=modmaxcovj;
                   6571:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   6572:         /*for (i=0; i<=cptcode; i++) {*/
                   6573:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   6574:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6575:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6576:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   6577:             if( j != -1){
                   6578:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   6579:                                  covariate for which somebody answered excluding 
                   6580:                                  undefined. Usually 2: 0 and 1. */
                   6581:             }
                   6582:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   6583:                                     covariate for which somebody answered including 
                   6584:                                     undefined. Usually 3: -1, 0 and 1. */
                   6585:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   6586:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   6587:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  6588:                        
1.242     brouard  6589:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   6590:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   6591:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   6592:         /* modmincovj=3; modmaxcovj = 7; */
                   6593:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   6594:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   6595:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   6596:         /* nbcode[Tvar[j]][ij]=k; */
                   6597:         /* nbcode[Tvar[j]][1]=0; */
                   6598:         /* nbcode[Tvar[j]][2]=1; */
                   6599:         /* nbcode[Tvar[j]][3]=2; */
                   6600:         /* To be continued (not working yet). */
                   6601:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  6602: 
                   6603:         /* 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*/
                   6604:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   6605:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   6606:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   6607:         /*, could be restored in the future */
                   6608:         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  6609:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   6610:             break;
                   6611:           }
                   6612:           ij++;
1.287     brouard  6613:           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  6614:           cptcode = ij; /* New max modality for covar j */
                   6615:         } /* end of loop on modality i=-1 to 1 or more */
                   6616:         break;
                   6617:        case 1: /* Testing on varying covariate, could be simple and
                   6618:                * should look at waves or product of fixed *
                   6619:                * varying. No time to test -1, assuming 0 and 1 only */
                   6620:         ij=0;
                   6621:         for(i=0; i<=1;i++){
                   6622:           nbcode[Tvar[k]][++ij]=i;
                   6623:         }
                   6624:         break;
                   6625:        default:
                   6626:         break;
                   6627:        } /* end switch */
                   6628:      } /* end dummy test */
1.349     brouard  6629:      if(Dummy[k]==1 && Typevar[k] !=1 && Typevar[k] !=3 && Fixed ==0){ /* Fixed Quantitative covariate and not age product */ 
1.311     brouard  6630:        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  6631:         if(Tvar[k]<=0 || Tvar[k]>=NCOVMAX){
                   6632:           printf("Error k=%d \n",k);
                   6633:           exit(1);
                   6634:         }
1.311     brouard  6635:         if(isnan(covar[Tvar[k]][i])){
                   6636:           printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6637:           fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6638:           fflush(ficlog);
                   6639:           exit(1);
                   6640:          }
                   6641:        }
1.335     brouard  6642:      } /* end Quanti */
1.287     brouard  6643:    } /* 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  6644:   
                   6645:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   6646:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   6647:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   6648:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   6649:      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 */ 
                   6650:      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 */
                   6651:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   6652:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   6653:   
                   6654:    ij=0;
                   6655:    /* 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  6656:    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 */
                   6657:      /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
1.242     brouard  6658:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   6659:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
1.335     brouard  6660:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy simple and non empty in the model */
                   6661:        /* Typevar[k] =0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for product */
                   6662:        /* 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  6663:        /* If product not in single variable we don't print results */
                   6664:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
1.335     brouard  6665:        ++ij;/*    V5 + V4 + V3 + V4*V3 + V5*age + V2 +  V1*V2 + V1*age + V1, *//* V5 quanti, V2 quanti, V4, V3, V1 dummies */
                   6666:        /* k=       1    2   3     4       5       6      7       8        9  */
                   6667:        /* Tvar[k]= 5    4    3    6       5       2      7       1        1  */
                   6668:        /* ij            1    2                                            3  */  
                   6669:        /* Tvaraff[ij]=  4    3                                            1  */
                   6670:        /* Tmodelind[ij]=2    3                                            9  */
                   6671:        /* TmodelInvind[ij]=2 1                                            1  */
1.242     brouard  6672:        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*/
                   6673:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   6674:        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 */
                   6675:        if(Fixed[k]!=0)
                   6676:         anyvaryingduminmodel=1;
                   6677:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   6678:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6679:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   6680:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   6681:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   6682:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6683:      } 
                   6684:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   6685:    /* ij--; */
                   6686:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
1.335     brouard  6687:    *cptcov=ij; /* cptcov= Number of total real effective simple dummies (fixed or time  arying) effective (used as cptcoveff in other functions)
1.242     brouard  6688:                * because they can be excluded from the model and real
                   6689:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   6690:    for(j=ij+1; j<= cptcovt; j++){
                   6691:      Tvaraff[j]=0;
                   6692:      Tmodelind[j]=0;
                   6693:    }
                   6694:    for(j=ntveff+1; j<= cptcovt; j++){
                   6695:      TmodelInvind[j]=0;
                   6696:    }
                   6697:    /* To be sorted */
                   6698:    ;
                   6699:  }
1.126     brouard  6700: 
1.145     brouard  6701: 
1.126     brouard  6702: /*********** Health Expectancies ****************/
                   6703: 
1.235     brouard  6704:  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  6705: 
                   6706: {
                   6707:   /* Health expectancies, no variances */
1.329     brouard  6708:   /* cij is the combination in the list of combination of dummy covariates */
                   6709:   /* strstart is a string of time at start of computing */
1.164     brouard  6710:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  6711:   int nhstepma, nstepma; /* Decreasing with age */
                   6712:   double age, agelim, hf;
                   6713:   double ***p3mat;
                   6714:   double eip;
                   6715: 
1.238     brouard  6716:   /* pstamp(ficreseij); */
1.126     brouard  6717:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   6718:   fprintf(ficreseij,"# Age");
                   6719:   for(i=1; i<=nlstate;i++){
                   6720:     for(j=1; j<=nlstate;j++){
                   6721:       fprintf(ficreseij," e%1d%1d ",i,j);
                   6722:     }
                   6723:     fprintf(ficreseij," e%1d. ",i);
                   6724:   }
                   6725:   fprintf(ficreseij,"\n");
                   6726: 
                   6727:   
                   6728:   if(estepm < stepm){
                   6729:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6730:   }
                   6731:   else  hstepm=estepm;   
                   6732:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6733:    * This is mainly to measure the difference between two models: for example
                   6734:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6735:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6736:    * progression in between and thus overestimating or underestimating according
                   6737:    * to the curvature of the survival function. If, for the same date, we 
                   6738:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6739:    * to compare the new estimate of Life expectancy with the same linear 
                   6740:    * hypothesis. A more precise result, taking into account a more precise
                   6741:    * curvature will be obtained if estepm is as small as stepm. */
                   6742: 
                   6743:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6744:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6745:      nhstepm is the number of hstepm from age to agelim 
                   6746:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  6747:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  6748:      and note for a fixed period like estepm months */
                   6749:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6750:      survival function given by stepm (the optimization length). Unfortunately it
                   6751:      means that if the survival funtion is printed only each two years of age and if
                   6752:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6753:      results. So we changed our mind and took the option of the best precision.
                   6754:   */
                   6755:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6756: 
                   6757:   agelim=AGESUP;
                   6758:   /* If stepm=6 months */
                   6759:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   6760:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   6761:     
                   6762: /* nhstepm age range expressed in number of stepm */
                   6763:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6764:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6765:   /* if (stepm >= YEARM) hstepm=1;*/
                   6766:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6767:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6768: 
                   6769:   for (age=bage; age<=fage; age ++){ 
                   6770:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6771:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6772:     /* if (stepm >= YEARM) hstepm=1;*/
                   6773:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   6774: 
                   6775:     /* If stepm=6 months */
                   6776:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6777:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
1.330     brouard  6778:     /* 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  6779:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  6780:     
                   6781:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6782:     
                   6783:     printf("%d|",(int)age);fflush(stdout);
                   6784:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6785:     
                   6786:     /* Computing expectancies */
                   6787:     for(i=1; i<=nlstate;i++)
                   6788:       for(j=1; j<=nlstate;j++)
                   6789:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6790:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   6791:          
                   6792:          /* 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]);*/
                   6793: 
                   6794:        }
                   6795: 
                   6796:     fprintf(ficreseij,"%3.0f",age );
                   6797:     for(i=1; i<=nlstate;i++){
                   6798:       eip=0;
                   6799:       for(j=1; j<=nlstate;j++){
                   6800:        eip +=eij[i][j][(int)age];
                   6801:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   6802:       }
                   6803:       fprintf(ficreseij,"%9.4f", eip );
                   6804:     }
                   6805:     fprintf(ficreseij,"\n");
                   6806:     
                   6807:   }
                   6808:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6809:   printf("\n");
                   6810:   fprintf(ficlog,"\n");
                   6811:   
                   6812: }
                   6813: 
1.235     brouard  6814:  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  6815: 
                   6816: {
                   6817:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  6818:      to initial status i, ei. .
1.126     brouard  6819:   */
1.336     brouard  6820:   /* Very time consuming function, but already optimized with precov */
1.126     brouard  6821:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   6822:   int nhstepma, nstepma; /* Decreasing with age */
                   6823:   double age, agelim, hf;
                   6824:   double ***p3matp, ***p3matm, ***varhe;
                   6825:   double **dnewm,**doldm;
                   6826:   double *xp, *xm;
                   6827:   double **gp, **gm;
                   6828:   double ***gradg, ***trgradg;
                   6829:   int theta;
                   6830: 
                   6831:   double eip, vip;
                   6832: 
                   6833:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   6834:   xp=vector(1,npar);
                   6835:   xm=vector(1,npar);
                   6836:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   6837:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   6838:   
                   6839:   pstamp(ficresstdeij);
                   6840:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   6841:   fprintf(ficresstdeij,"# Age");
                   6842:   for(i=1; i<=nlstate;i++){
                   6843:     for(j=1; j<=nlstate;j++)
                   6844:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   6845:     fprintf(ficresstdeij," e%1d. ",i);
                   6846:   }
                   6847:   fprintf(ficresstdeij,"\n");
                   6848: 
                   6849:   pstamp(ficrescveij);
                   6850:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   6851:   fprintf(ficrescveij,"# Age");
                   6852:   for(i=1; i<=nlstate;i++)
                   6853:     for(j=1; j<=nlstate;j++){
                   6854:       cptj= (j-1)*nlstate+i;
                   6855:       for(i2=1; i2<=nlstate;i2++)
                   6856:        for(j2=1; j2<=nlstate;j2++){
                   6857:          cptj2= (j2-1)*nlstate+i2;
                   6858:          if(cptj2 <= cptj)
                   6859:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   6860:        }
                   6861:     }
                   6862:   fprintf(ficrescveij,"\n");
                   6863:   
                   6864:   if(estepm < stepm){
                   6865:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6866:   }
                   6867:   else  hstepm=estepm;   
                   6868:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6869:    * This is mainly to measure the difference between two models: for example
                   6870:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6871:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6872:    * progression in between and thus overestimating or underestimating according
                   6873:    * to the curvature of the survival function. If, for the same date, we 
                   6874:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6875:    * to compare the new estimate of Life expectancy with the same linear 
                   6876:    * hypothesis. A more precise result, taking into account a more precise
                   6877:    * curvature will be obtained if estepm is as small as stepm. */
                   6878: 
                   6879:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6880:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6881:      nhstepm is the number of hstepm from age to agelim 
                   6882:      nstepm is the number of stepm from age to agelin. 
                   6883:      Look at hpijx to understand the reason of that which relies in memory size
                   6884:      and note for a fixed period like estepm months */
                   6885:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6886:      survival function given by stepm (the optimization length). Unfortunately it
                   6887:      means that if the survival funtion is printed only each two years of age and if
                   6888:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6889:      results. So we changed our mind and took the option of the best precision.
                   6890:   */
                   6891:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6892: 
                   6893:   /* If stepm=6 months */
                   6894:   /* nhstepm age range expressed in number of stepm */
                   6895:   agelim=AGESUP;
                   6896:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   6897:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6898:   /* if (stepm >= YEARM) hstepm=1;*/
                   6899:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6900:   
                   6901:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6902:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6903:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   6904:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   6905:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   6906:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   6907: 
                   6908:   for (age=bage; age<=fage; age ++){ 
                   6909:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6910:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6911:     /* if (stepm >= YEARM) hstepm=1;*/
                   6912:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  6913:                
1.126     brouard  6914:     /* If stepm=6 months */
                   6915:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6916:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   6917:     
                   6918:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  6919:                
1.126     brouard  6920:     /* Computing  Variances of health expectancies */
                   6921:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   6922:        decrease memory allocation */
                   6923:     for(theta=1; theta <=npar; theta++){
                   6924:       for(i=1; i<=npar; i++){ 
1.222     brouard  6925:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6926:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  6927:       }
1.235     brouard  6928:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   6929:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  6930:                        
1.126     brouard  6931:       for(j=1; j<= nlstate; j++){
1.222     brouard  6932:        for(i=1; i<=nlstate; i++){
                   6933:          for(h=0; h<=nhstepm-1; h++){
                   6934:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   6935:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   6936:          }
                   6937:        }
1.126     brouard  6938:       }
1.218     brouard  6939:                        
1.126     brouard  6940:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  6941:        for(h=0; h<=nhstepm-1; h++){
                   6942:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   6943:        }
1.126     brouard  6944:     }/* End theta */
                   6945:     
                   6946:     
                   6947:     for(h=0; h<=nhstepm-1; h++)
                   6948:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  6949:        for(theta=1; theta <=npar; theta++)
                   6950:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  6951:     
1.218     brouard  6952:                
1.222     brouard  6953:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  6954:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  6955:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  6956:                
1.222     brouard  6957:     printf("%d|",(int)age);fflush(stdout);
                   6958:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6959:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  6960:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  6961:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   6962:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   6963:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   6964:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   6965:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  6966:       }
                   6967:     }
1.320     brouard  6968:     /* if((int)age ==50){ */
                   6969:     /*   printf(" age=%d cij=%d nres=%d varhe[%d][%d]=%f ",(int)age, cij, nres, 1,2,varhe[1][2]); */
                   6970:     /* } */
1.126     brouard  6971:     /* Computing expectancies */
1.235     brouard  6972:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  6973:     for(i=1; i<=nlstate;i++)
                   6974:       for(j=1; j<=nlstate;j++)
1.222     brouard  6975:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6976:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  6977:                                        
1.222     brouard  6978:          /* 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  6979:                                        
1.222     brouard  6980:        }
1.269     brouard  6981: 
                   6982:     /* Standard deviation of expectancies ij */                
1.126     brouard  6983:     fprintf(ficresstdeij,"%3.0f",age );
                   6984:     for(i=1; i<=nlstate;i++){
                   6985:       eip=0.;
                   6986:       vip=0.;
                   6987:       for(j=1; j<=nlstate;j++){
1.222     brouard  6988:        eip += eij[i][j][(int)age];
                   6989:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   6990:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   6991:        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  6992:       }
                   6993:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   6994:     }
                   6995:     fprintf(ficresstdeij,"\n");
1.218     brouard  6996:                
1.269     brouard  6997:     /* Variance of expectancies ij */          
1.126     brouard  6998:     fprintf(ficrescveij,"%3.0f",age );
                   6999:     for(i=1; i<=nlstate;i++)
                   7000:       for(j=1; j<=nlstate;j++){
1.222     brouard  7001:        cptj= (j-1)*nlstate+i;
                   7002:        for(i2=1; i2<=nlstate;i2++)
                   7003:          for(j2=1; j2<=nlstate;j2++){
                   7004:            cptj2= (j2-1)*nlstate+i2;
                   7005:            if(cptj2 <= cptj)
                   7006:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   7007:          }
1.126     brouard  7008:       }
                   7009:     fprintf(ficrescveij,"\n");
1.218     brouard  7010:                
1.126     brouard  7011:   }
                   7012:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   7013:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   7014:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   7015:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   7016:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7017:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7018:   printf("\n");
                   7019:   fprintf(ficlog,"\n");
1.218     brouard  7020:        
1.126     brouard  7021:   free_vector(xm,1,npar);
                   7022:   free_vector(xp,1,npar);
                   7023:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   7024:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   7025:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   7026: }
1.218     brouard  7027:  
1.126     brouard  7028: /************ Variance ******************/
1.235     brouard  7029:  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  7030:  {
1.279     brouard  7031:    /** Variance of health expectancies 
                   7032:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   7033:     * double **newm;
                   7034:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   7035:     */
1.218     brouard  7036:   
                   7037:    /* int movingaverage(); */
                   7038:    double **dnewm,**doldm;
                   7039:    double **dnewmp,**doldmp;
                   7040:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  7041:    int first=0;
1.218     brouard  7042:    int k;
                   7043:    double *xp;
1.279     brouard  7044:    double **gp, **gm;  /**< for var eij */
                   7045:    double ***gradg, ***trgradg; /**< for var eij */
                   7046:    double **gradgp, **trgradgp; /**< for var p point j */
                   7047:    double *gpp, *gmp; /**< for var p point j */
                   7048:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
1.218     brouard  7049:    double ***p3mat;
                   7050:    double age,agelim, hf;
                   7051:    /* double ***mobaverage; */
                   7052:    int theta;
                   7053:    char digit[4];
                   7054:    char digitp[25];
                   7055: 
                   7056:    char fileresprobmorprev[FILENAMELENGTH];
                   7057: 
                   7058:    if(popbased==1){
                   7059:      if(mobilav!=0)
                   7060:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   7061:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   7062:    }
                   7063:    else 
                   7064:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  7065: 
1.218     brouard  7066:    /* if (mobilav!=0) { */
                   7067:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7068:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   7069:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   7070:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   7071:    /*   } */
                   7072:    /* } */
                   7073: 
                   7074:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   7075:    sprintf(digit,"%-d",ij);
                   7076:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   7077:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   7078:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   7079:    strcat(fileresprobmorprev,fileresu);
                   7080:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   7081:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   7082:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   7083:    }
                   7084:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   7085:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   7086:    pstamp(ficresprobmorprev);
                   7087:    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  7088:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
1.337     brouard  7089: 
                   7090:    /* We use TinvDoQresult[nres][resultmodel[nres][j] we sort according to the equation model and the resultline: it is a choice */
                   7091:    /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ /\* To be done*\/ */
                   7092:    /*   fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   7093:    /* } */
                   7094:    for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */ /* To be done*/
1.344     brouard  7095:      /* fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); */
1.337     brouard  7096:      fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  7097:    }
1.337     brouard  7098:    /* for(j=1;j<=cptcoveff;j++)  */
                   7099:    /*   fprintf(ficresprobmorprev," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,TnsdVar[Tvaraff[j]])]); */
1.238     brouard  7100:    fprintf(ficresprobmorprev,"\n");
                   7101: 
1.218     brouard  7102:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   7103:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   7104:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   7105:      for(i=1; i<=nlstate;i++)
                   7106:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   7107:    }  
                   7108:    fprintf(ficresprobmorprev,"\n");
                   7109:   
                   7110:    fprintf(ficgp,"\n# Routine varevsij");
                   7111:    fprintf(ficgp,"\nunset title \n");
                   7112:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   7113:    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");
                   7114:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  7115: 
1.218     brouard  7116:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7117:    pstamp(ficresvij);
                   7118:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   7119:    if(popbased==1)
                   7120:      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);
                   7121:    else
                   7122:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   7123:    fprintf(ficresvij,"# Age");
                   7124:    for(i=1; i<=nlstate;i++)
                   7125:      for(j=1; j<=nlstate;j++)
                   7126:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   7127:    fprintf(ficresvij,"\n");
                   7128: 
                   7129:    xp=vector(1,npar);
                   7130:    dnewm=matrix(1,nlstate,1,npar);
                   7131:    doldm=matrix(1,nlstate,1,nlstate);
                   7132:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   7133:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7134: 
                   7135:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   7136:    gpp=vector(nlstate+1,nlstate+ndeath);
                   7137:    gmp=vector(nlstate+1,nlstate+ndeath);
                   7138:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  7139:   
1.218     brouard  7140:    if(estepm < stepm){
                   7141:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   7142:    }
                   7143:    else  hstepm=estepm;   
                   7144:    /* For example we decided to compute the life expectancy with the smallest unit */
                   7145:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   7146:       nhstepm is the number of hstepm from age to agelim 
                   7147:       nstepm is the number of stepm from age to agelim. 
                   7148:       Look at function hpijx to understand why because of memory size limitations, 
                   7149:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   7150:       survival function given by stepm (the optimization length). Unfortunately it
                   7151:       means that if the survival funtion is printed every two years of age and if
                   7152:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   7153:       results. So we changed our mind and took the option of the best precision.
                   7154:    */
                   7155:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   7156:    agelim = AGESUP;
                   7157:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   7158:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7159:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   7160:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7161:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   7162:      gp=matrix(0,nhstepm,1,nlstate);
                   7163:      gm=matrix(0,nhstepm,1,nlstate);
                   7164:                
                   7165:                
                   7166:      for(theta=1; theta <=npar; theta++){
                   7167:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   7168:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7169:        }
1.279     brouard  7170:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   7171:        * returns into prlim .
1.288     brouard  7172:        */
1.242     brouard  7173:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  7174: 
                   7175:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  7176:        if (popbased==1) {
                   7177:         if(mobilav ==0){
                   7178:           for(i=1; i<=nlstate;i++)
                   7179:             prlim[i][i]=probs[(int)age][i][ij];
                   7180:         }else{ /* mobilav */ 
                   7181:           for(i=1; i<=nlstate;i++)
                   7182:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   7183:         }
                   7184:        }
1.295     brouard  7185:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  7186:        */                      
                   7187:        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  7188:        /**< 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  7189:        * at horizon h in state j including mortality.
                   7190:        */
1.218     brouard  7191:        for(j=1; j<= nlstate; j++){
                   7192:         for(h=0; h<=nhstepm; h++){
                   7193:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   7194:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   7195:         }
                   7196:        }
1.279     brouard  7197:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  7198:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  7199:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  7200:        */
                   7201:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   7202:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   7203:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  7204:        }
                   7205:        
                   7206:        /* Again with minus shift */
1.218     brouard  7207:                        
                   7208:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   7209:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  7210: 
1.242     brouard  7211:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  7212:                        
                   7213:        if (popbased==1) {
                   7214:         if(mobilav ==0){
                   7215:           for(i=1; i<=nlstate;i++)
                   7216:             prlim[i][i]=probs[(int)age][i][ij];
                   7217:         }else{ /* mobilav */ 
                   7218:           for(i=1; i<=nlstate;i++)
                   7219:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   7220:         }
                   7221:        }
                   7222:                        
1.235     brouard  7223:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  7224:                        
                   7225:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   7226:         for(h=0; h<=nhstepm; h++){
                   7227:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   7228:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   7229:         }
                   7230:        }
                   7231:        /* This for computing probability of death (h=1 means
                   7232:          computed over hstepm matrices product = hstepm*stepm months) 
                   7233:          as a weighted average of prlim.
                   7234:        */
                   7235:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   7236:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   7237:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   7238:        }    
1.279     brouard  7239:        /* end shifting computations */
                   7240: 
                   7241:        /**< Computing gradient matrix at horizon h 
                   7242:        */
1.218     brouard  7243:        for(j=1; j<= nlstate; j++) /* vareij */
                   7244:         for(h=0; h<=nhstepm; h++){
                   7245:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   7246:         }
1.279     brouard  7247:        /**< Gradient of overall mortality p.3 (or p.j) 
                   7248:        */
                   7249:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
1.218     brouard  7250:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   7251:        }
                   7252:                        
                   7253:      } /* End theta */
1.279     brouard  7254:      
                   7255:      /* We got the gradient matrix for each theta and state j */               
1.218     brouard  7256:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   7257:                
                   7258:      for(h=0; h<=nhstepm; h++) /* veij */
                   7259:        for(j=1; j<=nlstate;j++)
                   7260:         for(theta=1; theta <=npar; theta++)
                   7261:           trgradg[h][j][theta]=gradg[h][theta][j];
                   7262:                
                   7263:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   7264:        for(theta=1; theta <=npar; theta++)
                   7265:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  7266:      /**< as well as its transposed matrix 
                   7267:       */               
1.218     brouard  7268:                
                   7269:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   7270:      for(i=1;i<=nlstate;i++)
                   7271:        for(j=1;j<=nlstate;j++)
                   7272:         vareij[i][j][(int)age] =0.;
1.279     brouard  7273: 
                   7274:      /* Computing trgradg by matcov by gradg at age and summing over h
                   7275:       * and k (nhstepm) formula 15 of article
                   7276:       * Lievre-Brouard-Heathcote
                   7277:       */
                   7278:      
1.218     brouard  7279:      for(h=0;h<=nhstepm;h++){
                   7280:        for(k=0;k<=nhstepm;k++){
                   7281:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   7282:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   7283:         for(i=1;i<=nlstate;i++)
                   7284:           for(j=1;j<=nlstate;j++)
                   7285:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   7286:        }
                   7287:      }
                   7288:                
1.279     brouard  7289:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
                   7290:       * p.j overall mortality formula 49 but computed directly because
                   7291:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   7292:       * wix is independent of theta.
                   7293:       */
1.218     brouard  7294:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   7295:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   7296:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   7297:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   7298:         varppt[j][i]=doldmp[j][i];
                   7299:      /* end ppptj */
                   7300:      /*  x centered again */
                   7301:                
1.242     brouard  7302:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  7303:                
                   7304:      if (popbased==1) {
                   7305:        if(mobilav ==0){
                   7306:         for(i=1; i<=nlstate;i++)
                   7307:           prlim[i][i]=probs[(int)age][i][ij];
                   7308:        }else{ /* mobilav */ 
                   7309:         for(i=1; i<=nlstate;i++)
                   7310:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   7311:        }
                   7312:      }
                   7313:                
                   7314:      /* This for computing probability of death (h=1 means
                   7315:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   7316:        as a weighted average of prlim.
                   7317:      */
1.235     brouard  7318:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  7319:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   7320:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   7321:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   7322:      }    
                   7323:      /* end probability of death */
                   7324:                
                   7325:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   7326:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   7327:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   7328:        for(i=1; i<=nlstate;i++){
                   7329:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   7330:        }
                   7331:      } 
                   7332:      fprintf(ficresprobmorprev,"\n");
                   7333:                
                   7334:      fprintf(ficresvij,"%.0f ",age );
                   7335:      for(i=1; i<=nlstate;i++)
                   7336:        for(j=1; j<=nlstate;j++){
                   7337:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   7338:        }
                   7339:      fprintf(ficresvij,"\n");
                   7340:      free_matrix(gp,0,nhstepm,1,nlstate);
                   7341:      free_matrix(gm,0,nhstepm,1,nlstate);
                   7342:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   7343:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   7344:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7345:    } /* End age */
                   7346:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   7347:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   7348:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   7349:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   7350:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   7351:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   7352:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   7353:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   7354:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   7355:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   7356:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   7357:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   7358:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   7359:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   7360:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   7361:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   7362:    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);
                   7363:    /*  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  7364:     */
1.218     brouard  7365:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   7366:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  7367: 
1.218     brouard  7368:    free_vector(xp,1,npar);
                   7369:    free_matrix(doldm,1,nlstate,1,nlstate);
                   7370:    free_matrix(dnewm,1,nlstate,1,npar);
                   7371:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7372:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   7373:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7374:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7375:    fclose(ficresprobmorprev);
                   7376:    fflush(ficgp);
                   7377:    fflush(fichtm); 
                   7378:  }  /* end varevsij */
1.126     brouard  7379: 
                   7380: /************ Variance of prevlim ******************/
1.269     brouard  7381:  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  7382: {
1.205     brouard  7383:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  7384:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  7385: 
1.268     brouard  7386:   double **dnewmpar,**doldm;
1.126     brouard  7387:   int i, j, nhstepm, hstepm;
                   7388:   double *xp;
                   7389:   double *gp, *gm;
                   7390:   double **gradg, **trgradg;
1.208     brouard  7391:   double **mgm, **mgp;
1.126     brouard  7392:   double age,agelim;
                   7393:   int theta;
                   7394:   
                   7395:   pstamp(ficresvpl);
1.288     brouard  7396:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  7397:   fprintf(ficresvpl,"# Age ");
                   7398:   if(nresult >=1)
                   7399:     fprintf(ficresvpl," Result# ");
1.126     brouard  7400:   for(i=1; i<=nlstate;i++)
                   7401:       fprintf(ficresvpl," %1d-%1d",i,i);
                   7402:   fprintf(ficresvpl,"\n");
                   7403: 
                   7404:   xp=vector(1,npar);
1.268     brouard  7405:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  7406:   doldm=matrix(1,nlstate,1,nlstate);
                   7407:   
                   7408:   hstepm=1*YEARM; /* Every year of age */
                   7409:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   7410:   agelim = AGESUP;
                   7411:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   7412:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7413:     if (stepm >= YEARM) hstepm=1;
                   7414:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7415:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  7416:     mgp=matrix(1,npar,1,nlstate);
                   7417:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  7418:     gp=vector(1,nlstate);
                   7419:     gm=vector(1,nlstate);
                   7420: 
                   7421:     for(theta=1; theta <=npar; theta++){
                   7422:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   7423:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7424:       }
1.288     brouard  7425:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   7426:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   7427:       /* else */
                   7428:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  7429:       for(i=1;i<=nlstate;i++){
1.126     brouard  7430:        gp[i] = prlim[i][i];
1.208     brouard  7431:        mgp[theta][i] = prlim[i][i];
                   7432:       }
1.126     brouard  7433:       for(i=1; i<=npar; i++) /* Computes gradient */
                   7434:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  7435:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   7436:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   7437:       /* else */
                   7438:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  7439:       for(i=1;i<=nlstate;i++){
1.126     brouard  7440:        gm[i] = prlim[i][i];
1.208     brouard  7441:        mgm[theta][i] = prlim[i][i];
                   7442:       }
1.126     brouard  7443:       for(i=1;i<=nlstate;i++)
                   7444:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  7445:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  7446:     } /* End theta */
                   7447: 
                   7448:     trgradg =matrix(1,nlstate,1,npar);
                   7449: 
                   7450:     for(j=1; j<=nlstate;j++)
                   7451:       for(theta=1; theta <=npar; theta++)
                   7452:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  7453:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7454:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7455:     /*   for(j=1; j<=nlstate;j++){ */
                   7456:     /*         printf(" %d ",j); */
                   7457:     /*         for(theta=1; theta <=npar; theta++) */
                   7458:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7459:     /*         printf("\n "); */
                   7460:     /*   } */
                   7461:     /* } */
                   7462:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7463:     /*   printf("\n gradg %d ",(int)age); */
                   7464:     /*   for(j=1; j<=nlstate;j++){ */
                   7465:     /*         printf("%d ",j); */
                   7466:     /*         for(theta=1; theta <=npar; theta++) */
                   7467:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7468:     /*         printf("\n "); */
                   7469:     /*   } */
                   7470:     /* } */
1.126     brouard  7471: 
                   7472:     for(i=1;i<=nlstate;i++)
                   7473:       varpl[i][(int)age] =0.;
1.209     brouard  7474:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  7475:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7476:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  7477:     }else{
1.268     brouard  7478:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7479:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  7480:     }
1.126     brouard  7481:     for(i=1;i<=nlstate;i++)
                   7482:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7483: 
                   7484:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  7485:     if(nresult >=1)
                   7486:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  7487:     for(i=1; i<=nlstate;i++){
1.126     brouard  7488:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  7489:       /* for(j=1;j<=nlstate;j++) */
                   7490:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   7491:     }
1.126     brouard  7492:     fprintf(ficresvpl,"\n");
                   7493:     free_vector(gp,1,nlstate);
                   7494:     free_vector(gm,1,nlstate);
1.208     brouard  7495:     free_matrix(mgm,1,npar,1,nlstate);
                   7496:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  7497:     free_matrix(gradg,1,npar,1,nlstate);
                   7498:     free_matrix(trgradg,1,nlstate,1,npar);
                   7499:   } /* End age */
                   7500: 
                   7501:   free_vector(xp,1,npar);
                   7502:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  7503:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   7504: 
                   7505: }
                   7506: 
                   7507: 
                   7508: /************ Variance of backprevalence limit ******************/
1.269     brouard  7509:  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  7510: {
                   7511:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   7512:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   7513: 
                   7514:   double **dnewmpar,**doldm;
                   7515:   int i, j, nhstepm, hstepm;
                   7516:   double *xp;
                   7517:   double *gp, *gm;
                   7518:   double **gradg, **trgradg;
                   7519:   double **mgm, **mgp;
                   7520:   double age,agelim;
                   7521:   int theta;
                   7522:   
                   7523:   pstamp(ficresvbl);
                   7524:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   7525:   fprintf(ficresvbl,"# Age ");
                   7526:   if(nresult >=1)
                   7527:     fprintf(ficresvbl," Result# ");
                   7528:   for(i=1; i<=nlstate;i++)
                   7529:       fprintf(ficresvbl," %1d-%1d",i,i);
                   7530:   fprintf(ficresvbl,"\n");
                   7531: 
                   7532:   xp=vector(1,npar);
                   7533:   dnewmpar=matrix(1,nlstate,1,npar);
                   7534:   doldm=matrix(1,nlstate,1,nlstate);
                   7535:   
                   7536:   hstepm=1*YEARM; /* Every year of age */
                   7537:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   7538:   agelim = AGEINF;
                   7539:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   7540:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7541:     if (stepm >= YEARM) hstepm=1;
                   7542:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7543:     gradg=matrix(1,npar,1,nlstate);
                   7544:     mgp=matrix(1,npar,1,nlstate);
                   7545:     mgm=matrix(1,npar,1,nlstate);
                   7546:     gp=vector(1,nlstate);
                   7547:     gm=vector(1,nlstate);
                   7548: 
                   7549:     for(theta=1; theta <=npar; theta++){
                   7550:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   7551:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7552:       }
                   7553:       if(mobilavproj > 0 )
                   7554:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7555:       else
                   7556:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7557:       for(i=1;i<=nlstate;i++){
                   7558:        gp[i] = bprlim[i][i];
                   7559:        mgp[theta][i] = bprlim[i][i];
                   7560:       }
                   7561:      for(i=1; i<=npar; i++) /* Computes gradient */
                   7562:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   7563:        if(mobilavproj > 0 )
                   7564:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7565:        else
                   7566:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7567:       for(i=1;i<=nlstate;i++){
                   7568:        gm[i] = bprlim[i][i];
                   7569:        mgm[theta][i] = bprlim[i][i];
                   7570:       }
                   7571:       for(i=1;i<=nlstate;i++)
                   7572:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   7573:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   7574:     } /* End theta */
                   7575: 
                   7576:     trgradg =matrix(1,nlstate,1,npar);
                   7577: 
                   7578:     for(j=1; j<=nlstate;j++)
                   7579:       for(theta=1; theta <=npar; theta++)
                   7580:        trgradg[j][theta]=gradg[theta][j];
                   7581:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7582:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7583:     /*   for(j=1; j<=nlstate;j++){ */
                   7584:     /*         printf(" %d ",j); */
                   7585:     /*         for(theta=1; theta <=npar; theta++) */
                   7586:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7587:     /*         printf("\n "); */
                   7588:     /*   } */
                   7589:     /* } */
                   7590:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7591:     /*   printf("\n gradg %d ",(int)age); */
                   7592:     /*   for(j=1; j<=nlstate;j++){ */
                   7593:     /*         printf("%d ",j); */
                   7594:     /*         for(theta=1; theta <=npar; theta++) */
                   7595:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7596:     /*         printf("\n "); */
                   7597:     /*   } */
                   7598:     /* } */
                   7599: 
                   7600:     for(i=1;i<=nlstate;i++)
                   7601:       varbpl[i][(int)age] =0.;
                   7602:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   7603:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7604:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7605:     }else{
                   7606:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7607:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7608:     }
                   7609:     for(i=1;i<=nlstate;i++)
                   7610:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7611: 
                   7612:     fprintf(ficresvbl,"%.0f ",age );
                   7613:     if(nresult >=1)
                   7614:       fprintf(ficresvbl,"%d ",nres );
                   7615:     for(i=1; i<=nlstate;i++)
                   7616:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   7617:     fprintf(ficresvbl,"\n");
                   7618:     free_vector(gp,1,nlstate);
                   7619:     free_vector(gm,1,nlstate);
                   7620:     free_matrix(mgm,1,npar,1,nlstate);
                   7621:     free_matrix(mgp,1,npar,1,nlstate);
                   7622:     free_matrix(gradg,1,npar,1,nlstate);
                   7623:     free_matrix(trgradg,1,nlstate,1,npar);
                   7624:   } /* End age */
                   7625: 
                   7626:   free_vector(xp,1,npar);
                   7627:   free_matrix(doldm,1,nlstate,1,npar);
                   7628:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  7629: 
                   7630: }
                   7631: 
                   7632: /************ Variance of one-step probabilities  ******************/
                   7633: 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  7634:  {
                   7635:    int i, j=0,  k1, l1, tj;
                   7636:    int k2, l2, j1,  z1;
                   7637:    int k=0, l;
                   7638:    int first=1, first1, first2;
1.326     brouard  7639:    int nres=0; /* New */
1.222     brouard  7640:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   7641:    double **dnewm,**doldm;
                   7642:    double *xp;
                   7643:    double *gp, *gm;
                   7644:    double **gradg, **trgradg;
                   7645:    double **mu;
                   7646:    double age, cov[NCOVMAX+1];
                   7647:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   7648:    int theta;
                   7649:    char fileresprob[FILENAMELENGTH];
                   7650:    char fileresprobcov[FILENAMELENGTH];
                   7651:    char fileresprobcor[FILENAMELENGTH];
                   7652:    double ***varpij;
                   7653: 
                   7654:    strcpy(fileresprob,"PROB_"); 
1.356     brouard  7655:    strcat(fileresprob,fileresu);
1.222     brouard  7656:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   7657:      printf("Problem with resultfile: %s\n", fileresprob);
                   7658:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   7659:    }
                   7660:    strcpy(fileresprobcov,"PROBCOV_"); 
                   7661:    strcat(fileresprobcov,fileresu);
                   7662:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   7663:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   7664:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   7665:    }
                   7666:    strcpy(fileresprobcor,"PROBCOR_"); 
                   7667:    strcat(fileresprobcor,fileresu);
                   7668:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   7669:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   7670:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   7671:    }
                   7672:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7673:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7674:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7675:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7676:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7677:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7678:    pstamp(ficresprob);
                   7679:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   7680:    fprintf(ficresprob,"# Age");
                   7681:    pstamp(ficresprobcov);
                   7682:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   7683:    fprintf(ficresprobcov,"# Age");
                   7684:    pstamp(ficresprobcor);
                   7685:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   7686:    fprintf(ficresprobcor,"# Age");
1.126     brouard  7687: 
                   7688: 
1.222     brouard  7689:    for(i=1; i<=nlstate;i++)
                   7690:      for(j=1; j<=(nlstate+ndeath);j++){
                   7691:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   7692:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   7693:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   7694:      }  
                   7695:    /* fprintf(ficresprob,"\n");
                   7696:       fprintf(ficresprobcov,"\n");
                   7697:       fprintf(ficresprobcor,"\n");
                   7698:    */
                   7699:    xp=vector(1,npar);
                   7700:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7701:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7702:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   7703:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   7704:    first=1;
                   7705:    fprintf(ficgp,"\n# Routine varprob");
                   7706:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   7707:    fprintf(fichtm,"\n");
                   7708: 
1.288     brouard  7709:    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  7710:    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);
                   7711:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  7712: and drawn. It helps understanding how is the covariance between two incidences.\
                   7713:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  7714:    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  7715: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   7716: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   7717: standard deviations wide on each axis. <br>\
                   7718:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   7719:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   7720: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   7721: 
1.222     brouard  7722:    cov[1]=1;
                   7723:    /* tj=cptcoveff; */
1.225     brouard  7724:    tj = (int) pow(2,cptcoveff);
1.222     brouard  7725:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   7726:    j1=0;
1.332     brouard  7727: 
                   7728:    for(nres=1;nres <=nresult; nres++){ /* For each resultline */
                   7729:    for(j1=1; j1<=tj;j1++){ /* For any combination of dummy covariates, fixed and varying */
1.342     brouard  7730:      /* 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  7731:      if(tj != 1 && TKresult[nres]!= j1)
                   7732:        continue;
                   7733: 
                   7734:    /* for(j1=1; j1<=tj;j1++){  /\* For each valid combination of covariates or only once*\/ */
                   7735:      /* for(nres=1;nres <=1; nres++){ /\* For each resultline *\/ */
                   7736:      /* /\* for(nres=1;nres <=nresult; nres++){ /\\* For each resultline *\\/ *\/ */
1.222     brouard  7737:      if  (cptcovn>0) {
1.334     brouard  7738:        fprintf(ficresprob, "\n#********** Variable ");
                   7739:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   7740:        fprintf(ficgp, "\n#********** Variable ");
                   7741:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   7742:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   7743: 
                   7744:        /* Including quantitative variables of the resultline to be done */
                   7745:        for (z1=1; z1<=cptcovs; z1++){ /* Loop on each variable of this resultline  */
1.343     brouard  7746:         /* printf("Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model); */
1.338     brouard  7747:         fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model);
                   7748:         /* 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  7749:         if(Dummy[modelresult[nres][z1]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to z1 in resultline  */
                   7750:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed referenced to model equation */
                   7751:             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  */
                   7752:             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  */
                   7753:             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  */
                   7754:             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  */
                   7755:             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  */
                   7756:             fprintf(ficresprob,"fixed ");
                   7757:             fprintf(ficresprobcov,"fixed ");
                   7758:             fprintf(ficgp,"fixed ");
                   7759:             fprintf(fichtmcov,"fixed ");
                   7760:             fprintf(ficresprobcor,"fixed ");
                   7761:           }else{
                   7762:             fprintf(ficresprob,"varyi ");
                   7763:             fprintf(ficresprobcov,"varyi ");
                   7764:             fprintf(ficgp,"varyi ");
                   7765:             fprintf(fichtmcov,"varyi ");
                   7766:             fprintf(ficresprobcor,"varyi ");
                   7767:           }
                   7768:         }else if(Dummy[modelresult[nres][z1]]==1){ /* Quanti variable */
                   7769:           /* For each selected (single) quantitative value */
1.337     brouard  7770:           fprintf(ficresprob," V%d=%lg ",Tvqresult[nres][z1],Tqresult[nres][z1]);
1.334     brouard  7771:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed */
                   7772:             fprintf(ficresprob,"fixed ");
                   7773:             fprintf(ficresprobcov,"fixed ");
                   7774:             fprintf(ficgp,"fixed ");
                   7775:             fprintf(fichtmcov,"fixed ");
                   7776:             fprintf(ficresprobcor,"fixed ");
                   7777:           }else{
                   7778:             fprintf(ficresprob,"varyi ");
                   7779:             fprintf(ficresprobcov,"varyi ");
                   7780:             fprintf(ficgp,"varyi ");
                   7781:             fprintf(fichtmcov,"varyi ");
                   7782:             fprintf(ficresprobcor,"varyi ");
                   7783:           }
                   7784:         }else{
                   7785:           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 */
                   7786:           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 */
                   7787:           exit(1);
                   7788:         }
                   7789:        } /* End loop on variable of this resultline */
                   7790:        /* for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]); */
1.222     brouard  7791:        fprintf(ficresprob, "**********\n#\n");
                   7792:        fprintf(ficresprobcov, "**********\n#\n");
                   7793:        fprintf(ficgp, "**********\n#\n");
                   7794:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   7795:        fprintf(ficresprobcor, "**********\n#");    
                   7796:        if(invalidvarcomb[j1]){
                   7797:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   7798:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   7799:         continue;
                   7800:        }
                   7801:      }
                   7802:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   7803:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7804:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   7805:      gm=vector(1,(nlstate)*(nlstate+ndeath));
1.334     brouard  7806:      for (age=bage; age<=fage; age ++){ /* Fo each age we feed the model equation with covariates, using precov as in hpxij() ? */
1.222     brouard  7807:        cov[2]=age;
                   7808:        if(nagesqr==1)
                   7809:         cov[3]= age*age;
1.334     brouard  7810:        /* New code end of combination but for each resultline */
                   7811:        for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  7812:         if(Typevar[k1]==1 || Typevar[k1] ==3){ /* A product with age */
1.334     brouard  7813:           cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.326     brouard  7814:         }else{
1.334     brouard  7815:           cov[2+nagesqr+k1]=precov[nres][k1];
1.326     brouard  7816:         }
1.334     brouard  7817:        }/* End of loop on model equation */
                   7818: /* Old code */
                   7819:        /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   7820:        /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)]; *\/ */
                   7821:        /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   7822:        /*       /\* Here comes the value of the covariate 'j1' after renumbering k with single dummy covariates *\/ */
                   7823:        /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(j1,TnsdVar[TvarsD[k]])]; */
                   7824:        /*       /\*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*\//\* j1 1 2 3 4 */
                   7825:        /*                                                                  * 1  1 1 1 1 */
                   7826:        /*                                                                  * 2  2 1 1 1 */
                   7827:        /*                                                                  * 3  1 2 1 1 */
                   7828:        /*                                                                  *\/ */
                   7829:        /*       /\* nbcode[1][1]=0 nbcode[1][2]=1;*\/ */
                   7830:        /* } */
                   7831:        /* /\* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   7832:        /* /\* ) p nbcode[Tvar[Tage[k]]][(1 & (ij-1) >> (k-1))+1] *\/ */
                   7833:        /* /\*for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; *\/ */
                   7834:        /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   7835:        /*       if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   7836:        /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(j1,TnsdVar[Tvar[Tage[k]]])]*cov[2]; */
                   7837:        /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7838:        /*       } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   7839:        /*         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]); */
                   7840:        /*         /\* cov[2+nagesqr+Tage[k]]=meanq[k]/idq[k]*cov[2];/\\* Using the mean of quantitative variable Tvar[Tage[k]] /\\* Tqresult[nres][k]; *\\/ *\/ */
                   7841:        /*         /\* exit(1); *\/ */
                   7842:        /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   7843:        /*       } */
                   7844:        /*       /\* cov[2+Tage[k]+nagesqr]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7845:        /* } */
                   7846:        /* for (k=1; k<=cptcovprod;k++){/\* For product without age *\/ */
                   7847:        /*       if(Dummy[Tvard[k][1]]==0){ */
                   7848:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7849:        /*           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]])]; */
                   7850:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7851:        /*         }else{ /\* Should we use the mean of the quantitative variables? *\/ */
                   7852:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,TnsdVar[Tvard[k][1]])] * Tqresult[nres][resultmodel[nres][k]]; */
                   7853:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   7854:        /*         } */
                   7855:        /*       }else{ */
                   7856:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7857:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(j1,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][TnsdVar[Tvard[k][1]]]; */
                   7858:        /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   7859:        /*         }else{ */
                   7860:        /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][TnsdVar[Tvard[k][1]]]*  Tqinvresult[nres][TnsdVar[Tvard[k][2]]]; */
                   7861:        /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   7862:        /*         } */
                   7863:        /*       } */
                   7864:        /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7865:        /* } */                 
1.326     brouard  7866: /* For each age and combination of dummy covariates we slightly move the parameters of delti in order to get the gradient*/                    
1.222     brouard  7867:        for(theta=1; theta <=npar; theta++){
                   7868:         for(i=1; i<=npar; i++)
                   7869:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  7870:                                
1.222     brouard  7871:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  7872:                                
1.222     brouard  7873:         k=0;
                   7874:         for(i=1; i<= (nlstate); i++){
                   7875:           for(j=1; j<=(nlstate+ndeath);j++){
                   7876:             k=k+1;
                   7877:             gp[k]=pmmij[i][j];
                   7878:           }
                   7879:         }
1.220     brouard  7880:                                
1.222     brouard  7881:         for(i=1; i<=npar; i++)
                   7882:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  7883:                                
1.222     brouard  7884:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   7885:         k=0;
                   7886:         for(i=1; i<=(nlstate); i++){
                   7887:           for(j=1; j<=(nlstate+ndeath);j++){
                   7888:             k=k+1;
                   7889:             gm[k]=pmmij[i][j];
                   7890:           }
                   7891:         }
1.220     brouard  7892:                                
1.222     brouard  7893:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   7894:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   7895:        }
1.126     brouard  7896: 
1.222     brouard  7897:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   7898:         for(theta=1; theta <=npar; theta++)
                   7899:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  7900:                        
1.222     brouard  7901:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   7902:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  7903:                        
1.222     brouard  7904:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  7905:                        
1.222     brouard  7906:        k=0;
                   7907:        for(i=1; i<=(nlstate); i++){
                   7908:         for(j=1; j<=(nlstate+ndeath);j++){
                   7909:           k=k+1;
                   7910:           mu[k][(int) age]=pmmij[i][j];
                   7911:         }
                   7912:        }
                   7913:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   7914:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   7915:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  7916:                        
1.222     brouard  7917:        /*printf("\n%d ",(int)age);
                   7918:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7919:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7920:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7921:         }*/
1.220     brouard  7922:                        
1.222     brouard  7923:        fprintf(ficresprob,"\n%d ",(int)age);
                   7924:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   7925:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  7926:                        
1.222     brouard  7927:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   7928:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   7929:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7930:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   7931:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   7932:        }
                   7933:        i=0;
                   7934:        for (k=1; k<=(nlstate);k++){
                   7935:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   7936:           i++;
                   7937:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   7938:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   7939:           for (j=1; j<=i;j++){
                   7940:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   7941:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   7942:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   7943:           }
                   7944:         }
                   7945:        }/* end of loop for state */
                   7946:      } /* end of loop for age */
                   7947:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7948:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7949:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7950:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7951:     
                   7952:      /* Confidence intervalle of pij  */
                   7953:      /*
                   7954:        fprintf(ficgp,"\nunset parametric;unset label");
                   7955:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   7956:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   7957:        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);
                   7958:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   7959:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   7960:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   7961:      */
                   7962:                
                   7963:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   7964:      first1=1;first2=2;
                   7965:      for (k2=1; k2<=(nlstate);k2++){
                   7966:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   7967:         if(l2==k2) continue;
                   7968:         j=(k2-1)*(nlstate+ndeath)+l2;
                   7969:         for (k1=1; k1<=(nlstate);k1++){
                   7970:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   7971:             if(l1==k1) continue;
                   7972:             i=(k1-1)*(nlstate+ndeath)+l1;
                   7973:             if(i<=j) continue;
                   7974:             for (age=bage; age<=fage; age ++){ 
                   7975:               if ((int)age %5==0){
                   7976:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   7977:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7978:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7979:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   7980:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   7981:                 c12=cv12/sqrt(v1*v2);
                   7982:                 /* Computing eigen value of matrix of covariance */
                   7983:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7984:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7985:                 if ((lc2 <0) || (lc1 <0) ){
                   7986:                   if(first2==1){
                   7987:                     first1=0;
                   7988:                     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);
                   7989:                   }
                   7990:                   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);
                   7991:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   7992:                   /* lc2=fabs(lc2); */
                   7993:                 }
1.220     brouard  7994:                                                                
1.222     brouard  7995:                 /* Eigen vectors */
1.280     brouard  7996:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   7997:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7998:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7999:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   8000:                 }else
                   8001:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  8002:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   8003:                 v21=(lc1-v1)/cv12*v11;
                   8004:                 v12=-v21;
                   8005:                 v22=v11;
                   8006:                 tnalp=v21/v11;
                   8007:                 if(first1==1){
                   8008:                   first1=0;
                   8009:                   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);
                   8010:                 }
                   8011:                 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);
                   8012:                 /*printf(fignu*/
                   8013:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   8014:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   8015:                 if(first==1){
                   8016:                   first=0;
                   8017:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   8018:                   fprintf(ficgp,"\nset parametric;unset label");
                   8019:                   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);
                   8020:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  8021:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  8022:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  8023: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  8024:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   8025:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   8026:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   8027:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   8028:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   8029:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   8030:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   8031:                   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  8032:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   8033:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  8034:                 }else{
                   8035:                   first=0;
                   8036:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   8037:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   8038:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   8039:                   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  8040:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   8041:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  8042:                 }/* if first */
                   8043:               } /* age mod 5 */
                   8044:             } /* end loop age */
                   8045:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   8046:             first=1;
                   8047:           } /*l12 */
                   8048:         } /* k12 */
                   8049:        } /*l1 */
                   8050:      }/* k1 */
1.332     brouard  8051:    }  /* loop on combination of covariates j1 */
1.326     brouard  8052:    } /* loop on nres */
1.222     brouard  8053:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   8054:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   8055:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   8056:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   8057:    free_vector(xp,1,npar);
                   8058:    fclose(ficresprob);
                   8059:    fclose(ficresprobcov);
                   8060:    fclose(ficresprobcor);
                   8061:    fflush(ficgp);
                   8062:    fflush(fichtmcov);
                   8063:  }
1.126     brouard  8064: 
                   8065: 
                   8066: /******************* Printing html file ***********/
1.201     brouard  8067: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  8068:                  int lastpass, int stepm, int weightopt, char model[],\
                   8069:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  8070:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   8071:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   8072:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.237     brouard  8073:   int jj1, k1, i1, cpt, k4, nres;
1.319     brouard  8074:   /* In fact some results are already printed in fichtm which is open */
1.126     brouard  8075:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   8076:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   8077: </ul>");
1.319     brouard  8078: /*    fprintf(fichtm,"<ul><li> model=1+age+%s\n \ */
                   8079: /* </ul>", model); */
1.214     brouard  8080:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   8081:    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",
                   8082:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
1.332     brouard  8083:    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  8084:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   8085:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  8086:    fprintf(fichtm,"\
                   8087:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  8088:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  8089:    fprintf(fichtm,"\
1.217     brouard  8090:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   8091:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   8092:    fprintf(fichtm,"\
1.288     brouard  8093:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  8094:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  8095:    fprintf(fichtm,"\
1.288     brouard  8096:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  8097:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   8098:    fprintf(fichtm,"\
1.211     brouard  8099:  - (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  8100:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  8101:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  8102:    if(prevfcast==1){
                   8103:      fprintf(fichtm,"\
                   8104:  - Prevalence projections by age and states:                           \
1.201     brouard  8105:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  8106:    }
1.126     brouard  8107: 
                   8108: 
1.225     brouard  8109:    m=pow(2,cptcoveff);
1.222     brouard  8110:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  8111: 
1.317     brouard  8112:    fprintf(fichtm," \n<ul><li><b>Graphs (first order)</b></li><p>");
1.264     brouard  8113: 
                   8114:    jj1=0;
                   8115: 
                   8116:    fprintf(fichtm," \n<ul>");
1.337     brouard  8117:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8118:      /* k1=nres; */
1.338     brouard  8119:      k1=TKresult[nres];
                   8120:      if(TKresult[nres]==0)k1=1; /* To be checked for no result */
1.337     brouard  8121:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   8122:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   8123:    /*     continue; */
1.264     brouard  8124:      jj1++;
                   8125:      if (cptcovn > 0) {
                   8126:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
1.337     brouard  8127:        for (cpt=1; cpt<=cptcovs;cpt++){ /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   8128:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  8129:        }
1.337     brouard  8130:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   8131:        /*       fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   8132:        /* } */
                   8133:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8134:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8135:        /* } */
1.264     brouard  8136:        fprintf(fichtm,"\">");
                   8137:        
                   8138:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   8139:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  8140:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8141:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  8142:        }
1.337     brouard  8143:        /* fprintf(fichtm,"************ Results for covariates"); */
                   8144:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   8145:        /*       fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   8146:        /* } */
                   8147:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8148:        /*       fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8149:        /* } */
1.264     brouard  8150:        if(invalidvarcomb[k1]){
                   8151:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   8152:         continue;
                   8153:        }
                   8154:        fprintf(fichtm,"</a></li>");
                   8155:      } /* cptcovn >0 */
                   8156:    }
1.317     brouard  8157:    fprintf(fichtm," \n</ul>");
1.264     brouard  8158: 
1.222     brouard  8159:    jj1=0;
1.237     brouard  8160: 
1.337     brouard  8161:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8162:      /* k1=nres; */
1.338     brouard  8163:      k1=TKresult[nres];
                   8164:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8165:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   8166:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   8167:    /*     continue; */
1.220     brouard  8168: 
1.222     brouard  8169:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   8170:      jj1++;
                   8171:      if (cptcovn > 0) {
1.264     brouard  8172:        fprintf(fichtm,"\n<p><a name=\"rescov");
1.337     brouard  8173:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8174:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  8175:        }
1.337     brouard  8176:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8177:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8178:        /* } */
1.264     brouard  8179:        fprintf(fichtm,"\"</a>");
                   8180:  
1.222     brouard  8181:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  8182:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8183:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8184:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  8185:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   8186:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  8187:        }
1.230     brouard  8188:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.338     brouard  8189:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.222     brouard  8190:        if(invalidvarcomb[k1]){
                   8191:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   8192:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   8193:         continue;
                   8194:        }
                   8195:      }
                   8196:      /* aij, bij */
1.259     brouard  8197:      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  8198: <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  8199:      /* Pij */
1.241     brouard  8200:      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> \
                   8201: <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  8202:      /* Quasi-incidences */
                   8203:      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  8204:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  8205:  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  8206: 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> \
                   8207: <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  8208:      /* Survival functions (period) in state j */
                   8209:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  8210:        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);
                   8211:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   8212:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.222     brouard  8213:      }
                   8214:      /* State specific survival functions (period) */
                   8215:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  8216:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
                   8217:  And probability to be observed in various states (up to %d) being in state %d at different ages.      \
1.329     brouard  8218:  <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);
                   8219:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   8220:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.222     brouard  8221:      }
1.288     brouard  8222:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  8223:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  8224:        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  8225:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
1.329     brouard  8226:       fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.222     brouard  8227:      }
1.296     brouard  8228:      if(prevbcast==1){
1.288     brouard  8229:        /* Backward prevalence in each health state */
1.222     brouard  8230:        for(cpt=1; cpt<=nlstate;cpt++){
1.338     brouard  8231:         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);
                   8232:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJB_"),subdirf2(optionfilefiname,"PIJB_"));
                   8233:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.222     brouard  8234:        }
1.217     brouard  8235:      }
1.222     brouard  8236:      if(prevfcast==1){
1.288     brouard  8237:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  8238:        for(cpt=1; cpt<=nlstate;cpt++){
1.314     brouard  8239:         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);
                   8240:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
                   8241:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
                   8242:                 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  8243:        }
                   8244:      }
1.296     brouard  8245:      if(prevbcast==1){
1.268     brouard  8246:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   8247:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  8248:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
                   8249:  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 \
                   8250:  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  8251: 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);
                   8252:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
                   8253:         fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
1.268     brouard  8254:        }
                   8255:      }
1.220     brouard  8256:         
1.222     brouard  8257:      for(cpt=1; cpt<=nlstate;cpt++) {
1.314     brouard  8258:        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);
                   8259:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
                   8260:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
1.222     brouard  8261:      }
                   8262:      /* } /\* end i1 *\/ */
1.337     brouard  8263:    }/* End k1=nres */
1.222     brouard  8264:    fprintf(fichtm,"</ul>");
1.126     brouard  8265: 
1.222     brouard  8266:    fprintf(fichtm,"\
1.126     brouard  8267: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  8268:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  8269:  - 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  8270: But because parameters are usually highly correlated (a higher incidence of disability \
                   8271: and a higher incidence of recovery can give very close observed transition) it might \
                   8272: be very useful to look not only at linear confidence intervals estimated from the \
                   8273: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   8274: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   8275: covariance matrix of the one-step probabilities. \
                   8276: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  8277: 
1.222     brouard  8278:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   8279:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   8280:    fprintf(fichtm,"\
1.126     brouard  8281:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  8282:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  8283: 
1.222     brouard  8284:    fprintf(fichtm,"\
1.126     brouard  8285:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  8286:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   8287:    fprintf(fichtm,"\
1.126     brouard  8288:  - 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): \
                   8289:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  8290:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  8291:    fprintf(fichtm,"\
1.126     brouard  8292:  - (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): \
                   8293:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  8294:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  8295:    fprintf(fichtm,"\
1.288     brouard  8296:  - 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  8297:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   8298:    fprintf(fichtm,"\
1.128     brouard  8299:  - 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  8300:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   8301:    fprintf(fichtm,"\
1.288     brouard  8302:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  8303:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  8304: 
                   8305: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   8306: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   8307: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   8308: /*     <br>",fileres,fileres,fileres,fileres); */
                   8309: /*  else  */
1.338     brouard  8310: /*    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  8311:    fflush(fichtm);
1.126     brouard  8312: 
1.225     brouard  8313:    m=pow(2,cptcoveff);
1.222     brouard  8314:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  8315: 
1.317     brouard  8316:    fprintf(fichtm," <ul><li><b>Graphs (second order)</b></li><p>");
                   8317: 
                   8318:   jj1=0;
                   8319: 
                   8320:    fprintf(fichtm," \n<ul>");
1.337     brouard  8321:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8322:      /* k1=nres; */
1.338     brouard  8323:      k1=TKresult[nres];
1.337     brouard  8324:      /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   8325:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8326:      /*   continue; */
1.317     brouard  8327:      jj1++;
                   8328:      if (cptcovn > 0) {
                   8329:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescovsecond");
1.337     brouard  8330:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8331:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8332:        }
                   8333:        fprintf(fichtm,"\">");
                   8334:        
                   8335:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   8336:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  8337:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8338:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8339:        }
                   8340:        if(invalidvarcomb[k1]){
                   8341:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   8342:         continue;
                   8343:        }
                   8344:        fprintf(fichtm,"</a></li>");
                   8345:      } /* cptcovn >0 */
1.337     brouard  8346:    } /* End nres */
1.317     brouard  8347:    fprintf(fichtm," \n</ul>");
                   8348: 
1.222     brouard  8349:    jj1=0;
1.237     brouard  8350: 
1.241     brouard  8351:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8352:      /* k1=nres; */
1.338     brouard  8353:      k1=TKresult[nres];
                   8354:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8355:      /* for(k1=1; k1<=m;k1++){ */
                   8356:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8357:      /*   continue; */
1.222     brouard  8358:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   8359:      jj1++;
1.126     brouard  8360:      if (cptcovn > 0) {
1.317     brouard  8361:        fprintf(fichtm,"\n<p><a name=\"rescovsecond");
1.337     brouard  8362:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8363:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8364:        }
                   8365:        fprintf(fichtm,"\"</a>");
                   8366:        
1.126     brouard  8367:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  8368:        for (cpt=1; cpt<=cptcovs;cpt++){  /**< cptcoveff number of variables */
                   8369:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8370:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  8371:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
1.317     brouard  8372:        }
1.237     brouard  8373: 
1.338     brouard  8374:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.220     brouard  8375: 
1.222     brouard  8376:        if(invalidvarcomb[k1]){
                   8377:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   8378:         continue;
                   8379:        }
1.337     brouard  8380:      } /* If cptcovn >0 */
1.126     brouard  8381:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  8382:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.314     brouard  8383: 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);
                   8384:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   8385:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
1.126     brouard  8386:      }
                   8387:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.314     brouard  8388: health expectancies in each live states (1 to %d). If popbased=1 the smooth (due to the model) \
1.128     brouard  8389: true period expectancies (those weighted with period prevalences are also\
                   8390:  drawn in addition to the population based expectancies computed using\
1.314     brouard  8391:  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);
                   8392:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
                   8393:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  8394:      /* } /\* end i1 *\/ */
1.241     brouard  8395:   }/* End nres */
1.222     brouard  8396:    fprintf(fichtm,"</ul>");
                   8397:    fflush(fichtm);
1.126     brouard  8398: }
                   8399: 
                   8400: /******************* Gnuplot file **************/
1.296     brouard  8401: 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  8402: 
1.354     brouard  8403:   char dirfileres[256],optfileres[256];
                   8404:   char gplotcondition[256], gplotlabel[256];
1.343     brouard  8405:   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  8406:   int lv=0, vlv=0, kl=0;
1.130     brouard  8407:   int ng=0;
1.201     brouard  8408:   int vpopbased;
1.223     brouard  8409:   int ioffset; /* variable offset for columns */
1.270     brouard  8410:   int iyearc=1; /* variable column for year of projection  */
                   8411:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  8412:   int nres=0; /* Index of resultline */
1.266     brouard  8413:   int istart=1; /* For starting graphs in projections */
1.219     brouard  8414: 
1.126     brouard  8415: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   8416: /*     printf("Problem with file %s",optionfilegnuplot); */
                   8417: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   8418: /*   } */
                   8419: 
                   8420:   /*#ifdef windows */
                   8421:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  8422:   /*#endif */
1.225     brouard  8423:   m=pow(2,cptcoveff);
1.126     brouard  8424: 
1.274     brouard  8425:   /* diagram of the model */
                   8426:   fprintf(ficgp,"\n#Diagram of the model \n");
                   8427:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   8428:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   8429:   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);
                   8430: 
1.343     brouard  8431:   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  8432:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   8433:   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);
                   8434:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   8435:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   8436:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   8437:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   8438: 
1.202     brouard  8439:   /* Contribution to likelihood */
                   8440:   /* Plot the probability implied in the likelihood */
1.223     brouard  8441:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   8442:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   8443:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   8444:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  8445: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  8446:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   8447: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  8448:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   8449:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8450:   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));
                   8451:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8452:   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));
                   8453:   for (i=1; i<= nlstate ; i ++) {
                   8454:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   8455:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   8456:     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);
                   8457:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   8458:       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);
                   8459:     }
                   8460:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8461:   }
                   8462:   /* 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 */               
                   8463:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   8464:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   8465:   fprintf(ficgp,"\nset out;unset log\n");
                   8466:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  8467: 
1.343     brouard  8468:   /* Plot the probability implied in the likelihood by covariate value */
                   8469:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
                   8470:   /* if(debugILK==1){ */
                   8471:   for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
1.347     brouard  8472:     kvar=Tvar[TvarFind[kf]]; /* variable name */
                   8473:     /* k=18+Tvar[TvarFind[kf]];/\*offset because there are 18 columns in the ILK_ file but could be placed else where *\/ */
1.350     brouard  8474:     /* k=18+kf;/\*offset because there are 18 columns in the ILK_ file *\/ */
1.356     brouard  8475:     /* k=19+kf;/\*offset because there are 19 columns in the ILK_ file *\/ */
1.355     brouard  8476:     k=16+nlstate+kf;/*offset because there are 19 columns in the ILK_ file, first cov Vn on col 21 with 4 living states */
1.343     brouard  8477:     for (i=1; i<= nlstate ; i ++) {
                   8478:       fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   8479:       fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
1.348     brouard  8480:       if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
                   8481:        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);
                   8482:        for (j=2; j<= nlstate+ndeath ; j ++) {
                   8483:          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);
                   8484:        }
                   8485:       }else{
                   8486:        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);
                   8487:        for (j=2; j<= nlstate+ndeath ; j ++) {
                   8488:          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);
                   8489:        }
1.343     brouard  8490:       }
                   8491:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8492:     }
                   8493:   } /* End of each covariate dummy */
                   8494:   for(ncovv=1, iposold=0, kk=0; ncovv <= ncovvt ; ncovv++){
                   8495:     /* Other example        V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   8496:      *     kmodel       =     1   2     3     4         5        6        7       8        9
                   8497:      *  varying                   1     2                                 3       4        5
                   8498:      *  ncovv                     1     2                                3 4     5 6      7 8
                   8499:      * TvarVV[ncovv]             V3     5                                1 3     3 5      1 5
                   8500:      * TvarVVind[ncovv]=kmodel    2     3                                7 7     8 8      9 9
                   8501:      * TvarFind[kmodel]       1   0     0     0         0        0        0       0        0
                   8502:      * kdata     ncovcol=[V1 V2] nqv=0 ntv=[V3 V4] nqtv=V5
                   8503:      * Dummy[kmodel]          0   0     1     2         2        3        1       1        1
                   8504:      */
                   8505:     ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   8506:     kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   8507:     /* 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]); */
                   8508:     if(ipos!=iposold){ /* Not a product or first of a product */
                   8509:       /* printf(" %d",ipos); */
                   8510:       /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   8511:       /* printf(" DebugILK ficgp suite ipos=%d != iposold=%d\n", ipos, iposold); */
                   8512:       kk++; /* Position of the ncovv column in ILK_ */
                   8513:       k=18+ncovf+kk; /*offset because there are 18 columns in the ILK_ file plus ncovf fixed covariate */
                   8514:       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)  */
                   8515:        for (i=1; i<= nlstate ; i ++) {
                   8516:          fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   8517:          fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
                   8518: 
1.348     brouard  8519:            /* printf("Before DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
1.343     brouard  8520:          if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
                   8521:            /* printf("DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
                   8522:            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);
                   8523:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   8524:              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);
                   8525:            }
                   8526:          }else{
                   8527:            /* printf("DebugILK gnuplotversion=%g <5.2\n",gnuplotversion); */
                   8528:            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);
                   8529:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   8530:              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);
                   8531:            }
                   8532:          }
                   8533:          fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8534:        }
                   8535:       }/* End if dummy varying */
                   8536:     }else{ /*Product */
                   8537:       /* printf("*"); */
                   8538:       /* fprintf(ficresilk,"*"); */
                   8539:     }
                   8540:     iposold=ipos;
                   8541:   } /* For each time varying covariate */
                   8542:   /* } /\* debugILK==1 *\/ */
                   8543:   /* 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 */               
                   8544:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   8545:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   8546:   fprintf(ficgp,"\nset out;unset log\n");
                   8547:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
                   8548: 
                   8549: 
                   8550:   
1.126     brouard  8551:   strcpy(dirfileres,optionfilefiname);
                   8552:   strcpy(optfileres,"vpl");
1.223     brouard  8553:   /* 1eme*/
1.238     brouard  8554:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
1.337     brouard  8555:     /* for (k1=1; k1<= m ; k1 ++){ /\* For each valid combination of covariate *\/ */
1.236     brouard  8556:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8557:        k1=TKresult[nres];
1.338     brouard  8558:        if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.238     brouard  8559:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.337     brouard  8560:        /* if(m != 1 && TKresult[nres]!= k1) */
                   8561:        /*   continue; */
1.238     brouard  8562:        /* We are interested in selected combination by the resultline */
1.246     brouard  8563:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  8564:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  8565:        strcpy(gplotlabel,"(");
1.337     brouard  8566:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8567:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8568:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8569: 
                   8570:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate k get corresponding value lv for combination k1 *\/ */
                   8571:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the value of the covariate corresponding to k1 combination *\\/ *\/ */
                   8572:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8573:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8574:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8575:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8576:        /*   vlv= nbcode[Tvaraff[k]][lv]; /\* vlv is the value of the covariate lv, 0 or 1 *\/ */
                   8577:        /*   /\* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv *\/ */
                   8578:        /*   /\* printf(" V%d=%d ",Tvaraff[k],vlv); *\/ */
                   8579:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8580:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8581:        /* } */
                   8582:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8583:        /*   /\* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); *\/ */
                   8584:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8585:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.264     brouard  8586:        }
                   8587:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  8588:        /* printf("\n#\n"); */
1.238     brouard  8589:        fprintf(ficgp,"\n#\n");
                   8590:        if(invalidvarcomb[k1]){
1.260     brouard  8591:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  8592:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8593:          continue;
                   8594:        }
1.235     brouard  8595:       
1.241     brouard  8596:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   8597:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  8598:        /* 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  8599:        fprintf(ficgp,"set title \"Alive state %d %s model=1+age+%s\" font \"Helvetica,12\"\n",cpt,gplotlabel,model);
1.260     brouard  8600:        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);
                   8601:        /* 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); */
                   8602:       /* k1-1 error should be nres-1*/
1.238     brouard  8603:        for (i=1; i<= nlstate ; i ++) {
                   8604:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8605:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   8606:        }
1.288     brouard  8607:        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  8608:        for (i=1; i<= nlstate ; i ++) {
                   8609:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8610:          else fprintf(ficgp," %%*lf (%%*lf)");
                   8611:        } 
1.260     brouard  8612:        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  8613:        for (i=1; i<= nlstate ; i ++) {
                   8614:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8615:          else fprintf(ficgp," %%*lf (%%*lf)");
                   8616:        }  
1.265     brouard  8617:        /* 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)); */
                   8618:        
                   8619:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   8620:         if(cptcoveff ==0){
1.271     brouard  8621:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  8622:        }else{
                   8623:          kl=0;
                   8624:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  8625:            /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8626:            lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.265     brouard  8627:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8628:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8629:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8630:            vlv= nbcode[Tvaraff[k]][lv];
                   8631:            kl++;
                   8632:            /* 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 *\/ */
                   8633:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8634:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8635:            /* ''  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*/
                   8636:            if(k==cptcoveff){
                   8637:              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], \
                   8638:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   8639:            }else{
                   8640:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   8641:              kl++;
                   8642:            }
                   8643:          } /* end covariate */
                   8644:        } /* end if no covariate */
                   8645: 
1.296     brouard  8646:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  8647:          /* 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  8648:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  8649:          if(cptcoveff ==0){
1.245     brouard  8650:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  8651:          }else{
                   8652:            kl=0;
                   8653:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  8654:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8655:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.238     brouard  8656:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8657:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8658:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8659:              /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8660:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.223     brouard  8661:              kl++;
1.238     brouard  8662:              /* 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 *\/ */
                   8663:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8664:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8665:              /* ''  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*/
                   8666:              if(k==cptcoveff){
1.245     brouard  8667:                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  8668:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  8669:              }else{
1.332     brouard  8670:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]);
1.238     brouard  8671:                kl++;
                   8672:              }
                   8673:            } /* end covariate */
                   8674:          } /* end if no covariate */
1.296     brouard  8675:          if(prevbcast == 1){
1.268     brouard  8676:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   8677:            /* k1-1 error should be nres-1*/
                   8678:            for (i=1; i<= nlstate ; i ++) {
                   8679:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8680:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   8681:            }
1.271     brouard  8682:            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  8683:            for (i=1; i<= nlstate ; i ++) {
                   8684:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8685:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8686:            } 
1.276     brouard  8687:            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  8688:            for (i=1; i<= nlstate ; i ++) {
                   8689:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8690:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8691:            } 
1.274     brouard  8692:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  8693:          } /* end if backprojcast */
1.296     brouard  8694:        } /* end if prevbcast */
1.276     brouard  8695:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   8696:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  8697:       } /* nres */
1.337     brouard  8698:     /* } /\* k1 *\/ */
1.201     brouard  8699:   } /* cpt */
1.235     brouard  8700: 
                   8701:   
1.126     brouard  8702:   /*2 eme*/
1.337     brouard  8703:   /* for (k1=1; k1<= m ; k1 ++){   */
1.238     brouard  8704:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8705:       k1=TKresult[nres];
1.338     brouard  8706:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8707:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8708:       /*       continue; */
1.238     brouard  8709:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  8710:       strcpy(gplotlabel,"(");
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(k=1; k <= ncovds; k++){ *\/ */
                   8726:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8727:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8728:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8729:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  8730:       }
1.264     brouard  8731:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8732:       fprintf(ficgp,"\n#\n");
1.223     brouard  8733:       if(invalidvarcomb[k1]){
                   8734:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8735:        continue;
                   8736:       }
1.219     brouard  8737:                        
1.241     brouard  8738:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  8739:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  8740:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   8741:        if(vpopbased==0){
1.238     brouard  8742:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  8743:        }else
1.238     brouard  8744:          fprintf(ficgp,"\nreplot ");
                   8745:        for (i=1; i<= nlstate+1 ; i ++) {
                   8746:          k=2*i;
1.261     brouard  8747:          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  8748:          for (j=1; j<= nlstate+1 ; j ++) {
                   8749:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8750:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8751:          }   
                   8752:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   8753:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
1.261     brouard  8754:          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  8755:          for (j=1; j<= nlstate+1 ; j ++) {
                   8756:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8757:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8758:          }   
                   8759:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  8760:          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  8761:          for (j=1; j<= nlstate+1 ; j ++) {
                   8762:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8763:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8764:          }   
                   8765:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   8766:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   8767:        } /* state */
                   8768:       } /* vpopbased */
1.264     brouard  8769:       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  8770:     } /* end nres */
1.337     brouard  8771:   /* } /\* k1 end 2 eme*\/ */
1.238     brouard  8772:        
                   8773:        
                   8774:   /*3eme*/
1.337     brouard  8775:   /* for (k1=1; k1<= m ; k1 ++){ */
1.238     brouard  8776:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8777:       k1=TKresult[nres];
1.338     brouard  8778:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8779:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8780:       /*       continue; */
1.238     brouard  8781: 
1.332     brouard  8782:       for (cpt=1; cpt<= nlstate ; cpt ++) { /* Fragile no verification of covariate values */
1.261     brouard  8783:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  8784:        strcpy(gplotlabel,"(");
1.337     brouard  8785:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8786:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8787:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8788:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8789:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8790:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8791:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8792:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8793:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8794:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8795:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8796:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8797:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8798:        /* } */
                   8799:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8800:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   8801:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   8802:        }
1.264     brouard  8803:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8804:        fprintf(ficgp,"\n#\n");
                   8805:        if(invalidvarcomb[k1]){
                   8806:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8807:          continue;
                   8808:        }
                   8809:                        
                   8810:        /*       k=2+nlstate*(2*cpt-2); */
                   8811:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  8812:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  8813:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  8814:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  8815: 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  8816:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8817:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8818:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   8819:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8820:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8821:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  8822:                                
1.238     brouard  8823:        */
                   8824:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  8825:          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  8826:          /*    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  8827:                                
1.238     brouard  8828:        } 
1.261     brouard  8829:        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  8830:       }
1.264     brouard  8831:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  8832:     } /* end nres */
1.337     brouard  8833:   /* } /\* end kl 3eme *\/ */
1.126     brouard  8834:   
1.223     brouard  8835:   /* 4eme */
1.201     brouard  8836:   /* Survival functions (period) from state i in state j by initial state i */
1.337     brouard  8837:   /* for (k1=1; k1<=m; k1++){    /\* For each covariate and each value *\/ */
1.238     brouard  8838:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8839:       k1=TKresult[nres];
1.338     brouard  8840:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8841:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8842:       /*       continue; */
1.238     brouard  8843:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  8844:        strcpy(gplotlabel,"(");
1.337     brouard  8845:        fprintf(ficgp,"\n#\n#\n# Survival functions in state %d : 'LIJ_' files, cov=%d state=%d", cpt, k1, cpt);
                   8846:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8847:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8848:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8849:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8850:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8851:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8852:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8853:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8854:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8855:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8856:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8857:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8858:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8859:        /* } */
                   8860:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8861:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8862:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  8863:        }       
1.264     brouard  8864:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8865:        fprintf(ficgp,"\n#\n");
                   8866:        if(invalidvarcomb[k1]){
                   8867:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8868:          continue;
1.223     brouard  8869:        }
1.238     brouard  8870:       
1.241     brouard  8871:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  8872:        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  8873:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8874: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8875:        k=3;
                   8876:        for (i=1; i<= nlstate ; i ++){
                   8877:          if(i==1){
                   8878:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8879:          }else{
                   8880:            fprintf(ficgp,", '' ");
                   8881:          }
                   8882:          l=(nlstate+ndeath)*(i-1)+1;
                   8883:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8884:          for (j=2; j<= nlstate+ndeath ; j ++)
                   8885:            fprintf(ficgp,"+$%d",k+l+j-1);
                   8886:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   8887:        } /* nlstate */
1.264     brouard  8888:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8889:       } /* end cpt state*/ 
                   8890:     } /* end nres */
1.337     brouard  8891:   /* } /\* end covariate k1 *\/   */
1.238     brouard  8892: 
1.220     brouard  8893: /* 5eme */
1.201     brouard  8894:   /* Survival functions (period) from state i in state j by final state j */
1.337     brouard  8895:   /* for (k1=1; k1<= m ; k1++){ /\* For each covariate combination if any *\/ */
1.238     brouard  8896:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8897:       k1=TKresult[nres];
1.338     brouard  8898:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8899:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8900:       /*       continue; */
1.238     brouard  8901:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  8902:        strcpy(gplotlabel,"(");
1.238     brouard  8903:        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  8904:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8905:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8906:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8907:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8908:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8909:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8910:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8911:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8912:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8913:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8914:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8915:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8916:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8917:        /* } */
                   8918:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8919:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8920:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  8921:        }       
1.264     brouard  8922:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8923:        fprintf(ficgp,"\n#\n");
                   8924:        if(invalidvarcomb[k1]){
                   8925:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8926:          continue;
                   8927:        }
1.227     brouard  8928:       
1.241     brouard  8929:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  8930:        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  8931:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8932: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8933:        k=3;
                   8934:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8935:          if(j==1)
                   8936:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8937:          else
                   8938:            fprintf(ficgp,", '' ");
                   8939:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8940:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   8941:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   8942:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   8943:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   8944:        } /* nlstate */
                   8945:        fprintf(ficgp,", '' ");
                   8946:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   8947:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8948:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8949:          if(j < nlstate)
                   8950:            fprintf(ficgp,"$%d +",k+l);
                   8951:          else
                   8952:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   8953:        }
1.264     brouard  8954:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8955:       } /* end cpt state*/ 
1.337     brouard  8956:     /* } /\* end covariate *\/   */
1.238     brouard  8957:   } /* end nres */
1.227     brouard  8958:   
1.220     brouard  8959: /* 6eme */
1.202     brouard  8960:   /* CV preval stable (period) for each covariate */
1.337     brouard  8961:   /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8962:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8963:      k1=TKresult[nres];
1.338     brouard  8964:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8965:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8966:      /*  continue; */
1.255     brouard  8967:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  8968:       strcpy(gplotlabel,"(");      
1.288     brouard  8969:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8970:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8971:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8972:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8973:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8974:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8975:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8976:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8977:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8978:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8979:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8980:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8981:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8982:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8983:       /* } */
                   8984:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8985:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8986:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8987:       }        
1.264     brouard  8988:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8989:       fprintf(ficgp,"\n#\n");
1.223     brouard  8990:       if(invalidvarcomb[k1]){
1.227     brouard  8991:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8992:        continue;
1.223     brouard  8993:       }
1.227     brouard  8994:       
1.241     brouard  8995:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  8996:       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  8997:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8998: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  8999:       k=3; /* Offset */
1.255     brouard  9000:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  9001:        if(i==1)
                   9002:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   9003:        else
                   9004:          fprintf(ficgp,", '' ");
1.255     brouard  9005:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  9006:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   9007:        for (j=2; j<= nlstate ; j ++)
                   9008:          fprintf(ficgp,"+$%d",k+l+j-1);
                   9009:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  9010:       } /* nlstate */
1.264     brouard  9011:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  9012:     } /* end cpt state*/ 
                   9013:   } /* end covariate */  
1.227     brouard  9014:   
                   9015:   
1.220     brouard  9016: /* 7eme */
1.296     brouard  9017:   if(prevbcast == 1){
1.288     brouard  9018:     /* CV backward prevalence  for each covariate */
1.337     brouard  9019:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  9020:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  9021:       k1=TKresult[nres];
1.338     brouard  9022:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9023:       /* if(m != 1 && TKresult[nres]!= k1) */
                   9024:       /*       continue; */
1.268     brouard  9025:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  9026:        strcpy(gplotlabel,"(");      
1.288     brouard  9027:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  9028:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9029:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9030:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9031:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   9032:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   9033:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   9034:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9035:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9036:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9037:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9038:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9039:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9040:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9041:        /* } */
                   9042:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9043:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9044:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  9045:        }       
1.264     brouard  9046:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  9047:        fprintf(ficgp,"\n#\n");
                   9048:        if(invalidvarcomb[k1]){
                   9049:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   9050:          continue;
                   9051:        }
                   9052:        
1.241     brouard  9053:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  9054:        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  9055:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  9056: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  9057:        k=3; /* Offset */
1.268     brouard  9058:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  9059:          if(i==1)
                   9060:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   9061:          else
                   9062:            fprintf(ficgp,", '' ");
                   9063:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  9064:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.324     brouard  9065:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   9066:          /* 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  9067:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  9068:          /* for (j=2; j<= nlstate ; j ++) */
                   9069:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   9070:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  9071:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  9072:        } /* nlstate */
1.264     brouard  9073:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  9074:       } /* end cpt state*/ 
                   9075:     } /* end covariate */  
1.296     brouard  9076:   } /* End if prevbcast */
1.218     brouard  9077:   
1.223     brouard  9078:   /* 8eme */
1.218     brouard  9079:   if(prevfcast==1){
1.288     brouard  9080:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  9081:     
1.337     brouard  9082:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  9083:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  9084:       k1=TKresult[nres];
1.338     brouard  9085:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9086:       /* if(m != 1 && TKresult[nres]!= k1) */
                   9087:       /*       continue; */
1.211     brouard  9088:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  9089:        strcpy(gplotlabel,"(");      
1.288     brouard  9090:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  9091:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9092:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9093:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9094:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   9095:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   9096:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   9097:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9098:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9099:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9100:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9101:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9102:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9103:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9104:        /* } */
                   9105:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9106:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9107:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  9108:        }       
1.264     brouard  9109:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  9110:        fprintf(ficgp,"\n#\n");
                   9111:        if(invalidvarcomb[k1]){
                   9112:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   9113:          continue;
                   9114:        }
                   9115:        
                   9116:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  9117:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  9118:        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  9119:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  9120: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  9121: 
                   9122:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   9123:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9124:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9125:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  9126:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9127:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   9128:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9129:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  9130:          if(i==istart){
1.227     brouard  9131:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   9132:          }else{
                   9133:            fprintf(ficgp,",\\\n '' ");
                   9134:          }
                   9135:          if(cptcoveff ==0){ /* No covariate */
                   9136:            ioffset=2; /* Age is in 2 */
                   9137:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9138:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9139:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9140:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9141:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  9142:            if(i==nlstate+1){
1.270     brouard  9143:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  9144:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   9145:              fprintf(ficgp,",\\\n '' ");
                   9146:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  9147:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  9148:                     offyear,                           \
1.268     brouard  9149:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  9150:            }else
1.227     brouard  9151:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   9152:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   9153:          }else{ /* more than 2 covariates */
1.270     brouard  9154:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   9155:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9156:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   9157:            iyearc=ioffset-1;
                   9158:            iagec=ioffset;
1.227     brouard  9159:            fprintf(ficgp," u %d:(",ioffset); 
                   9160:            kl=0;
                   9161:            strcpy(gplotcondition,"(");
1.351     brouard  9162:            /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
1.332     brouard  9163:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
1.351     brouard  9164:            for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9165:              /* lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   9166:              lv=Tvresult[nres][k];
                   9167:              vlv=TinvDoQresult[nres][Tvresult[nres][k]];
1.227     brouard  9168:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   9169:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   9170:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  9171:              /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
1.351     brouard  9172:              /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
1.227     brouard  9173:              kl++;
1.351     brouard  9174:              /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
                   9175:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,lv, kl+1, vlv );
1.227     brouard  9176:              kl++;
1.351     brouard  9177:              if(k <cptcovs && cptcovs>1)
1.227     brouard  9178:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   9179:            }
                   9180:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   9181:            /* 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 *\/ */
                   9182:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   9183:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   9184:            /* ''  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*/
                   9185:            if(i==nlstate+1){
1.270     brouard  9186:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   9187:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  9188:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  9189:              fprintf(ficgp," u %d:(",iagec); 
                   9190:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   9191:                      iyearc, iagec, offyear,                           \
                   9192:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  9193: /*  '' 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  9194:            }else{
                   9195:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   9196:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   9197:            }
                   9198:          } /* end if covariate */
                   9199:        } /* nlstate */
1.264     brouard  9200:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  9201:       } /* end cpt state*/
                   9202:     } /* end covariate */
                   9203:   } /* End if prevfcast */
1.227     brouard  9204:   
1.296     brouard  9205:   if(prevbcast==1){
1.268     brouard  9206:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   9207:     
1.337     brouard  9208:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.268     brouard  9209:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  9210:      k1=TKresult[nres];
1.338     brouard  9211:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9212:        /* if(m != 1 && TKresult[nres]!= k1) */
                   9213:        /*      continue; */
1.268     brouard  9214:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   9215:        strcpy(gplotlabel,"(");      
                   9216:        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  9217:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9218:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9219:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9220:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   9221:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   9222:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9223:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9224:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9225:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9226:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9227:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9228:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9229:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9230:        /* } */
                   9231:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9232:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9233:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.268     brouard  9234:        }       
                   9235:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   9236:        fprintf(ficgp,"\n#\n");
                   9237:        if(invalidvarcomb[k1]){
                   9238:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   9239:          continue;
                   9240:        }
                   9241:        
                   9242:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   9243:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   9244:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   9245:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   9246: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   9247: 
                   9248:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   9249:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9250:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9251:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   9252:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9253:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   9254:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9255:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   9256:          if(i==istart){
                   9257:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   9258:          }else{
                   9259:            fprintf(ficgp,",\\\n '' ");
                   9260:          }
1.351     brouard  9261:          /* if(cptcoveff ==0){ /\* No covariate *\/ */
                   9262:          if(cptcovs ==0){ /* No covariate */
1.268     brouard  9263:            ioffset=2; /* Age is in 2 */
                   9264:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9265:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9266:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9267:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9268:            fprintf(ficgp," u %d:(", ioffset); 
                   9269:            if(i==nlstate+1){
1.270     brouard  9270:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  9271:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   9272:              fprintf(ficgp,",\\\n '' ");
                   9273:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  9274:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  9275:                     offbyear,                          \
                   9276:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   9277:            }else
                   9278:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   9279:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   9280:          }else{ /* more than 2 covariates */
1.270     brouard  9281:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   9282:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9283:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   9284:            iyearc=ioffset-1;
                   9285:            iagec=ioffset;
1.268     brouard  9286:            fprintf(ficgp," u %d:(",ioffset); 
                   9287:            kl=0;
                   9288:            strcpy(gplotcondition,"(");
1.337     brouard  9289:            for (k=1; k<=cptcovs; k++){    /* For each covariate k of the resultline, get corresponding value lv for combination k1 */
1.338     brouard  9290:              if(Dummy[modelresult[nres][k]]==0){  /* To be verified */
1.337     brouard  9291:                /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
                   9292:                /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9293:                /* lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9294:                lv=Tvresult[nres][k];
                   9295:                vlv=TinvDoQresult[nres][Tvresult[nres][k]];
                   9296:                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   9297:                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   9298:                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   9299:                /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   9300:                /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9301:                kl++;
                   9302:                /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
                   9303:                sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%lg " ,kl,Tvresult[nres][k], kl+1,TinvDoQresult[nres][Tvresult[nres][k]]);
                   9304:                kl++;
1.338     brouard  9305:                if(k <cptcovs && cptcovs>1)
1.337     brouard  9306:                  sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   9307:              }
1.268     brouard  9308:            }
                   9309:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   9310:            /* 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 *\/ */
                   9311:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   9312:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   9313:            /* ''  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*/
                   9314:            if(i==nlstate+1){
1.270     brouard  9315:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   9316:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  9317:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  9318:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  9319:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  9320:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   9321:                      iyearc,iagec,offbyear,                            \
                   9322:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  9323: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   9324:            }else{
                   9325:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   9326:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   9327:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   9328:            }
                   9329:          } /* end if covariate */
                   9330:        } /* nlstate */
                   9331:        fprintf(ficgp,"\nset out; unset label;\n");
                   9332:       } /* end cpt state*/
                   9333:     } /* end covariate */
1.296     brouard  9334:   } /* End if prevbcast */
1.268     brouard  9335:   
1.227     brouard  9336:   
1.238     brouard  9337:   /* 9eme writing MLE parameters */
                   9338:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  9339:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  9340:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  9341:     for(k=1; k <=(nlstate+ndeath); k++){
                   9342:       if (k != i) {
1.227     brouard  9343:        fprintf(ficgp,"#   current state %d\n",k);
                   9344:        for(j=1; j <=ncovmodel; j++){
                   9345:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   9346:          jk++; 
                   9347:        }
                   9348:        fprintf(ficgp,"\n");
1.126     brouard  9349:       }
                   9350:     }
1.223     brouard  9351:   }
1.187     brouard  9352:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  9353:   
1.145     brouard  9354:   /*goto avoid;*/
1.238     brouard  9355:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   9356:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  9357:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   9358:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   9359:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   9360:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   9361:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9362:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   9363:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9364:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   9365:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   9366:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9367:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   9368:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   9369:   fprintf(ficgp,"#\n");
1.223     brouard  9370:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  9371:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.338     brouard  9372:     fprintf(ficgp,"#model=1+age+%s \n",model);
1.238     brouard  9373:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.351     brouard  9374:     /* fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/\* to be checked *\/ */
                   9375:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcovs,m);/* to be checked */
1.337     brouard  9376:     /* for(k1=1; k1 <=m; k1++)  /\* For each combination of covariate *\/ */
1.237     brouard  9377:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  9378:      /* k1=nres; */
1.338     brouard  9379:       k1=TKresult[nres];
                   9380:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9381:       fprintf(ficgp,"\n\n# Resultline k1=%d ",k1);
1.264     brouard  9382:       strcpy(gplotlabel,"(");
1.276     brouard  9383:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.337     brouard  9384:       for (k=1; k<=cptcovs; k++){  /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   9385:        /* for each resultline nres, and position k, Tvresult[nres][k] gives the name of the variable and
                   9386:           TinvDoQresult[nres][Tvresult[nres][k]] gives its value double or integer) */
                   9387:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9388:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9389:       }
                   9390:       /* if(m != 1 && TKresult[nres]!= k1) */
                   9391:       /*       continue; */
                   9392:       /* fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1); */
                   9393:       /* strcpy(gplotlabel,"("); */
                   9394:       /* /\*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*\/ */
                   9395:       /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   9396:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   9397:       /*       lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9398:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9399:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9400:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9401:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9402:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9403:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9404:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9405:       /* } */
                   9406:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9407:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9408:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9409:       /* }      */
1.264     brouard  9410:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  9411:       fprintf(ficgp,"\n#\n");
1.264     brouard  9412:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  9413:       fprintf(ficgp,"\nset key outside ");
                   9414:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   9415:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  9416:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   9417:       if (ng==1){
                   9418:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   9419:        fprintf(ficgp,"\nunset log y");
                   9420:       }else if (ng==2){
                   9421:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   9422:        fprintf(ficgp,"\nset log y");
                   9423:       }else if (ng==3){
                   9424:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   9425:        fprintf(ficgp,"\nset log y");
                   9426:       }else
                   9427:        fprintf(ficgp,"\nunset title ");
                   9428:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   9429:       i=1;
                   9430:       for(k2=1; k2<=nlstate; k2++) {
                   9431:        k3=i;
                   9432:        for(k=1; k<=(nlstate+ndeath); k++) {
                   9433:          if (k != k2){
                   9434:            switch( ng) {
                   9435:            case 1:
                   9436:              if(nagesqr==0)
                   9437:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   9438:              else /* nagesqr =1 */
                   9439:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   9440:              break;
                   9441:            case 2: /* ng=2 */
                   9442:              if(nagesqr==0)
                   9443:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   9444:              else /* nagesqr =1 */
                   9445:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   9446:              break;
                   9447:            case 3:
                   9448:              if(nagesqr==0)
                   9449:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   9450:              else /* nagesqr =1 */
                   9451:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   9452:              break;
                   9453:            }
                   9454:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  9455:            ijp=1; /* product no age */
                   9456:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   9457:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  9458:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.329     brouard  9459:              switch(Typevar[j]){
                   9460:              case 1:
                   9461:                if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   9462:                  if(j==Tage[ij]) { /* Product by age  To be looked at!!*//* Bug valgrind */
                   9463:                    if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   9464:                      if(DummyV[j]==0){/* Bug valgrind */
                   9465:                        fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   9466:                      }else{ /* quantitative */
                   9467:                        fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   9468:                        /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9469:                      }
                   9470:                      ij++;
1.268     brouard  9471:                    }
1.237     brouard  9472:                  }
1.329     brouard  9473:                }
                   9474:                break;
                   9475:              case 2:
                   9476:                if(cptcovprod >0){
                   9477:                  if(j==Tprod[ijp]) { /* */ 
                   9478:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9479:                    if(ijp <=cptcovprod) { /* Product */
                   9480:                      if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   9481:                        if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   9482:                          /* 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)]); */
                   9483:                          fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9484:                        }else{ /* Vn is dummy and Vm is quanti */
                   9485:                          /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9486:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9487:                        }
                   9488:                      }else{ /* Vn*Vm Vn is quanti */
                   9489:                        if(DummyV[Tvard[ijp][2]]==0){
                   9490:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   9491:                        }else{ /* Both quanti */
                   9492:                          fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9493:                        }
1.268     brouard  9494:                      }
1.329     brouard  9495:                      ijp++;
1.237     brouard  9496:                    }
1.329     brouard  9497:                  } /* end Tprod */
                   9498:                }
                   9499:                break;
1.349     brouard  9500:              case 3:
                   9501:                if(cptcovdageprod >0){
                   9502:                  /* if(j==Tprod[ijp]) { */ /* not necessary */ 
                   9503:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
1.350     brouard  9504:                    if(ijp <=cptcovprod) { /* Product Vn*Vm and age*VN*Vm*/
                   9505:                      if(DummyV[Tvardk[ijp][1]]==0){/* Vn is dummy */
                   9506:                        if(DummyV[Tvardk[ijp][2]]==0){/* Vn and Vm are dummy */
1.349     brouard  9507:                          /* 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)]); */
                   9508:                          fprintf(ficgp,"+p%d*%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9509:                        }else{ /* Vn is dummy and Vm is quanti */
                   9510:                          /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
1.350     brouard  9511:                          fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvardk[ijp][1]],Tqinvresult[nres][Tvardk[ijp][2]]);
1.349     brouard  9512:                        }
1.350     brouard  9513:                      }else{ /* age* Vn*Vm Vn is quanti HERE */
1.349     brouard  9514:                        if(DummyV[Tvard[ijp][2]]==0){
1.350     brouard  9515:                          fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvardk[ijp][2]],Tqinvresult[nres][Tvardk[ijp][1]]);
1.349     brouard  9516:                        }else{ /* Both quanti */
1.350     brouard  9517:                          fprintf(ficgp,"+p%d*%f*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvardk[ijp][1]],Tqinvresult[nres][Tvardk[ijp][2]]);
1.349     brouard  9518:                        }
                   9519:                      }
                   9520:                      ijp++;
                   9521:                    }
                   9522:                    /* } */ /* end Tprod */
                   9523:                }
                   9524:                break;
1.329     brouard  9525:              case 0:
                   9526:                /* simple covariate */
1.264     brouard  9527:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  9528:                if(Dummy[j]==0){
                   9529:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   9530:                }else{ /* quantitative */
                   9531:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  9532:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  9533:                }
1.329     brouard  9534:               /* end simple */
                   9535:                break;
                   9536:              default:
                   9537:                break;
                   9538:              } /* end switch */
1.237     brouard  9539:            } /* end j */
1.329     brouard  9540:          }else{ /* k=k2 */
                   9541:            if(ng !=1 ){ /* For logit formula of log p11 is more difficult to get */
                   9542:              fprintf(ficgp," (1.");i=i-ncovmodel;
                   9543:            }else
                   9544:              i=i-ncovmodel;
1.223     brouard  9545:          }
1.227     brouard  9546:          
1.223     brouard  9547:          if(ng != 1){
                   9548:            fprintf(ficgp,")/(1");
1.227     brouard  9549:            
1.264     brouard  9550:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  9551:              if(nagesqr==0)
1.264     brouard  9552:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  9553:              else /* nagesqr =1 */
1.264     brouard  9554:                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  9555:               
1.223     brouard  9556:              ij=1;
1.329     brouard  9557:              ijp=1;
                   9558:              /* for(j=3; j <=ncovmodel-nagesqr; j++){ */
                   9559:              for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
                   9560:                switch(Typevar[j]){
                   9561:                case 1:
                   9562:                  if(cptcovage >0){ 
                   9563:                    if(j==Tage[ij]) { /* Bug valgrind */
                   9564:                      if(ij <=cptcovage) { /* Bug valgrind */
                   9565:                        if(DummyV[j]==0){/* Bug valgrind */
                   9566:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]); */
                   9567:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,nbcode[Tvar[j]][codtabm(k1,j)]); */
                   9568:                          fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]);
                   9569:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);; */
                   9570:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9571:                        }else{ /* quantitative */
                   9572:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   9573:                          fprintf(ficgp,"+p%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   9574:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   9575:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9576:                        }
                   9577:                        ij++;
                   9578:                      }
                   9579:                    }
                   9580:                  }
                   9581:                  break;
                   9582:                case 2:
                   9583:                  if(cptcovprod >0){
                   9584:                    if(j==Tprod[ijp]) { /* */ 
                   9585:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9586:                      if(ijp <=cptcovprod) { /* Product */
                   9587:                        if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   9588:                          if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   9589:                            /* 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)]); */
                   9590:                            fprintf(ficgp,"+p%d*%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9591:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   9592:                          }else{ /* Vn is dummy and Vm is quanti */
                   9593:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9594:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9595:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9596:                          }
                   9597:                        }else{ /* Vn*Vm Vn is quanti */
                   9598:                          if(DummyV[Tvard[ijp][2]]==0){
                   9599:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   9600:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   9601:                          }else{ /* Both quanti */
                   9602:                            fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9603:                            /* fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9604:                          } 
                   9605:                        }
                   9606:                        ijp++;
                   9607:                      }
                   9608:                    } /* end Tprod */
                   9609:                  } /* end if */
                   9610:                  break;
1.349     brouard  9611:                case 3:
                   9612:                  if(cptcovdageprod >0){
                   9613:                    /* if(j==Tprod[ijp]) { /\* *\/  */
                   9614:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9615:                      if(ijp <=cptcovprod) { /* Product */
1.350     brouard  9616:                        if(DummyV[Tvardk[ijp][1]]==0){/* Vn is dummy */
                   9617:                          if(DummyV[Tvardk[ijp][2]]==0){/* Vn and Vm are dummy */
1.349     brouard  9618:                            /* 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)]); */
1.350     brouard  9619:                            fprintf(ficgp,"+p%d*%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvardk[ijp][1]],Tinvresult[nres][Tvardk[ijp][2]]);
1.349     brouard  9620:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   9621:                          }else{ /* Vn is dummy and Vm is quanti */
                   9622:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
1.350     brouard  9623:                            fprintf(ficgp,"+p%d*%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvardk[ijp][1]],Tqinvresult[nres][Tvardk[ijp][2]]);
1.349     brouard  9624:                            /* fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9625:                          }
                   9626:                        }else{ /* Vn*Vm Vn is quanti */
1.350     brouard  9627:                          if(DummyV[Tvardk[ijp][2]]==0){
                   9628:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvardk[ijp][2]],Tqinvresult[nres][Tvardk[ijp][1]]);
1.349     brouard  9629:                            /* fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   9630:                          }else{ /* Both quanti */
1.350     brouard  9631:                            fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvardk[ijp][1]],Tqinvresult[nres][Tvardk[ijp][2]]);
1.349     brouard  9632:                            /* fprintf(ficgp,"+p%d*%f*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9633:                          } 
                   9634:                        }
                   9635:                        ijp++;
                   9636:                      }
                   9637:                    /* } /\* end Tprod *\/ */
                   9638:                  } /* end if */
                   9639:                  break;
1.329     brouard  9640:                case 0: 
                   9641:                  /* simple covariate */
                   9642:                  /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
                   9643:                  if(Dummy[j]==0){
                   9644:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   9645:                    fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]); /*  */
                   9646:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   9647:                  }else{ /* quantitative */
                   9648:                    fprintf(ficgp,"+p%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* */
                   9649:                    /* fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* *\/ */
                   9650:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9651:                  }
                   9652:                  /* end simple */
                   9653:                  /* fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);/\* Valgrind bug nbcode *\/ */
                   9654:                  break;
                   9655:                default:
                   9656:                  break;
                   9657:                } /* end switch */
1.223     brouard  9658:              }
                   9659:              fprintf(ficgp,")");
                   9660:            }
                   9661:            fprintf(ficgp,")");
                   9662:            if(ng ==2)
1.276     brouard  9663:              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  9664:            else /* ng= 3 */
1.276     brouard  9665:              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  9666:           }else{ /* end ng <> 1 */
1.223     brouard  9667:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  9668:              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  9669:          }
                   9670:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   9671:            fprintf(ficgp,",");
                   9672:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   9673:            fprintf(ficgp,",");
                   9674:          i=i+ncovmodel;
                   9675:        } /* end k */
                   9676:       } /* end k2 */
1.276     brouard  9677:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   9678:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.337     brouard  9679:     } /* end resultline */
1.223     brouard  9680:   } /* end ng */
                   9681:   /* avoid: */
                   9682:   fflush(ficgp); 
1.126     brouard  9683: }  /* end gnuplot */
                   9684: 
                   9685: 
                   9686: /*************** Moving average **************/
1.219     brouard  9687: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  9688:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  9689:    
1.222     brouard  9690:    int i, cpt, cptcod;
                   9691:    int modcovmax =1;
                   9692:    int mobilavrange, mob;
                   9693:    int iage=0;
1.288     brouard  9694:    int firstA1=0, firstA2=0;
1.222     brouard  9695: 
1.266     brouard  9696:    double sum=0., sumr=0.;
1.222     brouard  9697:    double age;
1.266     brouard  9698:    double *sumnewp, *sumnewm, *sumnewmr;
                   9699:    double *agemingood, *agemaxgood; 
                   9700:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  9701:   
                   9702:   
1.278     brouard  9703:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   9704:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  9705: 
                   9706:    sumnewp = vector(1,ncovcombmax);
                   9707:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  9708:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  9709:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  9710:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  9711:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  9712:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  9713: 
                   9714:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  9715:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  9716:      sumnewp[cptcod]=0.;
1.266     brouard  9717:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   9718:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  9719:    }
                   9720:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   9721:   
1.266     brouard  9722:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   9723:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  9724:      else mobilavrange=mobilav;
                   9725:      for (age=bage; age<=fage; age++)
                   9726:        for (i=1; i<=nlstate;i++)
                   9727:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   9728:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9729:      /* We keep the original values on the extreme ages bage, fage and for 
                   9730:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   9731:        we use a 5 terms etc. until the borders are no more concerned. 
                   9732:      */ 
                   9733:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   9734:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  9735:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   9736:           sumnewm[cptcod]=0.;
                   9737:           for (i=1; i<=nlstate;i++){
1.222     brouard  9738:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   9739:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   9740:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   9741:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   9742:             }
                   9743:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  9744:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9745:           } /* end i */
                   9746:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   9747:         } /* end cptcod */
1.222     brouard  9748:        }/* end age */
                   9749:      }/* end mob */
1.266     brouard  9750:    }else{
                   9751:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  9752:      return -1;
1.266     brouard  9753:    }
                   9754: 
                   9755:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  9756:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   9757:      if(invalidvarcomb[cptcod]){
                   9758:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   9759:        continue;
                   9760:      }
1.219     brouard  9761: 
1.266     brouard  9762:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   9763:        sumnewm[cptcod]=0.;
                   9764:        sumnewmr[cptcod]=0.;
                   9765:        for (i=1; i<=nlstate;i++){
                   9766:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9767:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9768:        }
                   9769:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9770:         agemingoodr[cptcod]=age;
                   9771:        }
                   9772:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9773:           agemingood[cptcod]=age;
                   9774:        }
                   9775:      } /* age */
                   9776:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  9777:        sumnewm[cptcod]=0.;
1.266     brouard  9778:        sumnewmr[cptcod]=0.;
1.222     brouard  9779:        for (i=1; i<=nlstate;i++){
                   9780:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9781:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9782:        }
                   9783:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9784:         agemaxgoodr[cptcod]=age;
1.222     brouard  9785:        }
                   9786:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  9787:         agemaxgood[cptcod]=age;
                   9788:        }
                   9789:      } /* age */
                   9790:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   9791:      /* but they will change */
1.288     brouard  9792:      firstA1=0;firstA2=0;
1.266     brouard  9793:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   9794:        sumnewm[cptcod]=0.;
                   9795:        sumnewmr[cptcod]=0.;
                   9796:        for (i=1; i<=nlstate;i++){
                   9797:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9798:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9799:        }
                   9800:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9801:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9802:           agemaxgoodr[cptcod]=age;  /* age min */
                   9803:           for (i=1; i<=nlstate;i++)
                   9804:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9805:         }else{ /* bad we change the value with the values of good ages */
                   9806:           for (i=1; i<=nlstate;i++){
                   9807:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   9808:           } /* i */
                   9809:         } /* end bad */
                   9810:        }else{
                   9811:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9812:           agemaxgood[cptcod]=age;
                   9813:         }else{ /* bad we change the value with the values of good ages */
                   9814:           for (i=1; i<=nlstate;i++){
                   9815:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   9816:           } /* i */
                   9817:         } /* end bad */
                   9818:        }/* end else */
                   9819:        sum=0.;sumr=0.;
                   9820:        for (i=1; i<=nlstate;i++){
                   9821:         sum+=mobaverage[(int)age][i][cptcod];
                   9822:         sumr+=probs[(int)age][i][cptcod];
                   9823:        }
                   9824:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  9825:         if(!firstA1){
                   9826:           firstA1=1;
                   9827:           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);
                   9828:         }
                   9829:         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  9830:        } /* end bad */
                   9831:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9832:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  9833:         if(!firstA2){
                   9834:           firstA2=1;
                   9835:           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);
                   9836:         }
                   9837:         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  9838:        } /* end bad */
                   9839:      }/* age */
1.266     brouard  9840: 
                   9841:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  9842:        sumnewm[cptcod]=0.;
1.266     brouard  9843:        sumnewmr[cptcod]=0.;
1.222     brouard  9844:        for (i=1; i<=nlstate;i++){
                   9845:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9846:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9847:        } 
                   9848:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9849:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   9850:           agemingoodr[cptcod]=age;
                   9851:           for (i=1; i<=nlstate;i++)
                   9852:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9853:         }else{ /* bad we change the value with the values of good ages */
                   9854:           for (i=1; i<=nlstate;i++){
                   9855:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   9856:           } /* i */
                   9857:         } /* end bad */
                   9858:        }else{
                   9859:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9860:           agemingood[cptcod]=age;
                   9861:         }else{ /* bad */
                   9862:           for (i=1; i<=nlstate;i++){
                   9863:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   9864:           } /* i */
                   9865:         } /* end bad */
                   9866:        }/* end else */
                   9867:        sum=0.;sumr=0.;
                   9868:        for (i=1; i<=nlstate;i++){
                   9869:         sum+=mobaverage[(int)age][i][cptcod];
                   9870:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  9871:        }
1.266     brouard  9872:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  9873:         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  9874:        } /* end bad */
                   9875:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9876:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  9877:         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  9878:        } /* end bad */
                   9879:      }/* age */
1.266     brouard  9880: 
1.222     brouard  9881:                
                   9882:      for (age=bage; age<=fage; age++){
1.235     brouard  9883:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  9884:        sumnewp[cptcod]=0.;
                   9885:        sumnewm[cptcod]=0.;
                   9886:        for (i=1; i<=nlstate;i++){
                   9887:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   9888:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9889:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   9890:        }
                   9891:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   9892:      }
                   9893:      /* printf("\n"); */
                   9894:      /* } */
1.266     brouard  9895: 
1.222     brouard  9896:      /* brutal averaging */
1.266     brouard  9897:      /* for (i=1; i<=nlstate;i++){ */
                   9898:      /*   for (age=1; age<=bage; age++){ */
                   9899:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   9900:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9901:      /*   }     */
                   9902:      /*   for (age=fage; age<=AGESUP; age++){ */
                   9903:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   9904:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9905:      /*   } */
                   9906:      /* } /\* end i status *\/ */
                   9907:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   9908:      /*   for (age=1; age<=AGESUP; age++){ */
                   9909:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   9910:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   9911:      /*   } */
                   9912:      /* } */
1.222     brouard  9913:    }/* end cptcod */
1.266     brouard  9914:    free_vector(agemaxgoodr,1, ncovcombmax);
                   9915:    free_vector(agemaxgood,1, ncovcombmax);
                   9916:    free_vector(agemingood,1, ncovcombmax);
                   9917:    free_vector(agemingoodr,1, ncovcombmax);
                   9918:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  9919:    free_vector(sumnewm,1, ncovcombmax);
                   9920:    free_vector(sumnewp,1, ncovcombmax);
                   9921:    return 0;
                   9922:  }/* End movingaverage */
1.218     brouard  9923:  
1.126     brouard  9924: 
1.296     brouard  9925:  
1.126     brouard  9926: /************** Forecasting ******************/
1.296     brouard  9927: /* 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)*/
                   9928: 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){
                   9929:   /* dateintemean, mean date of interviews
                   9930:      dateprojd, year, month, day of starting projection 
                   9931:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  9932:      agemin, agemax range of age
                   9933:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   9934:   */
1.296     brouard  9935:   /* double anprojd, mprojd, jprojd; */
                   9936:   /* double anprojf, mprojf, jprojf; */
1.267     brouard  9937:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  9938:   double agec; /* generic age */
1.296     brouard  9939:   double agelim, ppij, yp,yp1,yp2;
1.126     brouard  9940:   double *popeffectif,*popcount;
                   9941:   double ***p3mat;
1.218     brouard  9942:   /* double ***mobaverage; */
1.126     brouard  9943:   char fileresf[FILENAMELENGTH];
                   9944: 
                   9945:   agelim=AGESUP;
1.211     brouard  9946:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9947:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9948:      We still use firstpass and lastpass as another selection.
                   9949:   */
1.214     brouard  9950:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9951:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  9952:  
1.201     brouard  9953:   strcpy(fileresf,"F_"); 
                   9954:   strcat(fileresf,fileresu);
1.126     brouard  9955:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   9956:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   9957:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   9958:   }
1.235     brouard  9959:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   9960:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  9961: 
1.225     brouard  9962:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  9963: 
                   9964: 
                   9965:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9966:   if (stepm<=12) stepsize=1;
                   9967:   if(estepm < stepm){
                   9968:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9969:   }
1.270     brouard  9970:   else{
                   9971:     hstepm=estepm;   
                   9972:   }
                   9973:   if(estepm > stepm){ /* Yes every two year */
                   9974:     stepsize=2;
                   9975:   }
1.296     brouard  9976:   hstepm=hstepm/stepm;
1.126     brouard  9977: 
1.296     brouard  9978:   
                   9979:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9980:   /*                              fractional in yp1 *\/ */
                   9981:   /* aintmean=yp; */
                   9982:   /* yp2=modf((yp1*12),&yp); */
                   9983:   /* mintmean=yp; */
                   9984:   /* yp1=modf((yp2*30.5),&yp); */
                   9985:   /* jintmean=yp; */
                   9986:   /* if(jintmean==0) jintmean=1; */
                   9987:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  9988: 
1.296     brouard  9989: 
                   9990:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   9991:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   9992:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.351     brouard  9993:   /* i1=pow(2,cptcoveff); */
                   9994:   /* if (cptcovn < 1){i1=1;} */
1.126     brouard  9995:   
1.296     brouard  9996:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  9997:   
                   9998:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  9999:   
1.126     brouard  10000: /*           if (h==(int)(YEARM*yearp)){ */
1.351     brouard  10001:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10002:     k=TKresult[nres];
                   10003:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   10004:     /*  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) *\/ */
                   10005:     /* if(i1 != 1 && TKresult[nres]!= k) */
                   10006:     /*   continue; */
                   10007:     /* if(invalidvarcomb[k]){ */
                   10008:     /*   printf("\nCombination (%d) projection ignored because no cases \n",k);  */
                   10009:     /*   continue; */
                   10010:     /* } */
1.227     brouard  10011:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
1.351     brouard  10012:     for(j=1;j<=cptcovs;j++){
                   10013:       /* for(j=1;j<=cptcoveff;j++) { */
                   10014:     /*   /\* fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); *\/ */
                   10015:     /*   fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10016:     /* } */
                   10017:     /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10018:     /*   fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   10019:     /* } */
                   10020:       fprintf(ficresf," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.235     brouard  10021:     }
1.351     brouard  10022:  
1.227     brouard  10023:     fprintf(ficresf," yearproj age");
                   10024:     for(j=1; j<=nlstate+ndeath;j++){ 
                   10025:       for(i=1; i<=nlstate;i++)               
                   10026:        fprintf(ficresf," p%d%d",i,j);
                   10027:       fprintf(ficresf," wp.%d",j);
                   10028:     }
1.296     brouard  10029:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  10030:       fprintf(ficresf,"\n");
1.296     brouard  10031:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  10032:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   10033:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  10034:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   10035:        nhstepm = nhstepm/hstepm; 
                   10036:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10037:        oldm=oldms;savm=savms;
1.268     brouard  10038:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  10039:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  10040:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  10041:        for (h=0; h<=nhstepm; h++){
                   10042:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  10043:            break;
                   10044:          }
                   10045:        }
                   10046:        fprintf(ficresf,"\n");
1.351     brouard  10047:        /* for(j=1;j<=cptcoveff;j++)  */
                   10048:        for(j=1;j<=cptcovs;j++) 
                   10049:          fprintf(ficresf,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.332     brouard  10050:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Tvaraff not correct *\/ */
1.351     brouard  10051:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* TnsdVar[Tvaraff]  correct *\/ */
1.296     brouard  10052:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  10053:        
                   10054:        for(j=1; j<=nlstate+ndeath;j++) {
                   10055:          ppij=0.;
                   10056:          for(i=1; i<=nlstate;i++) {
1.278     brouard  10057:            if (mobilav>=1)
                   10058:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   10059:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   10060:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   10061:            }
1.268     brouard  10062:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   10063:          } /* end i */
                   10064:          fprintf(ficresf," %.3f", ppij);
                   10065:        }/* end j */
1.227     brouard  10066:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10067:       } /* end agec */
1.266     brouard  10068:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   10069:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  10070:     } /* end yearp */
                   10071:   } /* end  k */
1.219     brouard  10072:        
1.126     brouard  10073:   fclose(ficresf);
1.215     brouard  10074:   printf("End of Computing forecasting \n");
                   10075:   fprintf(ficlog,"End of Computing forecasting\n");
                   10076: 
1.126     brouard  10077: }
                   10078: 
1.269     brouard  10079: /************** Back Forecasting ******************/
1.296     brouard  10080:  /* 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){ */
                   10081:  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){
                   10082:   /* back1, year, month, day of starting backprojection
1.267     brouard  10083:      agemin, agemax range of age
                   10084:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  10085:      anback2 year of end of backprojection (same day and month as back1).
                   10086:      prevacurrent and prev are prevalences.
1.267     brouard  10087:   */
                   10088:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   10089:   double agec; /* generic age */
1.302     brouard  10090:   double agelim, ppij, ppi, yp,yp1,yp2; /* ,jintmean,mintmean,aintmean;*/
1.267     brouard  10091:   double *popeffectif,*popcount;
                   10092:   double ***p3mat;
                   10093:   /* double ***mobaverage; */
                   10094:   char fileresfb[FILENAMELENGTH];
                   10095:  
1.268     brouard  10096:   agelim=AGEINF;
1.267     brouard  10097:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   10098:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   10099:      We still use firstpass and lastpass as another selection.
                   10100:   */
                   10101:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   10102:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   10103: 
                   10104:   /*Do we need to compute prevalence again?*/
                   10105: 
                   10106:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   10107:   
                   10108:   strcpy(fileresfb,"FB_");
                   10109:   strcat(fileresfb,fileresu);
                   10110:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   10111:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   10112:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   10113:   }
                   10114:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   10115:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   10116:   
                   10117:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   10118:   
                   10119:    
                   10120:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   10121:   if (stepm<=12) stepsize=1;
                   10122:   if(estepm < stepm){
                   10123:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   10124:   }
1.270     brouard  10125:   else{
                   10126:     hstepm=estepm;   
                   10127:   }
                   10128:   if(estepm >= stepm){ /* Yes every two year */
                   10129:     stepsize=2;
                   10130:   }
1.267     brouard  10131:   
                   10132:   hstepm=hstepm/stepm;
1.296     brouard  10133:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   10134:   /*                              fractional in yp1 *\/ */
                   10135:   /* aintmean=yp; */
                   10136:   /* yp2=modf((yp1*12),&yp); */
                   10137:   /* mintmean=yp; */
                   10138:   /* yp1=modf((yp2*30.5),&yp); */
                   10139:   /* jintmean=yp; */
                   10140:   /* if(jintmean==0) jintmean=1; */
                   10141:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  10142:   
1.351     brouard  10143:   /* i1=pow(2,cptcoveff); */
                   10144:   /* if (cptcovn < 1){i1=1;} */
1.267     brouard  10145:   
1.296     brouard  10146:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   10147:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  10148:   
                   10149:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   10150:   
1.351     brouard  10151:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10152:     k=TKresult[nres];
                   10153:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   10154:   /* for(k=1; k<=i1;k++){ */
                   10155:   /*   if(i1 != 1 && TKresult[nres]!= k) */
                   10156:   /*     continue; */
                   10157:   /*   if(invalidvarcomb[k]){ */
                   10158:   /*     printf("\nCombination (%d) projection ignored because no cases \n",k);  */
                   10159:   /*     continue; */
                   10160:   /*   } */
1.268     brouard  10161:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.351     brouard  10162:     for(j=1;j<=cptcovs;j++){
                   10163:     /* for(j=1;j<=cptcoveff;j++) { */
                   10164:     /*   fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10165:     /* } */
                   10166:       fprintf(ficresfb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.267     brouard  10167:     }
1.351     brouard  10168:    /*  fprintf(ficrespij,"******\n"); */
                   10169:    /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10170:    /*    fprintf(ficresfb," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   10171:    /*  } */
1.267     brouard  10172:     fprintf(ficresfb," yearbproj age");
                   10173:     for(j=1; j<=nlstate+ndeath;j++){
                   10174:       for(i=1; i<=nlstate;i++)
1.268     brouard  10175:        fprintf(ficresfb," b%d%d",i,j);
                   10176:       fprintf(ficresfb," b.%d",j);
1.267     brouard  10177:     }
1.296     brouard  10178:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  10179:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   10180:       fprintf(ficresfb,"\n");
1.296     brouard  10181:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  10182:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  10183:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   10184:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  10185:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  10186:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  10187:        nhstepm = nhstepm/hstepm;
                   10188:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10189:        oldm=oldms;savm=savms;
1.268     brouard  10190:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  10191:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  10192:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  10193:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   10194:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   10195:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  10196:        for (h=0; h<=nhstepm; h++){
1.268     brouard  10197:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   10198:            break;
                   10199:          }
                   10200:        }
                   10201:        fprintf(ficresfb,"\n");
1.351     brouard  10202:        /* for(j=1;j<=cptcoveff;j++) */
                   10203:        for(j=1;j<=cptcovs;j++)
                   10204:          fprintf(ficresfb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   10205:          /* fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.296     brouard  10206:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  10207:        for(i=1; i<=nlstate+ndeath;i++) {
                   10208:          ppij=0.;ppi=0.;
                   10209:          for(j=1; j<=nlstate;j++) {
                   10210:            /* if (mobilav==1) */
1.269     brouard  10211:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   10212:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   10213:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   10214:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  10215:              /* else { */
                   10216:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   10217:              /* } */
1.268     brouard  10218:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   10219:          } /* end j */
                   10220:          if(ppi <0.99){
                   10221:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   10222:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   10223:          }
                   10224:          fprintf(ficresfb," %.3f", ppij);
                   10225:        }/* end j */
1.267     brouard  10226:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10227:       } /* end agec */
                   10228:     } /* end yearp */
                   10229:   } /* end k */
1.217     brouard  10230:   
1.267     brouard  10231:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  10232:   
1.267     brouard  10233:   fclose(ficresfb);
                   10234:   printf("End of Computing Back forecasting \n");
                   10235:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  10236:        
1.267     brouard  10237: }
1.217     brouard  10238: 
1.269     brouard  10239: /* Variance of prevalence limit: varprlim */
                   10240:  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  10241:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  10242:  
                   10243:    char fileresvpl[FILENAMELENGTH];  
                   10244:    FILE *ficresvpl;
                   10245:    double **oldm, **savm;
                   10246:    double **varpl; /* Variances of prevalence limits by age */   
                   10247:    int i1, k, nres, j ;
                   10248:    
                   10249:     strcpy(fileresvpl,"VPL_");
                   10250:     strcat(fileresvpl,fileresu);
                   10251:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  10252:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  10253:       exit(0);
                   10254:     }
1.288     brouard  10255:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   10256:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  10257:     
                   10258:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   10259:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   10260:     
                   10261:     i1=pow(2,cptcoveff);
                   10262:     if (cptcovn < 1){i1=1;}
                   10263: 
1.337     brouard  10264:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10265:        k=TKresult[nres];
1.338     brouard  10266:        if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  10267:      /* for(k=1; k<=i1;k++){ /\* We find the combination equivalent to result line values of dummies *\/ */
1.269     brouard  10268:       if(i1 != 1 && TKresult[nres]!= k)
                   10269:        continue;
                   10270:       fprintf(ficresvpl,"\n#****** ");
                   10271:       printf("\n#****** ");
                   10272:       fprintf(ficlog,"\n#****** ");
1.337     brouard  10273:       for(j=1;j<=cptcovs;j++) {
                   10274:        fprintf(ficresvpl,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   10275:        fprintf(ficlog,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   10276:        printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   10277:        /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10278:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.269     brouard  10279:       }
1.337     brouard  10280:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   10281:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10282:       /*       fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10283:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10284:       /* }      */
1.269     brouard  10285:       fprintf(ficresvpl,"******\n");
                   10286:       printf("******\n");
                   10287:       fprintf(ficlog,"******\n");
                   10288:       
                   10289:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   10290:       oldm=oldms;savm=savms;
                   10291:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   10292:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   10293:       /*}*/
                   10294:     }
                   10295:     
                   10296:     fclose(ficresvpl);
1.288     brouard  10297:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   10298:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  10299: 
                   10300:  }
                   10301: /* Variance of back prevalence: varbprlim */
                   10302:  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){
                   10303:       /*------- Variance of back (stable) prevalence------*/
                   10304: 
                   10305:    char fileresvbl[FILENAMELENGTH];  
                   10306:    FILE  *ficresvbl;
                   10307: 
                   10308:    double **oldm, **savm;
                   10309:    double **varbpl; /* Variances of back prevalence limits by age */   
                   10310:    int i1, k, nres, j ;
                   10311: 
                   10312:    strcpy(fileresvbl,"VBL_");
                   10313:    strcat(fileresvbl,fileresu);
                   10314:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   10315:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   10316:      exit(0);
                   10317:    }
                   10318:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   10319:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   10320:    
                   10321:    
                   10322:    i1=pow(2,cptcoveff);
                   10323:    if (cptcovn < 1){i1=1;}
                   10324:    
1.337     brouard  10325:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10326:      k=TKresult[nres];
1.338     brouard  10327:      if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  10328:     /* for(k=1; k<=i1;k++){ */
                   10329:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   10330:     /*          continue; */
1.269     brouard  10331:        fprintf(ficresvbl,"\n#****** ");
                   10332:        printf("\n#****** ");
                   10333:        fprintf(ficlog,"\n#****** ");
1.337     brouard  10334:        for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */
1.338     brouard  10335:         printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   10336:         fprintf(ficresvbl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   10337:         fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
1.337     brouard  10338:        /* for(j=1;j<=cptcoveff;j++) { */
                   10339:        /*       fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10340:        /*       fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10341:        /*       printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10342:        /* } */
                   10343:        /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   10344:        /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10345:        /*       fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10346:        /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
1.269     brouard  10347:        }
                   10348:        fprintf(ficresvbl,"******\n");
                   10349:        printf("******\n");
                   10350:        fprintf(ficlog,"******\n");
                   10351:        
                   10352:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   10353:        oldm=oldms;savm=savms;
                   10354:        
                   10355:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   10356:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   10357:        /*}*/
                   10358:      }
                   10359:    
                   10360:    fclose(ficresvbl);
                   10361:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   10362:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   10363: 
                   10364:  } /* End of varbprlim */
                   10365: 
1.126     brouard  10366: /************** Forecasting *****not tested NB*************/
1.227     brouard  10367: /* 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  10368:   
1.227     brouard  10369: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   10370: /*   int *popage; */
                   10371: /*   double calagedatem, agelim, kk1, kk2; */
                   10372: /*   double *popeffectif,*popcount; */
                   10373: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   10374: /*   /\* double ***mobaverage; *\/ */
                   10375: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  10376: 
1.227     brouard  10377: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10378: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10379: /*   agelim=AGESUP; */
                   10380: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  10381:   
1.227     brouard  10382: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  10383:   
                   10384:   
1.227     brouard  10385: /*   strcpy(filerespop,"POP_");  */
                   10386: /*   strcat(filerespop,fileresu); */
                   10387: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   10388: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   10389: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   10390: /*   } */
                   10391: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   10392: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  10393: 
1.227     brouard  10394: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  10395: 
1.227     brouard  10396: /*   /\* if (mobilav!=0) { *\/ */
                   10397: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   10398: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   10399: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   10400: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   10401: /*   /\*   } *\/ */
                   10402: /*   /\* } *\/ */
1.126     brouard  10403: 
1.227     brouard  10404: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   10405: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  10406:   
1.227     brouard  10407: /*   agelim=AGESUP; */
1.126     brouard  10408:   
1.227     brouard  10409: /*   hstepm=1; */
                   10410: /*   hstepm=hstepm/stepm;  */
1.218     brouard  10411:        
1.227     brouard  10412: /*   if (popforecast==1) { */
                   10413: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   10414: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   10415: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   10416: /*     }  */
                   10417: /*     popage=ivector(0,AGESUP); */
                   10418: /*     popeffectif=vector(0,AGESUP); */
                   10419: /*     popcount=vector(0,AGESUP); */
1.126     brouard  10420:     
1.227     brouard  10421: /*     i=1;    */
                   10422: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  10423:     
1.227     brouard  10424: /*     imx=i; */
                   10425: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   10426: /*   } */
1.218     brouard  10427:   
1.227     brouard  10428: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   10429: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   10430: /*       k=k+1; */
                   10431: /*       fprintf(ficrespop,"\n#******"); */
                   10432: /*       for(j=1;j<=cptcoveff;j++) { */
                   10433: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   10434: /*       } */
                   10435: /*       fprintf(ficrespop,"******\n"); */
                   10436: /*       fprintf(ficrespop,"# Age"); */
                   10437: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   10438: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  10439:       
1.227     brouard  10440: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   10441: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  10442:        
1.227     brouard  10443: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   10444: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   10445: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  10446:          
1.227     brouard  10447: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10448: /*       oldm=oldms;savm=savms; */
                   10449: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  10450:          
1.227     brouard  10451: /*       for (h=0; h<=nhstepm; h++){ */
                   10452: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   10453: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   10454: /*         }  */
                   10455: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   10456: /*           kk1=0.;kk2=0; */
                   10457: /*           for(i=1; i<=nlstate;i++) {               */
                   10458: /*             if (mobilav==1)  */
                   10459: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   10460: /*             else { */
                   10461: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   10462: /*             } */
                   10463: /*           } */
                   10464: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   10465: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   10466: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   10467: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   10468: /*           } */
                   10469: /*         } */
                   10470: /*         for(i=1; i<=nlstate;i++){ */
                   10471: /*           kk1=0.; */
                   10472: /*           for(j=1; j<=nlstate;j++){ */
                   10473: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   10474: /*           } */
                   10475: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   10476: /*         } */
1.218     brouard  10477:            
1.227     brouard  10478: /*         if (h==(int)(calagedatem+12*cpt)) */
                   10479: /*           for(j=1; j<=nlstate;j++)  */
                   10480: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   10481: /*       } */
                   10482: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10483: /*     } */
                   10484: /*       } */
1.218     brouard  10485:       
1.227     brouard  10486: /*       /\******\/ */
1.218     brouard  10487:       
1.227     brouard  10488: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   10489: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   10490: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   10491: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   10492: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  10493:          
1.227     brouard  10494: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10495: /*       oldm=oldms;savm=savms; */
                   10496: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   10497: /*       for (h=0; h<=nhstepm; h++){ */
                   10498: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   10499: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   10500: /*         }  */
                   10501: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   10502: /*           kk1=0.;kk2=0; */
                   10503: /*           for(i=1; i<=nlstate;i++) {               */
                   10504: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   10505: /*           } */
                   10506: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   10507: /*         } */
                   10508: /*       } */
                   10509: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10510: /*     } */
                   10511: /*       } */
                   10512: /*     }  */
                   10513: /*   } */
1.218     brouard  10514:   
1.227     brouard  10515: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  10516:   
1.227     brouard  10517: /*   if (popforecast==1) { */
                   10518: /*     free_ivector(popage,0,AGESUP); */
                   10519: /*     free_vector(popeffectif,0,AGESUP); */
                   10520: /*     free_vector(popcount,0,AGESUP); */
                   10521: /*   } */
                   10522: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10523: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10524: /*   fclose(ficrespop); */
                   10525: /* } /\* End of popforecast *\/ */
1.218     brouard  10526:  
1.126     brouard  10527: int fileappend(FILE *fichier, char *optionfich)
                   10528: {
                   10529:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   10530:     printf("Problem with file: %s\n", optionfich);
                   10531:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   10532:     return (0);
                   10533:   }
                   10534:   fflush(fichier);
                   10535:   return (1);
                   10536: }
                   10537: 
                   10538: 
                   10539: /**************** function prwizard **********************/
                   10540: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   10541: {
                   10542: 
                   10543:   /* Wizard to print covariance matrix template */
                   10544: 
1.164     brouard  10545:   char ca[32], cb[32];
                   10546:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  10547:   int numlinepar;
                   10548: 
                   10549:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10550:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10551:   for(i=1; i <=nlstate; i++){
                   10552:     jj=0;
                   10553:     for(j=1; j <=nlstate+ndeath; j++){
                   10554:       if(j==i) continue;
                   10555:       jj++;
                   10556:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   10557:       printf("%1d%1d",i,j);
                   10558:       fprintf(ficparo,"%1d%1d",i,j);
                   10559:       for(k=1; k<=ncovmodel;k++){
                   10560:        /*        printf(" %lf",param[i][j][k]); */
                   10561:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   10562:        printf(" 0.");
                   10563:        fprintf(ficparo," 0.");
                   10564:       }
                   10565:       printf("\n");
                   10566:       fprintf(ficparo,"\n");
                   10567:     }
                   10568:   }
                   10569:   printf("# Scales (for hessian or gradient estimation)\n");
                   10570:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   10571:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   10572:   for(i=1; i <=nlstate; i++){
                   10573:     jj=0;
                   10574:     for(j=1; j <=nlstate+ndeath; j++){
                   10575:       if(j==i) continue;
                   10576:       jj++;
                   10577:       fprintf(ficparo,"%1d%1d",i,j);
                   10578:       printf("%1d%1d",i,j);
                   10579:       fflush(stdout);
                   10580:       for(k=1; k<=ncovmodel;k++){
                   10581:        /*      printf(" %le",delti3[i][j][k]); */
                   10582:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   10583:        printf(" 0.");
                   10584:        fprintf(ficparo," 0.");
                   10585:       }
                   10586:       numlinepar++;
                   10587:       printf("\n");
                   10588:       fprintf(ficparo,"\n");
                   10589:     }
                   10590:   }
                   10591:   printf("# Covariance matrix\n");
                   10592: /* # 121 Var(a12)\n\ */
                   10593: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10594: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   10595: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   10596: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   10597: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   10598: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   10599: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   10600:   fflush(stdout);
                   10601:   fprintf(ficparo,"# Covariance matrix\n");
                   10602:   /* # 121 Var(a12)\n\ */
                   10603:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10604:   /* #   ...\n\ */
                   10605:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   10606:   
                   10607:   for(itimes=1;itimes<=2;itimes++){
                   10608:     jj=0;
                   10609:     for(i=1; i <=nlstate; i++){
                   10610:       for(j=1; j <=nlstate+ndeath; j++){
                   10611:        if(j==i) continue;
                   10612:        for(k=1; k<=ncovmodel;k++){
                   10613:          jj++;
                   10614:          ca[0]= k+'a'-1;ca[1]='\0';
                   10615:          if(itimes==1){
                   10616:            printf("#%1d%1d%d",i,j,k);
                   10617:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   10618:          }else{
                   10619:            printf("%1d%1d%d",i,j,k);
                   10620:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   10621:            /*  printf(" %.5le",matcov[i][j]); */
                   10622:          }
                   10623:          ll=0;
                   10624:          for(li=1;li <=nlstate; li++){
                   10625:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   10626:              if(lj==li) continue;
                   10627:              for(lk=1;lk<=ncovmodel;lk++){
                   10628:                ll++;
                   10629:                if(ll<=jj){
                   10630:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   10631:                  if(ll<jj){
                   10632:                    if(itimes==1){
                   10633:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10634:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10635:                    }else{
                   10636:                      printf(" 0.");
                   10637:                      fprintf(ficparo," 0.");
                   10638:                    }
                   10639:                  }else{
                   10640:                    if(itimes==1){
                   10641:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   10642:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   10643:                    }else{
                   10644:                      printf(" 0.");
                   10645:                      fprintf(ficparo," 0.");
                   10646:                    }
                   10647:                  }
                   10648:                }
                   10649:              } /* end lk */
                   10650:            } /* end lj */
                   10651:          } /* end li */
                   10652:          printf("\n");
                   10653:          fprintf(ficparo,"\n");
                   10654:          numlinepar++;
                   10655:        } /* end k*/
                   10656:       } /*end j */
                   10657:     } /* end i */
                   10658:   } /* end itimes */
                   10659: 
                   10660: } /* end of prwizard */
                   10661: /******************* Gompertz Likelihood ******************************/
                   10662: double gompertz(double x[])
                   10663: { 
1.302     brouard  10664:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
1.126     brouard  10665:   int i,n=0; /* n is the size of the sample */
                   10666: 
1.220     brouard  10667:   for (i=1;i<=imx ; i++) {
1.126     brouard  10668:     sump=sump+weight[i];
                   10669:     /*    sump=sump+1;*/
                   10670:     num=num+1;
                   10671:   }
1.302     brouard  10672:   L=0.0;
                   10673:   /* agegomp=AGEGOMP; */
1.126     brouard  10674:   /* for (i=0; i<=imx; i++) 
                   10675:      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]);*/
                   10676: 
1.302     brouard  10677:   for (i=1;i<=imx ; i++) {
                   10678:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   10679:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   10680:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   10681:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   10682:      * +
                   10683:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   10684:      */
                   10685:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   10686:        if (cens[i] == 1){
                   10687:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   10688:        } else if (cens[i] == 0){
1.126     brouard  10689:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
1.302     brouard  10690:          +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   10691:       } else
                   10692:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
1.126     brouard  10693:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
1.302     brouard  10694:        L=L+A*weight[i];
1.126     brouard  10695:        /*      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  10696:      }
                   10697:   }
1.126     brouard  10698: 
1.302     brouard  10699:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
1.126     brouard  10700:  
                   10701:   return -2*L*num/sump;
                   10702: }
                   10703: 
1.136     brouard  10704: #ifdef GSL
                   10705: /******************* Gompertz_f Likelihood ******************************/
                   10706: double gompertz_f(const gsl_vector *v, void *params)
                   10707: { 
1.302     brouard  10708:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
1.136     brouard  10709:   double *x= (double *) v->data;
                   10710:   int i,n=0; /* n is the size of the sample */
                   10711: 
                   10712:   for (i=0;i<=imx-1 ; i++) {
                   10713:     sump=sump+weight[i];
                   10714:     /*    sump=sump+1;*/
                   10715:     num=num+1;
                   10716:   }
                   10717:  
                   10718:  
                   10719:   /* for (i=0; i<=imx; i++) 
                   10720:      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]);*/
                   10721:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   10722:   for (i=1;i<=imx ; i++)
                   10723:     {
                   10724:       if (cens[i] == 1 && wav[i]>1)
                   10725:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   10726:       
                   10727:       if (cens[i] == 0 && wav[i]>1)
                   10728:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   10729:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   10730:       
                   10731:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   10732:       if (wav[i] > 1 ) { /* ??? */
                   10733:        LL=LL+A*weight[i];
                   10734:        /*      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]);*/
                   10735:       }
                   10736:     }
                   10737: 
                   10738:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   10739:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   10740:  
                   10741:   return -2*LL*num/sump;
                   10742: }
                   10743: #endif
                   10744: 
1.126     brouard  10745: /******************* Printing html file ***********/
1.201     brouard  10746: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  10747:                  int lastpass, int stepm, int weightopt, char model[],\
                   10748:                  int imx,  double p[],double **matcov,double agemortsup){
                   10749:   int i,k;
                   10750: 
                   10751:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   10752:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   10753:   for (i=1;i<=2;i++) 
                   10754:     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  10755:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  10756:   fprintf(fichtm,"</ul>");
                   10757: 
                   10758: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   10759: 
                   10760:  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>");
                   10761: 
                   10762:  for (k=agegomp;k<(agemortsup-2);k++) 
                   10763:    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]);
                   10764: 
                   10765:  
                   10766:   fflush(fichtm);
                   10767: }
                   10768: 
                   10769: /******************* Gnuplot file **************/
1.201     brouard  10770: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  10771: 
                   10772:   char dirfileres[132],optfileres[132];
1.164     brouard  10773: 
1.126     brouard  10774:   int ng;
                   10775: 
                   10776: 
                   10777:   /*#ifdef windows */
                   10778:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   10779:     /*#endif */
                   10780: 
                   10781: 
                   10782:   strcpy(dirfileres,optionfilefiname);
                   10783:   strcpy(optfileres,"vpl");
1.199     brouard  10784:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  10785:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  10786:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  10787:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  10788:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   10789: 
                   10790: } 
                   10791: 
1.136     brouard  10792: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   10793: {
1.126     brouard  10794: 
1.136     brouard  10795:   /*-------- data file ----------*/
                   10796:   FILE *fic;
                   10797:   char dummy[]="                         ";
1.240     brouard  10798:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  10799:   int lstra;
1.136     brouard  10800:   int linei, month, year,iout;
1.302     brouard  10801:   int noffset=0; /* This is the offset if BOM data file */
1.136     brouard  10802:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  10803:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  10804:   char *stratrunc;
1.223     brouard  10805: 
1.349     brouard  10806:   /* DummyV=ivector(-1,NCOVMAX); /\* 1 to 3 *\/ */
                   10807:   /* FixedV=ivector(-1,NCOVMAX); /\* 1 to 3 *\/ */
1.339     brouard  10808:   
                   10809:   ncovcolt=ncovcol+nqv+ntv+nqtv; /* total of covariates in the data, not in the model equation */
                   10810:   
1.136     brouard  10811:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  10812:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10813:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  10814:   }
1.126     brouard  10815: 
1.302     brouard  10816:     /* Is it a BOM UTF-8 Windows file? */
                   10817:   /* First data line */
                   10818:   linei=0;
                   10819:   while(fgets(line, MAXLINE, fic)) {
                   10820:     noffset=0;
                   10821:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   10822:     {
                   10823:       noffset=noffset+3;
                   10824:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   10825:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   10826:       fflush(ficlog); return 1;
                   10827:     }
                   10828:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   10829:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   10830:     {
                   10831:       noffset=noffset+2;
1.304     brouard  10832:       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);
                   10833:       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  10834:       fflush(ficlog); return 1;
                   10835:     }
                   10836:     else if( line[0] == 0 && line[1] == 0)
                   10837:     {
                   10838:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   10839:        noffset=noffset+4;
1.304     brouard  10840:        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);
                   10841:        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  10842:        fflush(ficlog); return 1;
                   10843:       }
                   10844:     } else{
                   10845:       ;/*printf(" Not a BOM file\n");*/
                   10846:     }
                   10847:         /* If line starts with a # it is a comment */
                   10848:     if (line[noffset] == '#') {
                   10849:       linei=linei+1;
                   10850:       break;
                   10851:     }else{
                   10852:       break;
                   10853:     }
                   10854:   }
                   10855:   fclose(fic);
                   10856:   if((fic=fopen(datafile,"r"))==NULL)    {
                   10857:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10858:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   10859:   }
                   10860:   /* Not a Bom file */
                   10861:   
1.136     brouard  10862:   i=1;
                   10863:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   10864:     linei=linei+1;
                   10865:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   10866:       if(line[j] == '\t')
                   10867:        line[j] = ' ';
                   10868:     }
                   10869:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   10870:       ;
                   10871:     };
                   10872:     line[j+1]=0;  /* Trims blanks at end of line */
                   10873:     if(line[0]=='#'){
                   10874:       fprintf(ficlog,"Comment line\n%s\n",line);
                   10875:       printf("Comment line\n%s\n",line);
                   10876:       continue;
                   10877:     }
                   10878:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  10879:     strcpy(line, linetmp);
1.223     brouard  10880:     
                   10881:     /* Loops on waves */
                   10882:     for (j=maxwav;j>=1;j--){
                   10883:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  10884:        cutv(stra, strb, line, ' '); 
                   10885:        if(strb[0]=='.') { /* Missing value */
                   10886:          lval=-1;
                   10887:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
1.341     brouard  10888:          cotvar[j][ncovcol+nqv+ntv+iv][i]=-1; /* For performance reasons */
1.238     brouard  10889:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   10890:            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);
                   10891:            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);
                   10892:            return 1;
                   10893:          }
                   10894:        }else{
                   10895:          errno=0;
                   10896:          /* what_kind_of_number(strb); */
                   10897:          dval=strtod(strb,&endptr); 
                   10898:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   10899:          /* if(strb != endptr && *endptr == '\0') */
                   10900:          /*    dval=dlval; */
                   10901:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10902:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10903:            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);
                   10904:            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);
                   10905:            return 1;
                   10906:          }
                   10907:          cotqvar[j][iv][i]=dval; 
1.341     brouard  10908:          cotvar[j][ncovcol+nqv+ntv+iv][i]=dval; /* because cotvar starts now at first ntv */ 
1.238     brouard  10909:        }
                   10910:        strcpy(line,stra);
1.223     brouard  10911:       }/* end loop ntqv */
1.225     brouard  10912:       
1.223     brouard  10913:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  10914:        cutv(stra, strb, line, ' '); 
                   10915:        if(strb[0]=='.') { /* Missing value */
                   10916:          lval=-1;
                   10917:        }else{
                   10918:          errno=0;
                   10919:          lval=strtol(strb,&endptr,10); 
                   10920:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   10921:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10922:            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);
                   10923:            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);
                   10924:            return 1;
                   10925:          }
                   10926:        }
                   10927:        if(lval <-1 || lval >1){
                   10928:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10929:  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  10930:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10931:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10932:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10933:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10934:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10935:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10936:  Exiting.\n",lval,linei, i,line,iv,j);
1.238     brouard  10937:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10938:  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  10939:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10940:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10941:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10942:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10943:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10944:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10945:  Exiting.\n",lval,linei, i,line,iv,j);fflush(ficlog);
1.238     brouard  10946:          return 1;
                   10947:        }
1.341     brouard  10948:        cotvar[j][ncovcol+nqv+iv][i]=(double)(lval);
1.238     brouard  10949:        strcpy(line,stra);
1.223     brouard  10950:       }/* end loop ntv */
1.225     brouard  10951:       
1.223     brouard  10952:       /* Statuses  at wave */
1.137     brouard  10953:       cutv(stra, strb, line, ' '); 
1.223     brouard  10954:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  10955:        lval=-1;
1.136     brouard  10956:       }else{
1.238     brouard  10957:        errno=0;
                   10958:        lval=strtol(strb,&endptr,10); 
                   10959:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
1.347     brouard  10960:        if( strb[0]=='\0' || (*endptr != '\0' )){
                   10961:          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);
                   10962:          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);
                   10963:          return 1;
                   10964:        }else if( lval==0 || lval > nlstate+ndeath){
1.348     brouard  10965:          printf("Error in data around '%s' at line number %d for individual %d, '%s'\n Should be a state at wave %d. A state should be 1 to %d and not %ld.\n Fix your data file '%s'!  Exiting.\n", strb, linei,i,line,j,nlstate+ndeath, lval, datafile);fflush(stdout);
                   10966:          fprintf(ficlog,"Error in data around '%s' at line number %d for individual %d, '%s'\n Should be a state at wave %d. A state should be 1 to %d and not %ld.\n Fix your data file '%s'!  Exiting.\n", strb, linei,i,line,j,nlstate+ndeath, lval, datafile); fflush(ficlog);
1.238     brouard  10967:          return 1;
                   10968:        }
1.136     brouard  10969:       }
1.225     brouard  10970:       
1.136     brouard  10971:       s[j][i]=lval;
1.225     brouard  10972:       
1.223     brouard  10973:       /* Date of Interview */
1.136     brouard  10974:       strcpy(line,stra);
                   10975:       cutv(stra, strb,line,' ');
1.169     brouard  10976:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10977:       }
1.169     brouard  10978:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  10979:        month=99;
                   10980:        year=9999;
1.136     brouard  10981:       }else{
1.225     brouard  10982:        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);
                   10983:        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);
                   10984:        return 1;
1.136     brouard  10985:       }
                   10986:       anint[j][i]= (double) year; 
1.302     brouard  10987:       mint[j][i]= (double)month;
                   10988:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   10989:       /*       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]); */
                   10990:       /*       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]); */
                   10991:       /* } */
1.136     brouard  10992:       strcpy(line,stra);
1.223     brouard  10993:     } /* End loop on waves */
1.225     brouard  10994:     
1.223     brouard  10995:     /* Date of death */
1.136     brouard  10996:     cutv(stra, strb,line,' '); 
1.169     brouard  10997:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10998:     }
1.169     brouard  10999:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  11000:       month=99;
                   11001:       year=9999;
                   11002:     }else{
1.141     brouard  11003:       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  11004:       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);
                   11005:       return 1;
1.136     brouard  11006:     }
                   11007:     andc[i]=(double) year; 
                   11008:     moisdc[i]=(double) month; 
                   11009:     strcpy(line,stra);
                   11010:     
1.223     brouard  11011:     /* Date of birth */
1.136     brouard  11012:     cutv(stra, strb,line,' '); 
1.169     brouard  11013:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  11014:     }
1.169     brouard  11015:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  11016:       month=99;
                   11017:       year=9999;
                   11018:     }else{
1.141     brouard  11019:       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);
                   11020:       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  11021:       return 1;
1.136     brouard  11022:     }
                   11023:     if (year==9999) {
1.141     brouard  11024:       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);
                   11025:       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  11026:       return 1;
                   11027:       
1.136     brouard  11028:     }
                   11029:     annais[i]=(double)(year);
1.302     brouard  11030:     moisnais[i]=(double)(month);
                   11031:     for (j=1;j<=maxwav;j++){
                   11032:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   11033:        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]);
                   11034:        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]);
                   11035:       }
                   11036:     }
                   11037: 
1.136     brouard  11038:     strcpy(line,stra);
1.225     brouard  11039:     
1.223     brouard  11040:     /* Sample weight */
1.136     brouard  11041:     cutv(stra, strb,line,' '); 
                   11042:     errno=0;
                   11043:     dval=strtod(strb,&endptr); 
                   11044:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  11045:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   11046:       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  11047:       fflush(ficlog);
                   11048:       return 1;
                   11049:     }
                   11050:     weight[i]=dval; 
                   11051:     strcpy(line,stra);
1.225     brouard  11052:     
1.223     brouard  11053:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   11054:       cutv(stra, strb, line, ' '); 
                   11055:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  11056:        lval=-1;
1.311     brouard  11057:        coqvar[iv][i]=NAN; 
                   11058:        covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  11059:       }else{
1.225     brouard  11060:        errno=0;
                   11061:        /* what_kind_of_number(strb); */
                   11062:        dval=strtod(strb,&endptr);
                   11063:        /* if(strb != endptr && *endptr == '\0') */
                   11064:        /*   dval=dlval; */
                   11065:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   11066:        if( strb[0]=='\0' || (*endptr != '\0')){
                   11067:          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);
                   11068:          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);
                   11069:          return 1;
                   11070:        }
                   11071:        coqvar[iv][i]=dval; 
1.226     brouard  11072:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  11073:       }
                   11074:       strcpy(line,stra);
                   11075:     }/* end loop nqv */
1.136     brouard  11076:     
1.223     brouard  11077:     /* Covariate values */
1.136     brouard  11078:     for (j=ncovcol;j>=1;j--){
                   11079:       cutv(stra, strb,line,' '); 
1.223     brouard  11080:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  11081:        lval=-1;
1.136     brouard  11082:       }else{
1.225     brouard  11083:        errno=0;
                   11084:        lval=strtol(strb,&endptr,10); 
                   11085:        if( strb[0]=='\0' || (*endptr != '\0')){
                   11086:          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);
                   11087:          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);
                   11088:          return 1;
                   11089:        }
1.136     brouard  11090:       }
                   11091:       if(lval <-1 || lval >1){
1.225     brouard  11092:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  11093:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   11094:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  11095:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   11096:  build V1=0 V2=0 for the reference value (1),\n                                \
                   11097:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  11098:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  11099:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  11100:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  11101:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  11102:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   11103:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  11104:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   11105:  build V1=0 V2=0 for the reference value (1),\n                                \
                   11106:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  11107:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  11108:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  11109:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  11110:        return 1;
1.136     brouard  11111:       }
                   11112:       covar[j][i]=(double)(lval);
                   11113:       strcpy(line,stra);
                   11114:     }  
                   11115:     lstra=strlen(stra);
1.225     brouard  11116:     
1.136     brouard  11117:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   11118:       stratrunc = &(stra[lstra-9]);
                   11119:       num[i]=atol(stratrunc);
                   11120:     }
                   11121:     else
                   11122:       num[i]=atol(stra);
                   11123:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   11124:       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;}*/
                   11125:     
                   11126:     i=i+1;
                   11127:   } /* End loop reading  data */
1.225     brouard  11128:   
1.136     brouard  11129:   *imax=i-1; /* Number of individuals */
                   11130:   fclose(fic);
1.225     brouard  11131:   
1.136     brouard  11132:   return (0);
1.164     brouard  11133:   /* endread: */
1.225     brouard  11134:   printf("Exiting readdata: ");
                   11135:   fclose(fic);
                   11136:   return (1);
1.223     brouard  11137: }
1.126     brouard  11138: 
1.234     brouard  11139: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  11140:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  11141:   while (*p2 == ' ')
1.234     brouard  11142:     p2++; 
                   11143:   /* while ((*p1++ = *p2++) !=0) */
                   11144:   /*   ; */
                   11145:   /* do */
                   11146:   /*   while (*p2 == ' ') */
                   11147:   /*     p2++; */
                   11148:   /* while (*p1++ == *p2++); */
                   11149:   *stri=p2; 
1.145     brouard  11150: }
                   11151: 
1.330     brouard  11152: int decoderesult( char resultline[], int nres)
1.230     brouard  11153: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   11154: {
1.235     brouard  11155:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  11156:   char resultsav[MAXLINE];
1.330     brouard  11157:   /* int resultmodel[MAXLINE]; */
1.334     brouard  11158:   /* int modelresult[MAXLINE]; */
1.230     brouard  11159:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   11160: 
1.234     brouard  11161:   removefirstspace(&resultline);
1.332     brouard  11162:   printf("decoderesult:%s\n",resultline);
1.230     brouard  11163: 
1.332     brouard  11164:   strcpy(resultsav,resultline);
1.342     brouard  11165:   /* printf("Decoderesult resultsav=\"%s\" resultline=\"%s\"\n", resultsav, resultline); */
1.230     brouard  11166:   if (strlen(resultsav) >1){
1.334     brouard  11167:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' in this resultline */
1.230     brouard  11168:   }
1.353     brouard  11169:   if(j == 0 && cptcovs== 0){ /* Resultline but no =  and no covariate in the model */
1.253     brouard  11170:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   11171:     return (0);
                   11172:   }
1.234     brouard  11173:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
1.353     brouard  11174:     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, 1+age+%s.\n",j, cptcovs, model);fflush(ficlog);
                   11175:     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, 1+age+%s.\n",j, cptcovs, model);fflush(stdout);
                   11176:     if(j==0)
                   11177:       return 1;
1.234     brouard  11178:   }
1.334     brouard  11179:   for(k=1; k<=j;k++){ /* Loop on any covariate of the RESULT LINE */
1.234     brouard  11180:     if(nbocc(resultsav,'=') >1){
1.318     brouard  11181:       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  11182:       /* 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  11183:       cutl(strc,strd,strb,'=');  /* strb:"V4=1" strc="1" strd="V4" */
1.332     brouard  11184:       /* If a blank, then strc="V4=" and strd='\0' */
                   11185:       if(strc[0]=='\0'){
                   11186:       printf("Error in resultline, probably a blank after the \"%s\", \"result:%s\", stra=\"%s\" resultsav=\"%s\"\n",strb,resultline, stra, resultsav);
                   11187:        fprintf(ficlog,"Error in resultline, probably a blank after the \"V%s=\", resultline=%s\n",strb,resultline);
                   11188:        return 1;
                   11189:       }
1.234     brouard  11190:     }else
                   11191:       cutl(strc,strd,resultsav,'=');
1.318     brouard  11192:     Tvalsel[k]=atof(strc); /* 1 */ /* Tvalsel of k is the float value of the kth covariate appearing in this result line */
1.234     brouard  11193:     
1.230     brouard  11194:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
1.318     brouard  11195:     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  11196:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   11197:     /* cptcovsel++;     */
                   11198:     if (nbocc(stra,'=') >0)
                   11199:       strcpy(resultsav,stra); /* and analyzes it */
                   11200:   }
1.235     brouard  11201:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  11202:   /* 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  11203:   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  11204:     if(Typevar[k1]==0){ /* Single covariate in model */
                   11205:       /* 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.234     brouard  11206:       match=0;
1.318     brouard  11207:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   11208:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  11209:          modelresult[nres][k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.318     brouard  11210:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
1.234     brouard  11211:          break;
                   11212:        }
                   11213:       }
                   11214:       if(match == 0){
1.338     brouard  11215:        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]);
                   11216:        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  11217:        return 1;
1.234     brouard  11218:       }
1.332     brouard  11219:     }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*/
                   11220:       /* We feed resultmodel[k1]=k2; */
                   11221:       match=0;
                   11222:       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 */
                   11223:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  11224:          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  11225:          resultmodel[nres][k1]=k2; /* Added here */
1.342     brouard  11226:          /* printf("Decoderesult first modelresult[k2=%d]=%d (k1) V%d*AGE\n",k2,k1,Tvar[k1]); */
1.332     brouard  11227:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   11228:          break;
                   11229:        }
                   11230:       }
                   11231:       if(match == 0){
1.338     brouard  11232:        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]);
                   11233:        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  11234:       return 1;
                   11235:       }
1.349     brouard  11236:     }else if(Typevar[k1]==2 || Typevar[k1]==3){ /* Product with or without age. We want to get the position in the resultline of the product in the model line*/
1.332     brouard  11237:       /* resultmodel[nres][of such a Vn * Vm product k1] is not unique, so can't exist, we feed Tvard[k1][1] and [2] */ 
                   11238:       match=0;
1.342     brouard  11239:       /* 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  11240:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   11241:        if(Tvardk[k1][1]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   11242:          /* modelresult[k2]=k1; */
1.342     brouard  11243:          /* printf("Decoderesult first Product modelresult[k2=%d]=%d (k1) V%d * \n",k2,k1,Tvarsel[k2]); */
1.332     brouard  11244:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   11245:        }
                   11246:       }
                   11247:       if(match == 0){
1.349     brouard  11248:        printf("Error in result line (Product without age first variable or double product with age): V%d is missing in result: %s according to model=1+age+%s\n",Tvardk[k1][1], resultline, model);
                   11249:        fprintf(ficlog,"Error in result line (Product without age first variable or double product with age): V%d is missing in result: %s according to model=1+age+%s\n",Tvardk[k1][1], resultline, model);
1.332     brouard  11250:        return 1;
                   11251:       }
                   11252:       match=0;
                   11253:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   11254:        if(Tvardk[k1][2]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   11255:          /* modelresult[k2]=k1;*/
1.342     brouard  11256:          /* printf("Decoderesult second Product modelresult[k2=%d]=%d (k1) * V%d \n ",k2,k1,Tvarsel[k2]); */
1.332     brouard  11257:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   11258:          break;
                   11259:        }
                   11260:       }
                   11261:       if(match == 0){
1.349     brouard  11262:        printf("Error in result line (Product without age second variable or double product with age): V%d is missing in result: %s according to model=1+age+%s\n",Tvardk[k1][2], resultline, model);
                   11263:        fprintf(ficlog,"Error in result line (Product without age second variable or double product with age): V%d is missing in result : %s according to model=1+age+%s\n",Tvardk[k1][2], resultline, model);
1.332     brouard  11264:        return 1;
                   11265:       }
                   11266:     }/* End of testing */
1.333     brouard  11267:   }/* End loop cptcovt */
1.235     brouard  11268:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  11269:   /* Feeds resultmodel[nres][k1]=k2 for single covariate (k1) in the model equation */
1.334     brouard  11270:   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)
                   11271:                           * Loop on resultline variables: result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  11272:     match=0;
1.318     brouard  11273:     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  11274:       if(Typevar[k1]==0){ /* Single only */
1.349     brouard  11275:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4  What if a product?  */
1.330     brouard  11276:          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  11277:          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  11278:          ++match;
                   11279:        }
                   11280:       }
                   11281:     }
                   11282:     if(match == 0){
1.338     brouard  11283:       printf("Error in result line: variable V%d is missing in model; result: %s, model=1+age+%s\n",Tvarsel[k2], resultline, model);
                   11284:       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  11285:       return 1;
1.234     brouard  11286:     }else if(match > 1){
1.338     brouard  11287:       printf("Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
                   11288:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
1.310     brouard  11289:       return 1;
1.234     brouard  11290:     }
                   11291:   }
1.334     brouard  11292:   /* cptcovres=j /\* Number of variables in the resultline is equal to cptcovs and thus useless *\/     */
1.234     brouard  11293:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  11294:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.330     brouard  11295:   /* nres=1st result line: V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   11296:   /* 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*/
                   11297:   /* nres=2nd result line: V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.235     brouard  11298:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   11299:   /*    1 0 0 0 */
                   11300:   /*    2 1 0 0 */
                   11301:   /*    3 0 1 0 */ 
1.330     brouard  11302:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 (nres=2)*/
1.235     brouard  11303:   /*    5 0 0 1 */
1.330     brouard  11304:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 (nres=1)*/
1.235     brouard  11305:   /*    7 0 1 1 */
                   11306:   /*    8 1 1 1 */
1.237     brouard  11307:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   11308:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   11309:   /* V5*age V5 known which value for nres?  */
                   11310:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.334     brouard  11311:   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.
                   11312:                                                   * loop on position k1 in the MODEL LINE */
1.331     brouard  11313:     /* k counting number of combination of single dummies in the equation model */
                   11314:     /* k4 counting single dummies in the equation model */
                   11315:     /* k4q counting single quantitatives in the equation model */
1.344     brouard  11316:     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  11317:        /* 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  11318:       /* 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  11319:       /* Value in the (current nres) resultline of the variable at the k1th position in the model equation resultmodel[nres][k1]= k3 */
1.332     brouard  11320:       /* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline                        */
                   11321:       /*      k3 is the position in the nres result line of the k1th variable of the model equation                                  */
                   11322:       /* Tvarsel[k3]: Name of the variable at the k3th position in the result line.                                                  */
                   11323:       /* Tvalsel[k3]: Value of the variable at the k3th position in the result line.                                                 */
                   11324:       /* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline                   */
1.334     brouard  11325:       /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline                     */
1.332     brouard  11326:       /* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line                                        */
1.330     brouard  11327:       /* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line                                                      */
1.332     brouard  11328:       k3= resultmodel[nres][k1]; /* From position k1 in model get position k3 in result line */
                   11329:       /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   11330:       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  11331:       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  11332:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][Name]=Value; stores the value into the name of the variable. */
1.332     brouard  11333:       /* Tinvresult[nres][4]=1 */
1.334     brouard  11334:       /* Tresult[nres][k4+1]=Tvalsel[k3];/\* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) *\/ */
                   11335:       Tresult[nres][k3]=Tvalsel[k3];/* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) */
                   11336:       /* Tvresult[nres][k4+1]=(int)Tvarsel[k3];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   11337:       Tvresult[nres][k3]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
1.237     brouard  11338:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.334     brouard  11339:       precov[nres][k1]=Tvalsel[k3]; /* Value from resultline of the variable at the k1 position in the model */
1.342     brouard  11340:       /* 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  11341:       k4++;;
1.331     brouard  11342:     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Quantitative and single */
1.330     brouard  11343:       /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 */
1.332     brouard  11344:       /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline                                 */
1.330     brouard  11345:       /* Tqinvresult[nres][Name of a quantitative variable]= value of the variable in the result line                                                      */
1.332     brouard  11346:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 5 =k3q */
                   11347:       k2q=(int)Tvarsel[k3q]; /*  Name of variable at k3q th position in the resultline */
                   11348:       /* Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  11349:       /* Tqresult[nres][k4q+1]=Tvalsel[k3q]; /\* Tqresult[nres][1]=25.1 *\/ */
                   11350:       /* Tvresult[nres][k4q+1]=(int)Tvarsel[k3q];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   11351:       /* Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /\* Tvqresult[nres][1]=5 *\/ */
                   11352:       Tqresult[nres][k3q]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   11353:       Tvresult[nres][k3q]=(int)Tvarsel[k3q];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   11354:       Tvqresult[nres][k3q]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
1.237     brouard  11355:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.330     brouard  11356:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.332     brouard  11357:       precov[nres][k1]=Tvalsel[k3q];
1.342     brouard  11358:       /* 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  11359:       k4q++;;
1.350     brouard  11360:     }else if( Dummy[k1]==2 ){ /* For dummy with age product "V2+V3+V4+V6+V7+V6*V2+V7*V2+V6*V3+V7*V3+V6*V4+V7*V4+age*V2+age*V3+age*V4+age*V6+age*V7+age*V6*V2+age*V6*V3+age*V7*V3+age*V6*V4+age*V7*V4\r"*/
                   11361:       /* Tvar[k1]; */ /* Age variable */ /* 17 age*V6*V2 ?*/
1.332     brouard  11362:       /* Wrong we want the value of variable name Tvar[k1] */
1.350     brouard  11363:       if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
                   11364:        precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
                   11365:       /* 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]]); */
                   11366:       }else{
                   11367:        k3= resultmodel[nres][k1]; /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   11368:        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)*/
                   11369:        TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][4]=1 */
                   11370:        precov[nres][k1]=Tvalsel[k3];
                   11371:       }
1.342     brouard  11372:       /* 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  11373:     }else if( Dummy[k1]==3 ){ /* For quant with age product */
1.350     brouard  11374:       if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
                   11375:        precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
                   11376:       /* 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]]); */
                   11377:       }else{
                   11378:        k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 25.1=k3q */
                   11379:        k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
                   11380:        TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* TinvDoQresult[nres][5]=25.1 */
                   11381:        precov[nres][k1]=Tvalsel[k3q];
                   11382:       }
1.342     brouard  11383:       /* 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.349     brouard  11384:     }else if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
1.332     brouard  11385:       precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
1.342     brouard  11386:       /* 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  11387:     }else{
1.332     brouard  11388:       printf("Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
                   11389:       fprintf(ficlog,"Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
1.235     brouard  11390:     }
                   11391:   }
1.234     brouard  11392:   
1.334     brouard  11393:   TKresult[nres]=++k; /* Number of combinations of dummies for the nresult and the model =Tvalsel[k3]*pow(2,k4) + 1*/
1.230     brouard  11394:   return (0);
                   11395: }
1.235     brouard  11396: 
1.230     brouard  11397: int decodemodel( char model[], int lastobs)
                   11398:  /**< This routine decodes the model and returns:
1.224     brouard  11399:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   11400:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   11401:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   11402:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   11403:        * - cptcovage number of covariates with age*products =2
                   11404:        * - cptcovs number of simple covariates
1.339     brouard  11405:        * ncovcolt=ncovcol+nqv+ntv+nqtv total of covariates in the data, not in the model equation
1.224     brouard  11406:        * - 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  11407:        *     which is a new column after the 9 (ncovcol+nqv+ntv+nqtv) variables. 
1.319     brouard  11408:        * - if k is a product Vn*Vm, covar[k][i] is filled with correct values for each individual
1.224     brouard  11409:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   11410:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   11411:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   11412:        */
1.319     brouard  11413: /* 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  11414: {
1.238     brouard  11415:   int i, j, k, ks, v;
1.349     brouard  11416:   int n,m;
                   11417:   int  j1, k1, k11, k12, k2, k3, k4;
                   11418:   char modelsav[300];
                   11419:   char stra[300], strb[300], strc[300], strd[300],stre[300],strf[300];
1.187     brouard  11420:   char *strpt;
1.349     brouard  11421:   int  **existcomb;
                   11422:   
                   11423:   existcomb=imatrix(1,NCOVMAX,1,NCOVMAX);
                   11424:   for(i=1;i<=NCOVMAX;i++)
                   11425:     for(j=1;j<=NCOVMAX;j++)
                   11426:       existcomb[i][j]=0;
                   11427:     
1.145     brouard  11428:   /*removespace(model);*/
1.136     brouard  11429:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.349     brouard  11430:     j=0, j1=0, k1=0, k12=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  11431:     if (strstr(model,"AGE") !=0){
1.192     brouard  11432:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   11433:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  11434:       return 1;
                   11435:     }
1.141     brouard  11436:     if (strstr(model,"v") !=0){
1.338     brouard  11437:       printf("Error. 'v' must be in upper case 'V' model=1+age+%s ",model);
                   11438:       fprintf(ficlog,"Error. 'v' must be in upper case model=1+age+%s ",model);fflush(ficlog);
1.141     brouard  11439:       return 1;
                   11440:     }
1.187     brouard  11441:     strcpy(modelsav,model); 
                   11442:     if ((strpt=strstr(model,"age*age")) !=0){
1.338     brouard  11443:       printf(" strpt=%s, model=1+age+%s\n",strpt, model);
1.187     brouard  11444:       if(strpt != model){
1.338     brouard  11445:        printf("Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  11446:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  11447:  corresponding column of parameters.\n",model);
1.338     brouard  11448:        fprintf(ficlog,"Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  11449:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  11450:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  11451:        return 1;
1.225     brouard  11452:       }
1.187     brouard  11453:       nagesqr=1;
                   11454:       if (strstr(model,"+age*age") !=0)
1.234     brouard  11455:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  11456:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  11457:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  11458:       else 
1.234     brouard  11459:        substrchaine(modelsav, model, "age*age");
1.187     brouard  11460:     }else
                   11461:       nagesqr=0;
1.349     brouard  11462:     if (strlen(modelsav) >1){ /* V2 +V3 +V4 +V6 +V7 +V6*V2 +V7*V2 +V6*V3 +V7*V3 +V6*V4 +V7*V4 +age*V2 +age*V3 +age*V4 +age*V6 +age*V7 +age*V6*V2 +V7*V2 +age*V6*V3 +age*V7*V3 +age*V6*V4 +age*V7*V4 */
1.187     brouard  11463:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   11464:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.351     brouard  11465:       cptcovs=0; /**<  Number of simple covariates V1 +V1*age +V3 +V3*V4 +age*age => V1 + V3 =4+1-3=2  Wrong */
1.187     brouard  11466:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  11467:                     * cst, age and age*age 
                   11468:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   11469:       /* including age products which are counted in cptcovage.
                   11470:        * but the covariates which are products must be treated 
                   11471:        * separately: ncovn=4- 2=2 (V1+V3). */
1.349     brouard  11472:       cptcovprod=0; /**< Number of products  V1*V2 +v3*age = 2 */
                   11473:       cptcovdageprod=0; /* Number of doouble products with age age*Vn*VM or Vn*age*Vm or Vn*Vm*age */
1.187     brouard  11474:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.349     brouard  11475:       cptcovprodage=0;
                   11476:       /* cptcovprodage=nboccstr(modelsav,"age");*/
1.225     brouard  11477:       
1.187     brouard  11478:       /*   Design
                   11479:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   11480:        *  <          ncovcol=8                >
                   11481:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   11482:        *   k=  1    2      3       4     5       6      7        8
                   11483:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
1.345     brouard  11484:        *  covar[k,i], are for fixed covariates, value of kth covariate if not including age for individual i:
1.224     brouard  11485:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   11486:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  11487:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   11488:        *  Tage[++cptcovage]=k
1.345     brouard  11489:        *       if products, new covar are created after ncovcol + nqv (quanti fixed) with k1
1.187     brouard  11490:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   11491:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   11492:        *  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
                   11493:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   11494:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   11495:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
1.345     brouard  11496:        *  <          ncovcol=8  8 fixed covariate. Additional starts at 9 (V5*V6) and 10(V7*V8)              >
1.187     brouard  11497:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   11498:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
1.345     brouard  11499:        *     Tvard[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   11500:        * p Tvar[1]@12={2,   1,     3,      3,   9,     10,     8,       8}
1.187     brouard  11501:        * p Tprod[1]@2={                         6, 5}
                   11502:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   11503:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   11504:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1.319     brouard  11505:        *How to reorganize? Tvars(orted)
1.187     brouard  11506:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   11507:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   11508:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   11509:        * Struct []
                   11510:        */
1.225     brouard  11511:       
1.187     brouard  11512:       /* This loop fills the array Tvar from the string 'model'.*/
                   11513:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   11514:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   11515:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   11516:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   11517:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   11518:       /*       k=1 Tvar[1]=2 (from V2) */
                   11519:       /*       k=5 Tvar[5] */
                   11520:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  11521:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  11522:       /*       } */
1.198     brouard  11523:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  11524:       /*
                   11525:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  11526:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   11527:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   11528:       }
1.187     brouard  11529:       cptcovage=0;
1.351     brouard  11530: 
                   11531:       /* First loop in order to calculate */
                   11532:       /* for age*VN*Vm
                   11533:        * Provides, Typevar[k], Tage[cptcovage], existcomb[n][m], FixedV[ncovcolt+k12]
                   11534:        * Tprod[k1]=k  Tposprod[k]=k1;    Tvard[k1][1] =m;
                   11535:       */
                   11536:       /* Needs  FixedV[Tvardk[k][1]] */
                   11537:       /* For others:
                   11538:        * Sets  Typevar[k];
                   11539:        * Tvar[k]=ncovcol+nqv+ntv+nqtv+k11;
                   11540:        *       Tposprod[k]=k11;
                   11541:        *       Tprod[k11]=k;
                   11542:        *       Tvardk[k][1] =m;
                   11543:        * Needs FixedV[Tvardk[k][1]] == 0
                   11544:       */
                   11545:       
1.319     brouard  11546:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model line */
                   11547:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' cutl from left to right
                   11548:                                         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" */
                   11549:        if (nbocc(modelsav,'+')==0)
                   11550:          strcpy(strb,modelsav); /* and analyzes it */
1.234     brouard  11551:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   11552:        /*scanf("%d",i);*/
1.349     brouard  11553:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V5*age+ V4+V3*age strb=V3*age OR double product with age strb=age*V6*V2 or V6*V2*age or V6*age*V2 */
                   11554:          cutl(strc,strd,strb,'*'); /**< k=1 strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 OR strb=age*V6*V2 strc=V6*V2 strd=age OR c=V2*age OR c=age*V2  */
                   11555:          if(strchr(strc,'*')) { /**< Model with age and DOUBLE product: allowed since 0.99r44, strc=V6*V2 or V2*age or age*V2, strd=age or V6 or V6   */
                   11556:            Typevar[k]=3;  /* 3 for age and double product age*Vn*Vm varying of fixed */
                   11557:             if(strstr(strc,"age")!=0) { /* It means that strc=V2*age or age*V2 and thus that strd=Vn */
                   11558:               cutl(stre,strf,strc,'*') ; /* strf=age or Vm, stre=Vm or age. If strc=V6*V2 then strf=V6 and stre=V2 */
                   11559:              strcpy(strc,strb); /* save strb(=age*Vn*Vm) into strc */
                   11560:              /* We want strb=Vn*Vm */
                   11561:               if(strcmp(strf,"age")==0){ /* strf is "age" so that stre=Vm =V2 . */
                   11562:                 strcpy(strb,strd);
                   11563:                 strcat(strb,"*");
                   11564:                 strcat(strb,stre);
                   11565:               }else{  /* strf=Vm  If strf=V6 then stre=V2 */
                   11566:                 strcpy(strb,strf);
                   11567:                 strcat(strb,"*");
                   11568:                 strcat(strb,stre);
                   11569:                 strcpy(strd,strb); /* in order for strd to not be "age"  for next test (will be Vn*Vm */
                   11570:               }
1.351     brouard  11571:              /* printf("DEBUG FIXED k=%d, Tage[k]=%d, Tvar[Tage[k]=%d,FixedV[Tvar[Tage[k]]]=%d\n",k,Tage[k],Tvar[Tage[k]],FixedV[Tvar[Tage[k]]]); */
                   11572:              /* FixedV[Tvar[Tage[k]]]=0; /\* HERY not sure if V7*V4*age Fixed might not exist  yet*\/ */
1.349     brouard  11573:             }else{  /* strc=Vn*Vm (and strd=age) and should be strb=Vn*Vm but want to keep original strb double product  */
                   11574:              strcpy(stre,strb); /* save full b in stre */
                   11575:              strcpy(strb,strc); /* save short c in new short b for next block strb=Vn*Vm*/
                   11576:              strcpy(strf,strc); /* save short c in new short f */
                   11577:               cutl(strc,strd,strf,'*'); /* We get strd=Vn and strc=Vm for next block (strb=Vn*Vm)*/
                   11578:              /* strcpy(strc,stre);*/ /* save full e in c for future */
                   11579:             }
                   11580:             cptcovdageprod++; /* double product with age  Which product is it? */
                   11581:             /* strcpy(strb,strc);  /\* strb was age*V6*V2 or V6*V2*age or V6*age*V2 IS now V6*V2 or V2*age or age*V2 *\/ */
                   11582:             /* cutl(strc,strd,strb,'*'); /\* strd=  V6    or   V2     or    age and  strc=  V2 or    age or    V2 *\/ */
1.234     brouard  11583:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
1.349     brouard  11584:            n=atoi(stre);
1.234     brouard  11585:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
1.349     brouard  11586:            m=atoi(strc);
                   11587:            cptcovage++; /* Counts the number of covariates which include age as a product */
                   11588:            Tage[cptcovage]=k; /* For age*V3*V2 gives the position in model of covariates associated with age Tage[1]=6 HERY too*/
                   11589:            if(existcomb[n][m] == 0){
                   11590:              /*  r /home/brouard/Documents/Recherches/REVES/Zachary/Zach-2022/Feinuo_Sun/Feinuo-threeway/femV12V15_3wayintNBe.imach */
                   11591:              printf("Warning in model combination V%d*V%d should exist in the model before adding V%d*V%d*age !\n",n,m,n,m);
                   11592:              fprintf(ficlog,"Warning in model combination V%d*V%d should exist in the model before adding V%d*V%d*age !\n",n,m,n,m);
                   11593:              fflush(ficlog);
                   11594:              k1++;  /* The combination Vn*Vm will be in the model so we create it at k1 */
                   11595:              k12++;
                   11596:              existcomb[n][m]=k1;
                   11597:              existcomb[m][n]=k1;
                   11598:              Tvar[k]=ncovcol+nqv+ntv+nqtv+k1;
                   11599:              Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2+ age*V6*V3 Gives the k position of the k1 double product Vn*Vm or age*Vn*Vm*/
                   11600:              Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 Gives the k1 double product  Vn*Vm or age*Vn*Vm at the k position */
                   11601:              Tvard[k1][1] =m; /* m 1 for V1*/
                   11602:              Tvardk[k][1] =m; /* m 1 for V1*/
                   11603:              Tvard[k1][2] =n; /* n 4 for V4*/
                   11604:              Tvardk[k][2] =n; /* n 4 for V4*/
1.351     brouard  11605: /*           Tvar[Tage[cptcovage]]=k1;*/ /* Tvar[6=age*V3*V2]=9 (new fixed covariate) */ /* We don't know about Fixed yet HERE */
1.349     brouard  11606:              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 */
                   11607:                for (i=1; i<=lastobs;i++){/* For fixed product */
                   11608:                  /* Computes the new covariate which is a product of
                   11609:                     covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   11610:                  covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   11611:                }
                   11612:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   11613:                FixedV[ncovcolt+k12]=0; /* We expand Vn*Vm */
                   11614:                k12++;
                   11615:                FixedV[ncovcolt+k12]=0;
                   11616:              }else{ /*End of FixedV */
                   11617:                cptcovprodvage++; /* Counting the number of varying covariate with age */
                   11618:                FixedV[ncovcolt+k12]=1; /* We expand Vn*Vm */
                   11619:                k12++;
                   11620:                FixedV[ncovcolt+k12]=1;
                   11621:              }
                   11622:            }else{  /* k1 Vn*Vm already exists */
                   11623:              k11=existcomb[n][m];
                   11624:              Tposprod[k]=k11; /* OK */
                   11625:              Tvar[k]=Tvar[Tprod[k11]]; /* HERY */
                   11626:              Tvardk[k][1]=m;
                   11627:              Tvardk[k][2]=n;
                   11628:              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 */
                   11629:                /*cptcovage++;*/ /* Counts the number of covariates which include age as a product */
                   11630:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   11631:                /*Tage[cptcovage]=k;*/ /* For age*V3*V2 Tage[1]=V3*V3=9 HERY too*/
                   11632:                Tvar[Tage[cptcovage]]=k1;
                   11633:                FixedV[ncovcolt+k12]=0; /* We expand Vn*Vm */
                   11634:                k12++;
                   11635:                FixedV[ncovcolt+k12]=0;
                   11636:              }else{ /* Already exists but time varying (and age) */
                   11637:                /*cptcovage++;*/ /* Counts the number of covariates which include age as a product */
                   11638:                /*Tage[cptcovage]=k;*/ /* For age*V3*V2 Tage[1]=V3*V3=9 HERY too*/
                   11639:                /* Tvar[Tage[cptcovage]]=k1; */
                   11640:                cptcovprodvage++;
                   11641:                FixedV[ncovcolt+k12]=1; /* We expand Vn*Vm */
                   11642:                k12++;
                   11643:                FixedV[ncovcolt+k12]=1;
                   11644:              }
                   11645:            }
                   11646:            /* Tage[cptcovage]=k;  /\*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   11647:            /* Tvar[k]=k11; /\* HERY *\/ */
                   11648:          } else {/* simple product strb=age*Vn so that c=Vn and d=age, or strb=Vn*age so that c=age and d=Vn, or b=Vn*Vm so that c=Vm and d=Vn */
                   11649:             cptcovprod++;
                   11650:             if (strcmp(strc,"age")==0) { /**< Model includes age: strb= Vn*age c=age d=Vn*/
                   11651:               /* covar is not filled and then is empty */
                   11652:               cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   11653:               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 */
                   11654:               Typevar[k]=1;  /* 1 for age product */
                   11655:               cptcovage++; /* Counts the number of covariates which include age as a product */
                   11656:               Tage[cptcovage]=k;  /*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   11657:              if( FixedV[Tvar[k]] == 0){
                   11658:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   11659:              }else{
                   11660:                cptcovprodvage++; /* Counting the number of fixedvarying covariate with age */
                   11661:              }
                   11662:               /*printf("stre=%s ", stre);*/
                   11663:             } else if (strcmp(strd,"age")==0) { /* strb= age*Vn c=Vn */
                   11664:               cutl(stre,strb,strc,'V');
                   11665:               Tvar[k]=atoi(stre);
                   11666:               Typevar[k]=1;  /* 1 for age product */
                   11667:               cptcovage++;
                   11668:               Tage[cptcovage]=k;
                   11669:              if( FixedV[Tvar[k]] == 0){
                   11670:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   11671:              }else{
                   11672:                cptcovprodvage++; /* Counting the number of fixedvarying covariate with age */
1.339     brouard  11673:              }
1.349     brouard  11674:             }else{ /*  for product Vn*Vm */
                   11675:              Typevar[k]=2;  /* 2 for product Vn*Vm */
                   11676:              cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   11677:              n=atoi(stre);
                   11678:              cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   11679:              m=atoi(strc);
                   11680:              k1++;
                   11681:              cptcovprodnoage++;
                   11682:              if(existcomb[n][m] != 0 || existcomb[m][n] != 0){
                   11683:                printf("Warning in model combination V%d*V%d already exists in the model in position k1=%d!\n",n,m,existcomb[n][m]);
                   11684:                fprintf(ficlog,"Warning in model combination V%d*V%d already exists in the model in position k1=%d!\n",n,m,existcomb[n][m]);
                   11685:                fflush(ficlog);
                   11686:                k11=existcomb[n][m];
                   11687:                Tvar[k]=ncovcol+nqv+ntv+nqtv+k11;
                   11688:                Tposprod[k]=k11;
                   11689:                Tprod[k11]=k;
                   11690:                Tvardk[k][1] =m; /* m 1 for V1*/
                   11691:                /* Tvard[k11][1] =m; /\* n 4 for V4*\/ */
                   11692:                Tvardk[k][2] =n; /* n 4 for V4*/                
                   11693:                /* Tvard[k11][2] =n; /\* n 4 for V4*\/ */
                   11694:              }else{ /* combination Vn*Vm doesn't exist we create it (no age)*/
                   11695:                existcomb[n][m]=k1;
                   11696:                existcomb[m][n]=k1;
                   11697:                Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* ncovcolt+k1; For model-covariate k tells which data-covariate to use but
                   11698:                                                    because this model-covariate is a construction we invent a new column
                   11699:                                                    which is after existing variables ncovcol+nqv+ntv+nqtv + k1
                   11700:                                                    If already ncovcol=4 and model= V2 + V1 + V1*V4 + age*V3 + V3*V2
                   11701:                                                    thus after V4 we invent V5 and V6 because age*V3 will be computed in 4
                   11702:                                                    Tvar[3=V1*V4]=4+1=5 Tvar[5=V3*V2]=4 + 2= 6, Tvar[4=age*V3]=3 etc */
                   11703:                /* Please remark that the new variables are model dependent */
                   11704:                /* If we have 4 variable but the model uses only 3, like in
                   11705:                 * model= V1 + age*V1 + V2 + V3 + age*V2 + age*V3 + V1*V2 + V1*V3
                   11706:                 *  k=     1     2      3   4     5        6        7       8
                   11707:                 * Tvar[k]=1     1       2   3     2        3       (5       6) (and not 4 5 because of V4 missing)
                   11708:                 * Tage[kk]    [1]= 2           [2]=5      [3]=6                  kk=1 to cptcovage=3
                   11709:                 * Tvar[Tage[kk]][1]=2          [2]=2      [3]=3
                   11710:                 */
                   11711:                /* We need to feed some variables like TvarVV, but later on next loop because of ncovv (k2) is not correct */
                   11712:                Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 +V6*V2*age  */
                   11713:                Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 */
                   11714:                Tvard[k1][1] =m; /* m 1 for V1*/
                   11715:                Tvardk[k][1] =m; /* m 1 for V1*/
                   11716:                Tvard[k1][2] =n; /* n 4 for V4*/
                   11717:                Tvardk[k][2] =n; /* n 4 for V4*/
                   11718:                k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   11719:                /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   11720:                /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
                   11721:                /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
                   11722:                /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   11723:                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 */
                   11724:                  for (i=1; i<=lastobs;i++){/* For fixed product */
                   11725:                    /* Computes the new covariate which is a product of
                   11726:                       covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   11727:                    covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   11728:                  }
                   11729:                  /* TvarVV[k2]=n; */
                   11730:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11731:                  /* TvarVV[k2+1]=m; */
                   11732:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11733:                }else{ /* not FixedV */
                   11734:                  /* TvarVV[k2]=n; */
                   11735:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11736:                  /* TvarVV[k2+1]=m; */
                   11737:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11738:                }                 
                   11739:              }  /* End of creation of Vn*Vm if not created by age*Vn*Vm earlier  */
                   11740:            } /*  End of product Vn*Vm */
                   11741:           } /* End of age*double product or simple product */
                   11742:        }else { /* not a product */
1.234     brouard  11743:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   11744:          /*  scanf("%d",i);*/
                   11745:          cutl(strd,strc,strb,'V');
                   11746:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   11747:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   11748:          Tvar[k]=atoi(strd);
                   11749:          Typevar[k]=0;  /* 0 for simple covariates */
                   11750:        }
                   11751:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  11752:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  11753:                                  scanf("%d",i);*/
1.187     brouard  11754:       } /* end of loop + on total covariates */
1.351     brouard  11755: 
                   11756:       
1.187     brouard  11757:     } /* end if strlen(modelsave == 0) age*age might exist */
                   11758:   } /* end if strlen(model == 0) */
1.349     brouard  11759:   cptcovs=cptcovt - cptcovdageprod - cptcovprod;/**<  Number of simple covariates V1 +V1*age +V3 +V3*V4 +age*age + age*v4*V3=> V1 + V3 =4+1-3=2  */
                   11760: 
1.136     brouard  11761:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   11762:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  11763:   
1.136     brouard  11764:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  11765:      printf("cptcovprod=%d ", cptcovprod);
                   11766:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   11767:      scanf("%d ",i);*/
                   11768: 
                   11769: 
1.230     brouard  11770: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   11771:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  11772: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   11773:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   11774:    k =           1    2   3     4       5       6      7      8        9
                   11775:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
1.319     brouard  11776:    Typevar[k]=   0    0   0     2       1       0      2      1        0
1.227     brouard  11777:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   11778:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   11779:          Tmodelind[combination of covar]=k;
1.225     brouard  11780: */  
                   11781: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  11782:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  11783:   /* 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  11784:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.318     brouard  11785:   printf("Model=1+age+%s\n\
1.349     brouard  11786: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product, 3 for double product with age \n\
1.227     brouard  11787: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   11788: 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  11789:   fprintf(ficlog,"Model=1+age+%s\n\
1.349     brouard  11790: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product, 3 for double product with age  \n\
1.227     brouard  11791: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   11792: 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  11793:   for(k=-1;k<=NCOVMAX; k++){ Fixed[k]=0; Dummy[k]=0;}
                   11794:   for(k=1;k<=NCOVMAX; k++){TvarFind[k]=0; TvarVind[k]=0;}
1.351     brouard  11795: 
                   11796: 
                   11797:   /* Second loop for calculating  Fixed[k], Dummy[k]*/
                   11798: 
                   11799:   
1.349     brouard  11800:   for(k=1, ncovf=0, nsd=0, nsq=0, ncovv=0,ncovva=0,ncovvta=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  11801:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  11802:       Fixed[k]= 0;
                   11803:       Dummy[k]= 0;
1.225     brouard  11804:       ncoveff++;
1.232     brouard  11805:       ncovf++;
1.234     brouard  11806:       nsd++;
                   11807:       modell[k].maintype= FTYPE;
                   11808:       TvarsD[nsd]=Tvar[k];
                   11809:       TvarsDind[nsd]=k;
1.330     brouard  11810:       TnsdVar[Tvar[k]]=nsd;
1.234     brouard  11811:       TvarF[ncovf]=Tvar[k];
                   11812:       TvarFind[ncovf]=k;
                   11813:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   11814:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.339     brouard  11815:     /* }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /\* Product of fixed dummy (<=ncovcol) covariates For a fixed product k is higher than ncovcol *\/ */
1.240     brouard  11816:     }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  11817:       Fixed[k]= 0;
                   11818:       Dummy[k]= 1;
1.230     brouard  11819:       nqfveff++;
1.234     brouard  11820:       modell[k].maintype= FTYPE;
                   11821:       modell[k].subtype= FQ;
                   11822:       nsq++;
1.334     brouard  11823:       TvarsQ[nsq]=Tvar[k]; /* Gives the variable name (extended to products) of first nsq simple quantitative covariates (fixed or time vary see below */
                   11824:       TvarsQind[nsq]=k;    /* Gives the position in the model equation of the first nsq simple quantitative covariates (fixed or time vary) */
1.232     brouard  11825:       ncovf++;
1.234     brouard  11826:       TvarF[ncovf]=Tvar[k];
                   11827:       TvarFind[ncovf]=k;
1.231     brouard  11828:       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  11829:       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  11830:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.339     brouard  11831:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11832:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11833:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11834:       ncovvt++;
                   11835:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11836:       TvarVVind[ncovvt]=k;    /*  TvarVVind[1]=2 (second position in the model equation  */
                   11837: 
1.227     brouard  11838:       Fixed[k]= 1;
                   11839:       Dummy[k]= 0;
1.225     brouard  11840:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  11841:       modell[k].maintype= VTYPE;
                   11842:       modell[k].subtype= VD;
                   11843:       nsd++;
                   11844:       TvarsD[nsd]=Tvar[k];
                   11845:       TvarsDind[nsd]=k;
1.330     brouard  11846:       TnsdVar[Tvar[k]]=nsd; /* To be verified */
1.234     brouard  11847:       ncovv++; /* Only simple time varying variables */
                   11848:       TvarV[ncovv]=Tvar[k];
1.242     brouard  11849:       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  11850:       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 */
                   11851:       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  11852:       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);
                   11853:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  11854:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.339     brouard  11855:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11856:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11857:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11858:       ncovvt++;
                   11859:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11860:       TvarVVind[ncovvt]=k;  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11861:       
1.234     brouard  11862:       Fixed[k]= 1;
                   11863:       Dummy[k]= 1;
                   11864:       nqtveff++;
                   11865:       modell[k].maintype= VTYPE;
                   11866:       modell[k].subtype= VQ;
                   11867:       ncovv++; /* Only simple time varying variables */
                   11868:       nsq++;
1.334     brouard  11869:       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) */
                   11870:       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  11871:       TvarV[ncovv]=Tvar[k];
1.242     brouard  11872:       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  11873:       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 */
                   11874:       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  11875:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   11876:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
1.349     brouard  11877:       /* printf("Quasi TmodelQind[%d]=%d,Tvar[TmodelQind[%d]]=V%d, ncovcol=%d, nqv=%d, ntv=%Ad,Tvar[k]- ncovcol-nqv-ntv=%d\n",nqtveff,k,nqtveff,Tvar[k], ncovcol, nqv, ntv, Tvar[k]- ncovcol-nqv-ntv); */
1.342     brouard  11878:       /* printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv); */
1.227     brouard  11879:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  11880:       ncova++;
                   11881:       TvarA[ncova]=Tvar[k];
                   11882:       TvarAind[ncova]=k;
1.349     brouard  11883:       /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   11884:       /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
1.231     brouard  11885:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  11886:        Fixed[k]= 2;
                   11887:        Dummy[k]= 2;
                   11888:        modell[k].maintype= ATYPE;
                   11889:        modell[k].subtype= APFD;
1.349     brouard  11890:        ncovta++;
                   11891:        TvarAVVA[ncovta]=Tvar[k]; /*  (2)age*V3 */
                   11892:        TvarAVVAind[ncovta]=k;
1.240     brouard  11893:        /* ncoveff++; */
1.227     brouard  11894:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  11895:        Fixed[k]= 2;
                   11896:        Dummy[k]= 3;
                   11897:        modell[k].maintype= ATYPE;
                   11898:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
1.349     brouard  11899:        ncovta++;
                   11900:        TvarAVVA[ncovta]=Tvar[k]; /*   */
                   11901:        TvarAVVAind[ncovta]=k;
1.240     brouard  11902:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  11903:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  11904:        Fixed[k]= 3;
                   11905:        Dummy[k]= 2;
                   11906:        modell[k].maintype= ATYPE;
                   11907:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
1.349     brouard  11908:        ncovva++;
                   11909:        TvarVVA[ncovva]=Tvar[k]; /*  (1)+age*V6 + (2)age*V7 */
                   11910:        TvarVVAind[ncovva]=k;
                   11911:        ncovta++;
                   11912:        TvarAVVA[ncovta]=Tvar[k]; /*   */
                   11913:        TvarAVVAind[ncovta]=k;
1.240     brouard  11914:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  11915:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  11916:        Fixed[k]= 3;
                   11917:        Dummy[k]= 3;
                   11918:        modell[k].maintype= ATYPE;
                   11919:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
1.349     brouard  11920:        ncovva++;
                   11921:        TvarVVA[ncovva]=Tvar[k]; /*   */
                   11922:        TvarVVAind[ncovva]=k;
                   11923:        ncovta++;
                   11924:        TvarAVVA[ncovta]=Tvar[k]; /*  (1)+age*V6 + (2)age*V7 */
                   11925:        TvarAVVAind[ncovta]=k;
1.240     brouard  11926:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  11927:       }
1.349     brouard  11928:     }else if( Tposprod[k]>0  &&  Typevar[k]==2){  /* Detects if fixed product no age Vm*Vn */
                   11929:       printf("MEMORY ERRORR k=%d  Tposprod[k]=%d, Typevar[k]=%d\n ",k, Tposprod[k], Typevar[k]);
                   11930:       if(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 V3*V2 */
                   11931:       printf("MEMORY ERRORR k=%d Tvardk[k][1]=%d, Tvardk[k][2]=%d, FixedV[Tvardk[k][1]]=%d,FixedV[Tvardk[k][2]]=%d\n ",k,Tvardk[k][1],Tvardk[k][2],FixedV[Tvardk[k][1]],FixedV[Tvardk[k][2]]);
                   11932:        Fixed[k]= 0;
                   11933:        Dummy[k]= 0;
                   11934:        ncoveff++;
                   11935:        ncovf++;
                   11936:        /* ncovv++; */
                   11937:        /* TvarVV[ncovv]=Tvardk[k][1]; */
                   11938:        /* FixedV[ncovcolt+ncovv]=0; /\* or FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11939:        /* ncovv++; */
                   11940:        /* TvarVV[ncovv]=Tvardk[k][2]; */
                   11941:        /* FixedV[ncovcolt+ncovv]=0; /\* or FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11942:        modell[k].maintype= FTYPE;
                   11943:        TvarF[ncovf]=Tvar[k];
                   11944:        /* TnsdVar[Tvar[k]]=nsd; */ /* To be done */
                   11945:        TvarFind[ncovf]=k;
                   11946:        TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   11947:        TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   11948:       }else{/* product varying 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  */
                   11949:        /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11950:        /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age*/
                   11951:        /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11952:        k1=Tposprod[k];  /* Position in the products of product k, Tposprod={0, 0, 0, 0, 1, 1} k1=1 first product but second time varying because of V3 */
                   11953:        ncovvt++;
                   11954:        TvarVV[ncovvt]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
                   11955:        TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   11956:        ncovvt++;
                   11957:        TvarVV[ncovvt]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
                   11958:        TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   11959:        
                   11960:        /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   11961:        /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
                   11962:        
                   11963:        if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   11964:          if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
                   11965:            Fixed[k]= 1;
                   11966:            Dummy[k]= 0;
                   11967:            modell[k].maintype= FTYPE;
                   11968:            modell[k].subtype= FPDD;            /*      Product fixed dummy * fixed dummy */
                   11969:            ncovf++; /* Fixed variables without age */
                   11970:            TvarF[ncovf]=Tvar[k];
                   11971:            TvarFind[ncovf]=k;
                   11972:          }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
                   11973:            Fixed[k]= 0;  /* Fixed product */
                   11974:            Dummy[k]= 1;
                   11975:            modell[k].maintype= FTYPE;
                   11976:            modell[k].subtype= FPDQ;            /*      Product fixed dummy * fixed quantitative */
                   11977:            ncovf++; /* Varying variables without age */
                   11978:            TvarF[ncovf]=Tvar[k];
                   11979:            TvarFind[ncovf]=k;
                   11980:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
                   11981:            Fixed[k]= 1;
                   11982:            Dummy[k]= 0;
                   11983:            modell[k].maintype= VTYPE;
                   11984:            modell[k].subtype= VPDD;            /*      Product fixed dummy * varying dummy */
                   11985:            ncovv++; /* Varying variables without age */
                   11986:            TvarV[ncovv]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
                   11987:            TvarVind[ncovv]=k;/* TvarVind[1]=5 */ 
                   11988:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
                   11989:            Fixed[k]= 1;
                   11990:            Dummy[k]= 1;
                   11991:            modell[k].maintype= VTYPE;
                   11992:            modell[k].subtype= VPDQ;            /*      Product fixed dummy * varying quantitative */
                   11993:            ncovv++; /* Varying variables without age */
                   11994:            TvarV[ncovv]=Tvar[k];
                   11995:            TvarVind[ncovv]=k;
                   11996:          }
                   11997:        }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   11998:          if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
                   11999:            Fixed[k]= 0;  /*  Fixed product */
                   12000:            Dummy[k]= 1;
                   12001:            modell[k].maintype= FTYPE;
                   12002:            modell[k].subtype= FPDQ;            /*      Product fixed quantitative * fixed dummy */
                   12003:            ncovf++; /* Fixed variables without age */
                   12004:            TvarF[ncovf]=Tvar[k];
                   12005:            TvarFind[ncovf]=k;
                   12006:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
                   12007:            Fixed[k]= 1;
                   12008:            Dummy[k]= 1;
                   12009:            modell[k].maintype= VTYPE;
                   12010:            modell[k].subtype= VPDQ;            /*      Product fixed quantitative * varying dummy */
                   12011:            ncovv++; /* Varying variables without age */
                   12012:            TvarV[ncovv]=Tvar[k];
                   12013:            TvarVind[ncovv]=k;
                   12014:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
                   12015:            Fixed[k]= 1;
                   12016:            Dummy[k]= 1;
                   12017:            modell[k].maintype= VTYPE;
                   12018:            modell[k].subtype= VPQQ;            /*      Product fixed quantitative * varying quantitative */
                   12019:            ncovv++; /* Varying variables without age */
                   12020:            TvarV[ncovv]=Tvar[k];
                   12021:            TvarVind[ncovv]=k;
                   12022:            ncovv++; /* Varying variables without age */
                   12023:            TvarV[ncovv]=Tvar[k];
                   12024:            TvarVind[ncovv]=k;
                   12025:          }
                   12026:        }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
                   12027:          if(Tvard[k1][2] <=ncovcol){
                   12028:            Fixed[k]= 1;
                   12029:            Dummy[k]= 1;
                   12030:            modell[k].maintype= VTYPE;
                   12031:            modell[k].subtype= VPDD;            /*      Product time varying dummy * fixed dummy */
                   12032:            ncovv++; /* Varying variables without age */
                   12033:            TvarV[ncovv]=Tvar[k];
                   12034:            TvarVind[ncovv]=k;
                   12035:          }else if(Tvard[k1][2] <=ncovcol+nqv){
                   12036:            Fixed[k]= 1;
                   12037:            Dummy[k]= 1;
                   12038:            modell[k].maintype= VTYPE;
                   12039:            modell[k].subtype= VPDQ;            /*      Product time varying dummy * fixed quantitative */
                   12040:            ncovv++; /* Varying variables without age */
                   12041:            TvarV[ncovv]=Tvar[k];
                   12042:            TvarVind[ncovv]=k;
                   12043:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   12044:            Fixed[k]= 1;
                   12045:            Dummy[k]= 0;
                   12046:            modell[k].maintype= VTYPE;
                   12047:            modell[k].subtype= VPDD;            /*      Product time varying dummy * time varying dummy */
                   12048:            ncovv++; /* Varying variables without age */
                   12049:            TvarV[ncovv]=Tvar[k];
                   12050:            TvarVind[ncovv]=k;
                   12051:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   12052:            Fixed[k]= 1;
                   12053:            Dummy[k]= 1;
                   12054:            modell[k].maintype= VTYPE;
                   12055:            modell[k].subtype= VPDQ;            /*      Product time varying dummy * time varying quantitative */
                   12056:            ncovv++; /* Varying variables without age */
                   12057:            TvarV[ncovv]=Tvar[k];
                   12058:            TvarVind[ncovv]=k;
                   12059:          }
                   12060:        }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
                   12061:          if(Tvard[k1][2] <=ncovcol){
                   12062:            Fixed[k]= 1;
                   12063:            Dummy[k]= 1;
                   12064:            modell[k].maintype= VTYPE;
                   12065:            modell[k].subtype= VPDQ;            /*      Product time varying quantitative * fixed dummy */
                   12066:            ncovv++; /* Varying variables without age */
                   12067:            TvarV[ncovv]=Tvar[k];
                   12068:            TvarVind[ncovv]=k;
                   12069:          }else if(Tvard[k1][2] <=ncovcol+nqv){
                   12070:            Fixed[k]= 1;
                   12071:            Dummy[k]= 1;
                   12072:            modell[k].maintype= VTYPE;
                   12073:            modell[k].subtype= VPQQ;            /*      Product time varying quantitative * fixed quantitative */
                   12074:            ncovv++; /* Varying variables without age */
                   12075:            TvarV[ncovv]=Tvar[k];
                   12076:            TvarVind[ncovv]=k;
                   12077:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   12078:            Fixed[k]= 1;
                   12079:            Dummy[k]= 1;
                   12080:            modell[k].maintype= VTYPE;
                   12081:            modell[k].subtype= VPDQ;            /*      Product time varying quantitative * time varying dummy */
                   12082:            ncovv++; /* Varying variables without age */
                   12083:            TvarV[ncovv]=Tvar[k];
                   12084:            TvarVind[ncovv]=k;
                   12085:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   12086:            Fixed[k]= 1;
                   12087:            Dummy[k]= 1;
                   12088:            modell[k].maintype= VTYPE;
                   12089:            modell[k].subtype= VPQQ;            /*      Product time varying quantitative * time varying quantitative */
                   12090:            ncovv++; /* Varying variables without age */
                   12091:            TvarV[ncovv]=Tvar[k];
                   12092:            TvarVind[ncovv]=k;
                   12093:          }
                   12094:        }else{
                   12095:          printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   12096:          fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   12097:        } /*end k1*/
                   12098:       }
                   12099:     }else if(Typevar[k] == 3){  /* product Vn * Vm with 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  */
1.339     brouard  12100:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
1.349     brouard  12101:       /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age*/
                   12102:       /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   12103:       k1=Tposprod[k];  /* Position in the products of product k, Tposprod={0, 0, 0, 0, 1, 1} k1=1 first product but second time varying because of V3 */
                   12104:       ncova++;
                   12105:       TvarA[ncova]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
                   12106:       TvarAind[ncova]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   12107:       ncova++;
                   12108:       TvarA[ncova]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
                   12109:       TvarAind[ncova]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
1.339     brouard  12110: 
1.349     brouard  12111:       /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   12112:       /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
                   12113:       if( FixedV[Tvardk[k][1]] == 0 && FixedV[Tvardk[k][2]] == 0){
                   12114:        ncovta++;
                   12115:        TvarAVVA[ncovta]=Tvard[k1][1]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   12116:        TvarAVVAind[ncovta]=k;
                   12117:        ncovta++;
                   12118:        TvarAVVA[ncovta]=Tvard[k1][2]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   12119:        TvarAVVAind[ncovta]=k;
                   12120:       }else{
                   12121:        ncovva++;  /* HERY  reached */
                   12122:        TvarVVA[ncovva]=Tvard[k1][1]; /*  age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4  */
                   12123:        TvarVVAind[ncovva]=k;
                   12124:        ncovva++;
                   12125:        TvarVVA[ncovva]=Tvard[k1][2]; /*   */
                   12126:        TvarVVAind[ncovva]=k;
                   12127:        ncovta++;
                   12128:        TvarAVVA[ncovta]=Tvard[k1][1]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   12129:        TvarAVVAind[ncovta]=k;
                   12130:        ncovta++;
                   12131:        TvarAVVA[ncovta]=Tvard[k1][2]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   12132:        TvarAVVAind[ncovta]=k;
                   12133:       }
1.339     brouard  12134:       if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   12135:        if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
1.349     brouard  12136:          Fixed[k]= 2;
                   12137:          Dummy[k]= 2;
1.240     brouard  12138:          modell[k].maintype= FTYPE;
                   12139:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
1.349     brouard  12140:          /* TvarF[ncova]=Tvar[k];   /\* Problem to solve *\/ */
                   12141:          /* TvarFind[ncova]=k; */
1.339     brouard  12142:        }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
1.349     brouard  12143:          Fixed[k]= 2;  /* Fixed product */
                   12144:          Dummy[k]= 3;
1.240     brouard  12145:          modell[k].maintype= FTYPE;
                   12146:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
1.349     brouard  12147:          /* TvarF[ncova]=Tvar[k]; */
                   12148:          /* TvarFind[ncova]=k; */
1.339     brouard  12149:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
1.349     brouard  12150:          Fixed[k]= 3;
                   12151:          Dummy[k]= 2;
1.240     brouard  12152:          modell[k].maintype= VTYPE;
                   12153:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
1.349     brouard  12154:          TvarV[ncova]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
                   12155:          TvarVind[ncova]=k;/* TvarVind[1]=5 */ 
1.339     brouard  12156:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
1.349     brouard  12157:          Fixed[k]= 3;
                   12158:          Dummy[k]= 3;
1.240     brouard  12159:          modell[k].maintype= VTYPE;
                   12160:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
1.349     brouard  12161:          /* ncovv++; /\* Varying variables without age *\/ */
                   12162:          /* TvarV[ncovv]=Tvar[k]; */
                   12163:          /* TvarVind[ncovv]=k; */
1.240     brouard  12164:        }
1.339     brouard  12165:       }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   12166:        if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
1.349     brouard  12167:          Fixed[k]= 2;  /*  Fixed product */
                   12168:          Dummy[k]= 2;
1.240     brouard  12169:          modell[k].maintype= FTYPE;
                   12170:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
1.349     brouard  12171:          /* ncova++; /\* Fixed variables with age *\/ */
                   12172:          /* TvarF[ncovf]=Tvar[k]; */
                   12173:          /* TvarFind[ncovf]=k; */
1.339     brouard  12174:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
1.349     brouard  12175:          Fixed[k]= 2;
                   12176:          Dummy[k]= 3;
1.240     brouard  12177:          modell[k].maintype= VTYPE;
                   12178:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
1.349     brouard  12179:          /* ncova++; /\* Varying variables with age *\/ */
                   12180:          /* TvarV[ncova]=Tvar[k]; */
                   12181:          /* TvarVind[ncova]=k; */
1.339     brouard  12182:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
1.349     brouard  12183:          Fixed[k]= 3;
                   12184:          Dummy[k]= 2;
1.240     brouard  12185:          modell[k].maintype= VTYPE;
                   12186:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
1.349     brouard  12187:          ncova++; /* Varying variables without age */
                   12188:          TvarV[ncova]=Tvar[k];
                   12189:          TvarVind[ncova]=k;
                   12190:          /* ncova++; /\* Varying variables without age *\/ */
                   12191:          /* TvarV[ncova]=Tvar[k]; */
                   12192:          /* TvarVind[ncova]=k; */
1.240     brouard  12193:        }
1.339     brouard  12194:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
1.240     brouard  12195:        if(Tvard[k1][2] <=ncovcol){
1.349     brouard  12196:          Fixed[k]= 2;
                   12197:          Dummy[k]= 2;
1.240     brouard  12198:          modell[k].maintype= VTYPE;
                   12199:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
1.349     brouard  12200:          /* ncova++; /\* Varying variables with age *\/ */
                   12201:          /* TvarV[ncova]=Tvar[k]; */
                   12202:          /* TvarVind[ncova]=k; */
1.240     brouard  12203:        }else if(Tvard[k1][2] <=ncovcol+nqv){
1.349     brouard  12204:          Fixed[k]= 2;
                   12205:          Dummy[k]= 3;
1.240     brouard  12206:          modell[k].maintype= VTYPE;
                   12207:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
1.349     brouard  12208:          /* ncova++; /\* Varying variables with age *\/ */
                   12209:          /* TvarV[ncova]=Tvar[k]; */
                   12210:          /* TvarVind[ncova]=k; */
1.240     brouard  12211:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
1.349     brouard  12212:          Fixed[k]= 3;
                   12213:          Dummy[k]= 2;
1.240     brouard  12214:          modell[k].maintype= VTYPE;
                   12215:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
1.349     brouard  12216:          /* ncova++; /\* Varying variables with age *\/ */
                   12217:          /* TvarV[ncova]=Tvar[k]; */
                   12218:          /* TvarVind[ncova]=k; */
1.240     brouard  12219:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
1.349     brouard  12220:          Fixed[k]= 3;
                   12221:          Dummy[k]= 3;
1.240     brouard  12222:          modell[k].maintype= VTYPE;
                   12223:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
1.349     brouard  12224:          /* ncova++; /\* Varying variables with age *\/ */
                   12225:          /* TvarV[ncova]=Tvar[k]; */
                   12226:          /* TvarVind[ncova]=k; */
1.240     brouard  12227:        }
1.339     brouard  12228:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
1.240     brouard  12229:        if(Tvard[k1][2] <=ncovcol){
1.349     brouard  12230:          Fixed[k]= 2;
                   12231:          Dummy[k]= 2;
1.240     brouard  12232:          modell[k].maintype= VTYPE;
                   12233:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
1.349     brouard  12234:          /* ncova++; /\* Varying variables with age *\/ */
                   12235:          /* TvarV[ncova]=Tvar[k]; */
                   12236:          /* TvarVind[ncova]=k; */
1.240     brouard  12237:        }else if(Tvard[k1][2] <=ncovcol+nqv){
1.349     brouard  12238:          Fixed[k]= 2;
                   12239:          Dummy[k]= 3;
1.240     brouard  12240:          modell[k].maintype= VTYPE;
                   12241:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
1.349     brouard  12242:          /* ncova++; /\* Varying variables with age *\/ */
                   12243:          /* TvarV[ncova]=Tvar[k]; */
                   12244:          /* TvarVind[ncova]=k; */
1.240     brouard  12245:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
1.349     brouard  12246:          Fixed[k]= 3;
                   12247:          Dummy[k]= 2;
1.240     brouard  12248:          modell[k].maintype= VTYPE;
                   12249:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
1.349     brouard  12250:          /* ncova++; /\* Varying variables with age *\/ */
                   12251:          /* TvarV[ncova]=Tvar[k]; */
                   12252:          /* TvarVind[ncova]=k; */
1.240     brouard  12253:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
1.349     brouard  12254:          Fixed[k]= 3;
                   12255:          Dummy[k]= 3;
1.240     brouard  12256:          modell[k].maintype= VTYPE;
                   12257:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
1.349     brouard  12258:          /* ncova++; /\* Varying variables with age *\/ */
                   12259:          /* TvarV[ncova]=Tvar[k]; */
                   12260:          /* TvarVind[ncova]=k; */
1.240     brouard  12261:        }
1.227     brouard  12262:       }else{
1.240     brouard  12263:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   12264:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   12265:       } /*end k1*/
1.349     brouard  12266:     } else{
1.226     brouard  12267:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   12268:       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  12269:     }
1.342     brouard  12270:     /* 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]); */
                   12271:     /* printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype); */
1.227     brouard  12272:     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]);
                   12273:   }
1.349     brouard  12274:   ncovvta=ncovva;
1.227     brouard  12275:   /* Searching for doublons in the model */
                   12276:   for(k1=1; k1<= cptcovt;k1++){
                   12277:     for(k2=1; k2 <k1;k2++){
1.285     brouard  12278:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   12279:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  12280:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   12281:          if(Tvar[k1]==Tvar[k2]){
1.338     brouard  12282:            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]);
                   12283:            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  12284:            return(1);
                   12285:          }
                   12286:        }else if (Typevar[k1] ==2){
                   12287:          k3=Tposprod[k1];
                   12288:          k4=Tposprod[k2];
                   12289:          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  12290:            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]]);
                   12291:            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  12292:            return(1);
                   12293:          }
                   12294:        }
1.227     brouard  12295:       }
                   12296:     }
1.225     brouard  12297:   }
                   12298:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   12299:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  12300:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   12301:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.349     brouard  12302: 
                   12303:   free_imatrix(existcomb,1,NCOVMAX,1,NCOVMAX);
1.137     brouard  12304:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  12305:   /*endread:*/
1.225     brouard  12306:   printf("Exiting decodemodel: ");
                   12307:   return (1);
1.136     brouard  12308: }
                   12309: 
1.169     brouard  12310: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  12311: {/* Check ages at death */
1.136     brouard  12312:   int i, m;
1.218     brouard  12313:   int firstone=0;
                   12314:   
1.136     brouard  12315:   for (i=1; i<=imx; i++) {
                   12316:     for(m=2; (m<= maxwav); m++) {
                   12317:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   12318:        anint[m][i]=9999;
1.216     brouard  12319:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   12320:          s[m][i]=-1;
1.136     brouard  12321:       }
                   12322:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  12323:        *nberr = *nberr + 1;
1.218     brouard  12324:        if(firstone == 0){
                   12325:          firstone=1;
1.260     brouard  12326:        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  12327:        }
1.262     brouard  12328:        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  12329:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  12330:       }
                   12331:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  12332:        (*nberr)++;
1.259     brouard  12333:        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  12334:        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  12335:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  12336:       }
                   12337:     }
                   12338:   }
                   12339: 
                   12340:   for (i=1; i<=imx; i++)  {
                   12341:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   12342:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  12343:       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  12344:        if (s[m][i] >= nlstate+1) {
1.169     brouard  12345:          if(agedc[i]>0){
                   12346:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  12347:              agev[m][i]=agedc[i];
1.214     brouard  12348:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  12349:            }else {
1.136     brouard  12350:              if ((int)andc[i]!=9999){
                   12351:                nbwarn++;
                   12352:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   12353:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   12354:                agev[m][i]=-1;
                   12355:              }
                   12356:            }
1.169     brouard  12357:          } /* agedc > 0 */
1.214     brouard  12358:        } /* end if */
1.136     brouard  12359:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   12360:                                 years but with the precision of a month */
                   12361:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   12362:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   12363:            agev[m][i]=1;
                   12364:          else if(agev[m][i] < *agemin){ 
                   12365:            *agemin=agev[m][i];
                   12366:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   12367:          }
                   12368:          else if(agev[m][i] >*agemax){
                   12369:            *agemax=agev[m][i];
1.156     brouard  12370:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  12371:          }
                   12372:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   12373:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  12374:        } /* en if 9*/
1.136     brouard  12375:        else { /* =9 */
1.214     brouard  12376:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  12377:          agev[m][i]=1;
                   12378:          s[m][i]=-1;
                   12379:        }
                   12380:       }
1.214     brouard  12381:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  12382:        agev[m][i]=1;
1.214     brouard  12383:       else{
                   12384:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   12385:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   12386:        agev[m][i]=0;
                   12387:       }
                   12388:     } /* End for lastpass */
                   12389:   }
1.136     brouard  12390:     
                   12391:   for (i=1; i<=imx; i++)  {
                   12392:     for(m=firstpass; (m<=lastpass); m++){
                   12393:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  12394:        (*nberr)++;
1.136     brouard  12395:        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);     
                   12396:        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);     
                   12397:        return 1;
                   12398:       }
                   12399:     }
                   12400:   }
                   12401: 
                   12402:   /*for (i=1; i<=imx; i++){
                   12403:   for (m=firstpass; (m<lastpass); m++){
                   12404:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   12405: }
                   12406: 
                   12407: }*/
                   12408: 
                   12409: 
1.139     brouard  12410:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   12411:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  12412: 
                   12413:   return (0);
1.164     brouard  12414:  /* endread:*/
1.136     brouard  12415:     printf("Exiting calandcheckages: ");
                   12416:     return (1);
                   12417: }
                   12418: 
1.172     brouard  12419: #if defined(_MSC_VER)
                   12420: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   12421: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   12422: //#include "stdafx.h"
                   12423: //#include <stdio.h>
                   12424: //#include <tchar.h>
                   12425: //#include <windows.h>
                   12426: //#include <iostream>
                   12427: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   12428: 
                   12429: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   12430: 
                   12431: BOOL IsWow64()
                   12432: {
                   12433:        BOOL bIsWow64 = FALSE;
                   12434: 
                   12435:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   12436:        //  (HANDLE, PBOOL);
                   12437: 
                   12438:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   12439: 
                   12440:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   12441:        const char funcName[] = "IsWow64Process";
                   12442:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   12443:                GetProcAddress(module, funcName);
                   12444: 
                   12445:        if (NULL != fnIsWow64Process)
                   12446:        {
                   12447:                if (!fnIsWow64Process(GetCurrentProcess(),
                   12448:                        &bIsWow64))
                   12449:                        //throw std::exception("Unknown error");
                   12450:                        printf("Unknown error\n");
                   12451:        }
                   12452:        return bIsWow64 != FALSE;
                   12453: }
                   12454: #endif
1.177     brouard  12455: 
1.191     brouard  12456: void syscompilerinfo(int logged)
1.292     brouard  12457: {
                   12458: #include <stdint.h>
                   12459: 
                   12460:   /* #include "syscompilerinfo.h"*/
1.185     brouard  12461:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   12462:    /* /GS /W3 /Gy
                   12463:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   12464:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   12465:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  12466:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   12467:    */ 
                   12468:    /* 64 bits */
1.185     brouard  12469:    /*
                   12470:      /GS /W3 /Gy
                   12471:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   12472:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   12473:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   12474:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   12475:    /* Optimization are useless and O3 is slower than O2 */
                   12476:    /*
                   12477:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   12478:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   12479:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   12480:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   12481:    */
1.186     brouard  12482:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  12483:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   12484:       /PDB:"visual studio
                   12485:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   12486:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   12487:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   12488:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   12489:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   12490:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   12491:       uiAccess='false'"
                   12492:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   12493:       /NOLOGO /TLBID:1
                   12494:    */
1.292     brouard  12495: 
                   12496: 
1.177     brouard  12497: #if defined __INTEL_COMPILER
1.178     brouard  12498: #if defined(__GNUC__)
                   12499:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   12500: #endif
1.177     brouard  12501: #elif defined(__GNUC__) 
1.179     brouard  12502: #ifndef  __APPLE__
1.174     brouard  12503: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  12504: #endif
1.177     brouard  12505:    struct utsname sysInfo;
1.178     brouard  12506:    int cross = CROSS;
                   12507:    if (cross){
                   12508:           printf("Cross-");
1.191     brouard  12509:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  12510:    }
1.174     brouard  12511: #endif
                   12512: 
1.191     brouard  12513:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  12514: #if defined(__clang__)
1.191     brouard  12515:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  12516: #endif
                   12517: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  12518:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  12519: #endif
                   12520: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  12521:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  12522: #endif
                   12523: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  12524:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  12525: #endif
                   12526: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  12527:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  12528: #endif
                   12529: #if defined(_MSC_VER)
1.191     brouard  12530:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  12531: #endif
                   12532: #if defined(__PGI)
1.191     brouard  12533:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  12534: #endif
                   12535: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  12536:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  12537: #endif
1.191     brouard  12538:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  12539:    
1.167     brouard  12540: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   12541: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   12542:     // Windows (x64 and x86)
1.191     brouard  12543:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  12544: #elif __unix__ // all unices, not all compilers
                   12545:     // Unix
1.191     brouard  12546:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  12547: #elif __linux__
                   12548:     // linux
1.191     brouard  12549:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  12550: #elif __APPLE__
1.174     brouard  12551:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  12552:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  12553: #endif
                   12554: 
                   12555: /*  __MINGW32__          */
                   12556: /*  __CYGWIN__  */
                   12557: /* __MINGW64__  */
                   12558: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   12559: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   12560: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   12561: /* _WIN64  // Defined for applications for Win64. */
                   12562: /* _M_X64 // Defined for compilations that target x64 processors. */
                   12563: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  12564: 
1.167     brouard  12565: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  12566:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  12567: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  12568:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  12569: #else
1.191     brouard  12570:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  12571: #endif
                   12572: 
1.169     brouard  12573: #if defined(__GNUC__)
                   12574: # if defined(__GNUC_PATCHLEVEL__)
                   12575: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   12576:                             + __GNUC_MINOR__ * 100 \
                   12577:                             + __GNUC_PATCHLEVEL__)
                   12578: # else
                   12579: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   12580:                             + __GNUC_MINOR__ * 100)
                   12581: # endif
1.174     brouard  12582:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  12583:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  12584: 
                   12585:    if (uname(&sysInfo) != -1) {
                   12586:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  12587:         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  12588:    }
                   12589:    else
                   12590:       perror("uname() error");
1.179     brouard  12591:    //#ifndef __INTEL_COMPILER 
                   12592: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  12593:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  12594:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  12595: #endif
1.169     brouard  12596: #endif
1.172     brouard  12597: 
1.286     brouard  12598:    //   void main ()
1.172     brouard  12599:    //   {
1.169     brouard  12600: #if defined(_MSC_VER)
1.174     brouard  12601:    if (IsWow64()){
1.191     brouard  12602:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   12603:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  12604:    }
                   12605:    else{
1.191     brouard  12606:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   12607:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  12608:    }
1.172     brouard  12609:    //     printf("\nPress Enter to continue...");
                   12610:    //     getchar();
                   12611:    //   }
                   12612: 
1.169     brouard  12613: #endif
                   12614:    
1.167     brouard  12615: 
1.219     brouard  12616: }
1.136     brouard  12617: 
1.219     brouard  12618: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  12619:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.332     brouard  12620:   /* Computes the prevalence limit for each combination of the dummy covariates */
1.235     brouard  12621:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  12622:   /* double ftolpl = 1.e-10; */
1.180     brouard  12623:   double age, agebase, agelim;
1.203     brouard  12624:   double tot;
1.180     brouard  12625: 
1.202     brouard  12626:   strcpy(filerespl,"PL_");
                   12627:   strcat(filerespl,fileresu);
                   12628:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  12629:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   12630:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  12631:   }
1.288     brouard  12632:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   12633:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  12634:   pstamp(ficrespl);
1.288     brouard  12635:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  12636:   fprintf(ficrespl,"#Age ");
                   12637:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   12638:   fprintf(ficrespl,"\n");
1.180     brouard  12639:   
1.219     brouard  12640:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  12641: 
1.219     brouard  12642:   agebase=ageminpar;
                   12643:   agelim=agemaxpar;
1.180     brouard  12644: 
1.227     brouard  12645:   /* i1=pow(2,ncoveff); */
1.234     brouard  12646:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  12647:   if (cptcovn < 1){i1=1;}
1.180     brouard  12648: 
1.337     brouard  12649:   /* for(k=1; k<=i1;k++){ /\* For each combination k of dummy covariates in the model *\/ */
1.238     brouard  12650:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  12651:       k=TKresult[nres];
1.338     brouard  12652:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12653:       /* if(i1 != 1 && TKresult[nres]!= k) /\* We found the combination k corresponding to the resultline value of dummies *\/ */
                   12654:       /*       continue; */
1.235     brouard  12655: 
1.238     brouard  12656:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12657:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   12658:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   12659:       /* k=k+1; */
                   12660:       /* to clean */
1.332     brouard  12661:       /*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*/
1.238     brouard  12662:       fprintf(ficrespl,"#******");
                   12663:       printf("#******");
                   12664:       fprintf(ficlog,"#******");
1.337     brouard  12665:       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  12666:        /* fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Here problem for varying dummy*\/ */
1.337     brouard  12667:        /* printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12668:        /* fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12669:        fprintf(ficrespl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12670:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12671:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12672:       }
                   12673:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   12674:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12675:       /*       fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12676:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12677:       /* } */
1.238     brouard  12678:       fprintf(ficrespl,"******\n");
                   12679:       printf("******\n");
                   12680:       fprintf(ficlog,"******\n");
                   12681:       if(invalidvarcomb[k]){
                   12682:        printf("\nCombination (%d) ignored because no case \n",k); 
                   12683:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   12684:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   12685:        continue;
                   12686:       }
1.219     brouard  12687: 
1.238     brouard  12688:       fprintf(ficrespl,"#Age ");
1.337     brouard  12689:       /* for(j=1;j<=cptcoveff;j++) { */
                   12690:       /*       fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12691:       /* } */
                   12692:       for(j=1;j<=cptcovs;j++) { /* New the quanti variable is added */
                   12693:        fprintf(ficrespl,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12694:       }
                   12695:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   12696:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  12697:     
1.238     brouard  12698:       for (age=agebase; age<=agelim; age++){
                   12699:        /* for (age=agebase; age<=agebase; age++){ */
1.337     brouard  12700:        /**< Computes the prevalence limit in each live state at age x and for covariate combination (k and) nres */
                   12701:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres); /* Nicely done */
1.238     brouard  12702:        fprintf(ficrespl,"%.0f ",age );
1.337     brouard  12703:        /* for(j=1;j<=cptcoveff;j++) */
                   12704:        /*   fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12705:        for(j=1;j<=cptcovs;j++)
                   12706:          fprintf(ficrespl,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12707:        tot=0.;
                   12708:        for(i=1; i<=nlstate;i++){
                   12709:          tot +=  prlim[i][i];
                   12710:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   12711:        }
                   12712:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   12713:       } /* Age */
                   12714:       /* was end of cptcod */
1.337     brouard  12715:     } /* nres */
                   12716:   /* } /\* for each combination *\/ */
1.219     brouard  12717:   return 0;
1.180     brouard  12718: }
                   12719: 
1.218     brouard  12720: 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  12721:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  12722:        
                   12723:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   12724:    * at any age between ageminpar and agemaxpar
                   12725:         */
1.235     brouard  12726:   int i, j, k, i1, nres=0 ;
1.217     brouard  12727:   /* double ftolpl = 1.e-10; */
                   12728:   double age, agebase, agelim;
                   12729:   double tot;
1.218     brouard  12730:   /* double ***mobaverage; */
                   12731:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  12732: 
                   12733:   strcpy(fileresplb,"PLB_");
                   12734:   strcat(fileresplb,fileresu);
                   12735:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  12736:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   12737:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  12738:   }
1.288     brouard  12739:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   12740:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  12741:   pstamp(ficresplb);
1.288     brouard  12742:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  12743:   fprintf(ficresplb,"#Age ");
                   12744:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   12745:   fprintf(ficresplb,"\n");
                   12746:   
1.218     brouard  12747:   
                   12748:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   12749:   
                   12750:   agebase=ageminpar;
                   12751:   agelim=agemaxpar;
                   12752:   
                   12753:   
1.227     brouard  12754:   i1=pow(2,cptcoveff);
1.218     brouard  12755:   if (cptcovn < 1){i1=1;}
1.227     brouard  12756:   
1.238     brouard  12757:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.338     brouard  12758:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   12759:       k=TKresult[nres];
                   12760:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   12761:      /* if(i1 != 1 && TKresult[nres]!= k) */
                   12762:      /*        continue; */
                   12763:      /* /\*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*\/ */
1.238     brouard  12764:       fprintf(ficresplb,"#******");
                   12765:       printf("#******");
                   12766:       fprintf(ficlog,"#******");
1.338     brouard  12767:       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) */
                   12768:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12769:        fprintf(ficresplb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12770:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12771:       }
1.338     brouard  12772:       /* for(j=1;j<=cptcoveff ;j++) {/\* all covariates *\/ */
                   12773:       /*       fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12774:       /*       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12775:       /*       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12776:       /* } */
                   12777:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   12778:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12779:       /*       fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12780:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12781:       /* } */
1.238     brouard  12782:       fprintf(ficresplb,"******\n");
                   12783:       printf("******\n");
                   12784:       fprintf(ficlog,"******\n");
                   12785:       if(invalidvarcomb[k]){
                   12786:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   12787:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   12788:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   12789:        continue;
                   12790:       }
1.218     brouard  12791:     
1.238     brouard  12792:       fprintf(ficresplb,"#Age ");
1.338     brouard  12793:       for(j=1;j<=cptcovs;j++) {
                   12794:        fprintf(ficresplb,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12795:       }
                   12796:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   12797:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  12798:     
                   12799:     
1.238     brouard  12800:       for (age=agebase; age<=agelim; age++){
                   12801:        /* for (age=agebase; age<=agebase; age++){ */
                   12802:        if(mobilavproj > 0){
                   12803:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   12804:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  12805:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  12806:        }else if (mobilavproj == 0){
                   12807:          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);
                   12808:          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);
                   12809:          exit(1);
                   12810:        }else{
                   12811:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  12812:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  12813:          /* printf("TOTOT\n"); */
                   12814:           /* exit(1); */
1.238     brouard  12815:        }
                   12816:        fprintf(ficresplb,"%.0f ",age );
1.338     brouard  12817:        for(j=1;j<=cptcovs;j++)
                   12818:          fprintf(ficresplb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12819:        tot=0.;
                   12820:        for(i=1; i<=nlstate;i++){
                   12821:          tot +=  bprlim[i][i];
                   12822:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   12823:        }
                   12824:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   12825:       } /* Age */
                   12826:       /* was end of cptcod */
1.255     brouard  12827:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.338     brouard  12828:     /* } /\* end of any combination *\/ */
1.238     brouard  12829:   } /* end of nres */  
1.218     brouard  12830:   /* hBijx(p, bage, fage); */
                   12831:   /* fclose(ficrespijb); */
                   12832:   
                   12833:   return 0;
1.217     brouard  12834: }
1.218     brouard  12835:  
1.180     brouard  12836: int hPijx(double *p, int bage, int fage){
                   12837:     /*------------- h Pij x at various ages ------------*/
1.336     brouard  12838:   /* to be optimized with precov */
1.180     brouard  12839:   int stepsize;
                   12840:   int agelim;
                   12841:   int hstepm;
                   12842:   int nhstepm;
1.235     brouard  12843:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  12844: 
                   12845:   double agedeb;
                   12846:   double ***p3mat;
                   12847: 
1.337     brouard  12848:   strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
                   12849:   if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   12850:     printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   12851:     fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   12852:   }
                   12853:   printf("Computing pij: result on file '%s' \n", filerespij);
                   12854:   fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   12855:   
                   12856:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   12857:   /*if (stepm<=24) stepsize=2;*/
                   12858:   
                   12859:   agelim=AGESUP;
                   12860:   hstepm=stepsize*YEARM; /* Every year of age */
                   12861:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   12862:   
                   12863:   /* hstepm=1;   aff par mois*/
                   12864:   pstamp(ficrespij);
                   12865:   fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   12866:   i1= pow(2,cptcoveff);
                   12867:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12868:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   12869:   /*   k=k+1;  */
                   12870:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   12871:     k=TKresult[nres];
1.338     brouard  12872:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12873:     /* for(k=1; k<=i1;k++){ */
                   12874:     /* if(i1 != 1 && TKresult[nres]!= k) */
                   12875:     /*         continue; */
                   12876:     fprintf(ficrespij,"\n#****** ");
                   12877:     for(j=1;j<=cptcovs;j++){
                   12878:       fprintf(ficrespij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12879:       /* fprintf(ficrespij,"@wV%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12880:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   12881:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12882:       /*       fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12883:     }
                   12884:     fprintf(ficrespij,"******\n");
                   12885:     
                   12886:     for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   12887:       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   12888:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   12889:       
                   12890:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   12891:       
                   12892:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12893:       oldm=oldms;savm=savms;
                   12894:       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
                   12895:       fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   12896:       for(i=1; i<=nlstate;i++)
                   12897:        for(j=1; j<=nlstate+ndeath;j++)
                   12898:          fprintf(ficrespij," %1d-%1d",i,j);
                   12899:       fprintf(ficrespij,"\n");
                   12900:       for (h=0; h<=nhstepm; h++){
                   12901:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   12902:        fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.183     brouard  12903:        for(i=1; i<=nlstate;i++)
                   12904:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  12905:            fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.183     brouard  12906:        fprintf(ficrespij,"\n");
                   12907:       }
1.337     brouard  12908:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12909:       fprintf(ficrespij,"\n");
1.180     brouard  12910:     }
1.337     brouard  12911:   }
                   12912:   /*}*/
                   12913:   return 0;
1.180     brouard  12914: }
1.218     brouard  12915:  
                   12916:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  12917:     /*------------- h Bij x at various ages ------------*/
1.336     brouard  12918:     /* To be optimized with precov */
1.217     brouard  12919:   int stepsize;
1.218     brouard  12920:   /* int agelim; */
                   12921:        int ageminl;
1.217     brouard  12922:   int hstepm;
                   12923:   int nhstepm;
1.238     brouard  12924:   int h, i, i1, j, k, nres;
1.218     brouard  12925:        
1.217     brouard  12926:   double agedeb;
                   12927:   double ***p3mat;
1.218     brouard  12928:        
                   12929:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   12930:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   12931:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   12932:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   12933:   }
                   12934:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   12935:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   12936:   
                   12937:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   12938:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  12939:   
1.218     brouard  12940:   /* agelim=AGESUP; */
1.289     brouard  12941:   ageminl=AGEINF; /* was 30 */
1.218     brouard  12942:   hstepm=stepsize*YEARM; /* Every year of age */
                   12943:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   12944:   
                   12945:   /* hstepm=1;   aff par mois*/
                   12946:   pstamp(ficrespijb);
1.255     brouard  12947:   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  12948:   i1= pow(2,cptcoveff);
1.218     brouard  12949:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12950:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   12951:   /*   k=k+1;  */
1.238     brouard  12952:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  12953:     k=TKresult[nres];
1.338     brouard  12954:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12955:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   12956:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   12957:     /*         continue; */
                   12958:     fprintf(ficrespijb,"\n#****** ");
                   12959:     for(j=1;j<=cptcovs;j++){
1.338     brouard  12960:       fprintf(ficrespijb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.337     brouard  12961:       /* for(j=1;j<=cptcoveff;j++) */
                   12962:       /*       fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12963:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   12964:       /*       fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12965:     }
                   12966:     fprintf(ficrespijb,"******\n");
                   12967:     if(invalidvarcomb[k]){  /* Is it necessary here? */
                   12968:       fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   12969:       continue;
                   12970:     }
                   12971:     
                   12972:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   12973:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   12974:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   12975:       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 */
                   12976:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
                   12977:       
                   12978:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   12979:       
                   12980:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   12981:       /* and memory limitations if stepm is small */
                   12982:       
                   12983:       /* oldm=oldms;savm=savms; */
                   12984:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   12985:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);/* Bug valgrind */
                   12986:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
                   12987:       fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
                   12988:       for(i=1; i<=nlstate;i++)
                   12989:        for(j=1; j<=nlstate+ndeath;j++)
                   12990:          fprintf(ficrespijb," %1d-%1d",i,j);
                   12991:       fprintf(ficrespijb,"\n");
                   12992:       for (h=0; h<=nhstepm; h++){
                   12993:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   12994:        fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   12995:        /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
1.217     brouard  12996:        for(i=1; i<=nlstate;i++)
                   12997:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  12998:            fprintf(ficrespijb," %.5f", p3mat[i][j][h]);/* Bug valgrind */
1.217     brouard  12999:        fprintf(ficrespijb,"\n");
1.337     brouard  13000:       }
                   13001:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   13002:       fprintf(ficrespijb,"\n");
                   13003:     } /* end age deb */
                   13004:     /* } /\* end combination *\/ */
1.238     brouard  13005:   } /* end nres */
1.218     brouard  13006:   return 0;
                   13007:  } /*  hBijx */
1.217     brouard  13008: 
1.180     brouard  13009: 
1.136     brouard  13010: /***********************************************/
                   13011: /**************** Main Program *****************/
                   13012: /***********************************************/
                   13013: 
                   13014: int main(int argc, char *argv[])
                   13015: {
                   13016: #ifdef GSL
                   13017:   const gsl_multimin_fminimizer_type *T;
                   13018:   size_t iteri = 0, it;
                   13019:   int rval = GSL_CONTINUE;
                   13020:   int status = GSL_SUCCESS;
                   13021:   double ssval;
                   13022: #endif
                   13023:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  13024:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   13025:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  13026:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  13027:   int jj, ll, li, lj, lk;
1.136     brouard  13028:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  13029:   int num_filled;
1.136     brouard  13030:   int itimes;
                   13031:   int NDIM=2;
                   13032:   int vpopbased=0;
1.235     brouard  13033:   int nres=0;
1.258     brouard  13034:   int endishere=0;
1.277     brouard  13035:   int noffset=0;
1.274     brouard  13036:   int ncurrv=0; /* Temporary variable */
                   13037:   
1.164     brouard  13038:   char ca[32], cb[32];
1.136     brouard  13039:   /*  FILE *fichtm; *//* Html File */
                   13040:   /* FILE *ficgp;*/ /*Gnuplot File */
                   13041:   struct stat info;
1.191     brouard  13042:   double agedeb=0.;
1.194     brouard  13043: 
                   13044:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  13045:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  13046: 
1.165     brouard  13047:   double fret;
1.191     brouard  13048:   double dum=0.; /* Dummy variable */
1.136     brouard  13049:   double ***p3mat;
1.218     brouard  13050:   /* double ***mobaverage; */
1.319     brouard  13051:   double wald;
1.164     brouard  13052: 
1.351     brouard  13053:   char line[MAXLINE], linetmp[MAXLINE];
1.197     brouard  13054:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   13055: 
1.234     brouard  13056:   char  modeltemp[MAXLINE];
1.332     brouard  13057:   char resultline[MAXLINE], resultlineori[MAXLINE];
1.230     brouard  13058:   
1.136     brouard  13059:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  13060:   char *tok, *val; /* pathtot */
1.334     brouard  13061:   /* int firstobs=1, lastobs=10; /\* nobs = lastobs-firstobs declared globally ;*\/ */
1.195     brouard  13062:   int c,  h , cpt, c2;
1.191     brouard  13063:   int jl=0;
                   13064:   int i1, j1, jk, stepsize=0;
1.194     brouard  13065:   int count=0;
                   13066: 
1.164     brouard  13067:   int *tab; 
1.136     brouard  13068:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  13069:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   13070:   /* double anprojf, mprojf, jprojf; */
                   13071:   /* double jintmean,mintmean,aintmean;   */
                   13072:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   13073:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   13074:   double yrfproj= 10.0; /* Number of years of forward projections */
                   13075:   double yrbproj= 10.0; /* Number of years of backward projections */
                   13076:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  13077:   int mobilav=0,popforecast=0;
1.191     brouard  13078:   int hstepm=0, nhstepm=0;
1.136     brouard  13079:   int agemortsup;
                   13080:   float  sumlpop=0.;
                   13081:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   13082:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   13083: 
1.191     brouard  13084:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  13085:   double ftolpl=FTOL;
                   13086:   double **prlim;
1.217     brouard  13087:   double **bprlim;
1.317     brouard  13088:   double ***param; /* Matrix of parameters, param[i][j][k] param=ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel) 
                   13089:                     state of origin, state of destination including death, for each covariate: constante, age, and V1 V2 etc. */
1.251     brouard  13090:   double ***paramstart; /* Matrix of starting parameter values */
                   13091:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  13092:   double **matcov; /* Matrix of covariance */
1.203     brouard  13093:   double **hess; /* Hessian matrix */
1.136     brouard  13094:   double ***delti3; /* Scale */
                   13095:   double *delti; /* Scale */
                   13096:   double ***eij, ***vareij;
                   13097:   double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  13098: 
1.136     brouard  13099:   double *epj, vepp;
1.164     brouard  13100: 
1.273     brouard  13101:   double dateprev1, dateprev2;
1.296     brouard  13102:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   13103:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   13104: 
1.217     brouard  13105: 
1.136     brouard  13106:   double **ximort;
1.145     brouard  13107:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  13108:   int *dcwave;
                   13109: 
1.164     brouard  13110:   char z[1]="c";
1.136     brouard  13111: 
                   13112:   /*char  *strt;*/
                   13113:   char strtend[80];
1.126     brouard  13114: 
1.164     brouard  13115: 
1.126     brouard  13116: /*   setlocale (LC_ALL, ""); */
                   13117: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   13118: /*   textdomain (PACKAGE); */
                   13119: /*   setlocale (LC_CTYPE, ""); */
                   13120: /*   setlocale (LC_MESSAGES, ""); */
                   13121: 
                   13122:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  13123:   rstart_time = time(NULL);  
                   13124:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   13125:   start_time = *localtime(&rstart_time);
1.126     brouard  13126:   curr_time=start_time;
1.157     brouard  13127:   /*tml = *localtime(&start_time.tm_sec);*/
                   13128:   /* strcpy(strstart,asctime(&tml)); */
                   13129:   strcpy(strstart,asctime(&start_time));
1.126     brouard  13130: 
                   13131: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  13132: /*  tp.tm_sec = tp.tm_sec +86400; */
                   13133: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  13134: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   13135: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   13136: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  13137: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  13138: /*   strt=asctime(&tmg); */
                   13139: /*   printf("Time(after) =%s",strstart);  */
                   13140: /*  (void) time (&time_value);
                   13141: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   13142: *  tm = *localtime(&time_value);
                   13143: *  strstart=asctime(&tm);
                   13144: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   13145: */
                   13146: 
                   13147:   nberr=0; /* Number of errors and warnings */
                   13148:   nbwarn=0;
1.184     brouard  13149: #ifdef WIN32
                   13150:   _getcwd(pathcd, size);
                   13151: #else
1.126     brouard  13152:   getcwd(pathcd, size);
1.184     brouard  13153: #endif
1.191     brouard  13154:   syscompilerinfo(0);
1.196     brouard  13155:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  13156:   if(argc <=1){
                   13157:     printf("\nEnter the parameter file name: ");
1.205     brouard  13158:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   13159:       printf("ERROR Empty parameter file name\n");
                   13160:       goto end;
                   13161:     }
1.126     brouard  13162:     i=strlen(pathr);
                   13163:     if(pathr[i-1]=='\n')
                   13164:       pathr[i-1]='\0';
1.156     brouard  13165:     i=strlen(pathr);
1.205     brouard  13166:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  13167:       pathr[i-1]='\0';
1.205     brouard  13168:     }
                   13169:     i=strlen(pathr);
                   13170:     if( i==0 ){
                   13171:       printf("ERROR Empty parameter file name\n");
                   13172:       goto end;
                   13173:     }
                   13174:     for (tok = pathr; tok != NULL; ){
1.126     brouard  13175:       printf("Pathr |%s|\n",pathr);
                   13176:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   13177:       printf("val= |%s| pathr=%s\n",val,pathr);
                   13178:       strcpy (pathtot, val);
                   13179:       if(pathr[0] == '\0') break; /* Dirty */
                   13180:     }
                   13181:   }
1.281     brouard  13182:   else if (argc<=2){
                   13183:     strcpy(pathtot,argv[1]);
                   13184:   }
1.126     brouard  13185:   else{
                   13186:     strcpy(pathtot,argv[1]);
1.281     brouard  13187:     strcpy(z,argv[2]);
                   13188:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  13189:   }
                   13190:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   13191:   /*cygwin_split_path(pathtot,path,optionfile);
                   13192:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   13193:   /* cutv(path,optionfile,pathtot,'\\');*/
                   13194: 
                   13195:   /* Split argv[0], imach program to get pathimach */
                   13196:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   13197:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   13198:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   13199:  /*   strcpy(pathimach,argv[0]); */
                   13200:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   13201:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   13202:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  13203: #ifdef WIN32
                   13204:   _chdir(path); /* Can be a relative path */
                   13205:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   13206: #else
1.126     brouard  13207:   chdir(path); /* Can be a relative path */
1.184     brouard  13208:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   13209: #endif
                   13210:   printf("Current directory %s!\n",pathcd);
1.126     brouard  13211:   strcpy(command,"mkdir ");
                   13212:   strcat(command,optionfilefiname);
                   13213:   if((outcmd=system(command)) != 0){
1.169     brouard  13214:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  13215:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   13216:     /* fclose(ficlog); */
                   13217: /*     exit(1); */
                   13218:   }
                   13219: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   13220: /*     perror("mkdir"); */
                   13221: /*   } */
                   13222: 
                   13223:   /*-------- arguments in the command line --------*/
                   13224: 
1.186     brouard  13225:   /* Main Log file */
1.126     brouard  13226:   strcat(filelog, optionfilefiname);
                   13227:   strcat(filelog,".log");    /* */
                   13228:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   13229:     printf("Problem with logfile %s\n",filelog);
                   13230:     goto end;
                   13231:   }
                   13232:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  13233:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  13234:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   13235:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   13236:  path=%s \n\
                   13237:  optionfile=%s\n\
                   13238:  optionfilext=%s\n\
1.156     brouard  13239:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  13240: 
1.197     brouard  13241:   syscompilerinfo(1);
1.167     brouard  13242: 
1.126     brouard  13243:   printf("Local time (at start):%s",strstart);
                   13244:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   13245:   fflush(ficlog);
                   13246: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  13247: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  13248: 
                   13249:   /* */
                   13250:   strcpy(fileres,"r");
                   13251:   strcat(fileres, optionfilefiname);
1.201     brouard  13252:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  13253:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  13254:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  13255: 
1.186     brouard  13256:   /* Main ---------arguments file --------*/
1.126     brouard  13257: 
                   13258:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  13259:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   13260:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  13261:     fflush(ficlog);
1.149     brouard  13262:     /* goto end; */
                   13263:     exit(70); 
1.126     brouard  13264:   }
                   13265: 
                   13266:   strcpy(filereso,"o");
1.201     brouard  13267:   strcat(filereso,fileresu);
1.126     brouard  13268:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   13269:     printf("Problem with Output resultfile: %s\n", filereso);
                   13270:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   13271:     fflush(ficlog);
                   13272:     goto end;
                   13273:   }
1.278     brouard  13274:       /*-------- Rewriting parameter file ----------*/
                   13275:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   13276:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   13277:   strcat(rfileres,".");    /* */
                   13278:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   13279:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   13280:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   13281:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   13282:     fflush(ficlog);
                   13283:     goto end;
                   13284:   }
                   13285:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  13286: 
1.278     brouard  13287:                                      
1.126     brouard  13288:   /* Reads comments: lines beginning with '#' */
                   13289:   numlinepar=0;
1.277     brouard  13290:   /* Is it a BOM UTF-8 Windows file? */
                   13291:   /* First parameter line */
1.197     brouard  13292:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  13293:     noffset=0;
                   13294:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   13295:     {
                   13296:       noffset=noffset+3;
                   13297:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   13298:     }
1.302     brouard  13299: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   13300:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
1.277     brouard  13301:     {
                   13302:       noffset=noffset+2;
                   13303:       printf("# File is an UTF16BE BOM file\n");
                   13304:     }
                   13305:     else if( line[0] == 0 && line[1] == 0)
                   13306:     {
                   13307:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   13308:        noffset=noffset+4;
                   13309:        printf("# File is an UTF16BE BOM file\n");
                   13310:       }
                   13311:     } else{
                   13312:       ;/*printf(" Not a BOM file\n");*/
                   13313:     }
                   13314:   
1.197     brouard  13315:     /* If line starts with a # it is a comment */
1.277     brouard  13316:     if (line[noffset] == '#') {
1.197     brouard  13317:       numlinepar++;
                   13318:       fputs(line,stdout);
                   13319:       fputs(line,ficparo);
1.278     brouard  13320:       fputs(line,ficres);
1.197     brouard  13321:       fputs(line,ficlog);
                   13322:       continue;
                   13323:     }else
                   13324:       break;
                   13325:   }
                   13326:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   13327:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   13328:     if (num_filled != 5) {
                   13329:       printf("Should be 5 parameters\n");
1.283     brouard  13330:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  13331:     }
1.126     brouard  13332:     numlinepar++;
1.197     brouard  13333:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  13334:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   13335:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   13336:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  13337:   }
                   13338:   /* Second parameter line */
                   13339:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  13340:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   13341:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  13342:     if (line[0] == '#') {
                   13343:       numlinepar++;
1.283     brouard  13344:       printf("%s",line);
                   13345:       fprintf(ficres,"%s",line);
                   13346:       fprintf(ficparo,"%s",line);
                   13347:       fprintf(ficlog,"%s",line);
1.197     brouard  13348:       continue;
                   13349:     }else
                   13350:       break;
                   13351:   }
1.223     brouard  13352:   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", \
                   13353:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   13354:     if (num_filled != 11) {
                   13355:       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  13356:       printf("but line=%s\n",line);
1.283     brouard  13357:       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");
                   13358:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  13359:     }
1.286     brouard  13360:     if( lastpass > maxwav){
                   13361:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   13362:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   13363:       fflush(ficlog);
                   13364:       goto end;
                   13365:     }
                   13366:       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  13367:     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  13368:     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  13369:     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  13370:   }
1.203     brouard  13371:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  13372:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  13373:   /* Third parameter line */
                   13374:   while(fgets(line, MAXLINE, ficpar)) {
                   13375:     /* If line starts with a # it is a comment */
                   13376:     if (line[0] == '#') {
                   13377:       numlinepar++;
1.283     brouard  13378:       printf("%s",line);
                   13379:       fprintf(ficres,"%s",line);
                   13380:       fprintf(ficparo,"%s",line);
                   13381:       fprintf(ficlog,"%s",line);
1.197     brouard  13382:       continue;
                   13383:     }else
                   13384:       break;
                   13385:   }
1.351     brouard  13386:   if((num_filled=sscanf(line,"model=%[^.\n]", model)) !=EOF){ /* Every character after model but dot and  return */
                   13387:     if (num_filled != 1){
                   13388:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   13389:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   13390:       model[0]='\0';
                   13391:       goto end;
                   13392:     }else{
                   13393:       trimbtab(linetmp,line); /* Trims multiple blanks in line */
                   13394:       strcpy(line, linetmp);
                   13395:     }
                   13396:   }
                   13397:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){ /* Every character after 1+age but dot and  return */
1.279     brouard  13398:     if (num_filled != 1){
1.302     brouard  13399:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   13400:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
1.197     brouard  13401:       model[0]='\0';
                   13402:       goto end;
                   13403:     }
                   13404:     else{
                   13405:       if (model[0]=='+'){
                   13406:        for(i=1; i<=strlen(model);i++)
                   13407:          modeltemp[i-1]=model[i];
1.201     brouard  13408:        strcpy(model,modeltemp); 
1.197     brouard  13409:       }
                   13410:     }
1.338     brouard  13411:     /* printf(" model=1+age%s modeltemp= %s, model=1+age+%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  13412:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  13413:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   13414:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   13415:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  13416:   }
                   13417:   /* 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); */
                   13418:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   13419:   /* 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  13420:   /* 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); */
                   13421:   /* 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  13422:   fflush(ficlog);
1.190     brouard  13423:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   13424:   if(model[0]=='#'){
1.279     brouard  13425:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   13426:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   13427:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  13428:     if(mle != -1){
1.279     brouard  13429:       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  13430:       exit(1);
                   13431:     }
                   13432:   }
1.126     brouard  13433:   while((c=getc(ficpar))=='#' && c!= EOF){
                   13434:     ungetc(c,ficpar);
                   13435:     fgets(line, MAXLINE, ficpar);
                   13436:     numlinepar++;
1.195     brouard  13437:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   13438:       z[0]=line[1];
1.342     brouard  13439:     }else if(line[1]=='d'){ /* For debugging individual values of covariates in ficresilk */
1.343     brouard  13440:       debugILK=1;printf("DebugILK\n");
1.195     brouard  13441:     }
                   13442:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  13443:     fputs(line, stdout);
                   13444:     //puts(line);
1.126     brouard  13445:     fputs(line,ficparo);
                   13446:     fputs(line,ficlog);
                   13447:   }
                   13448:   ungetc(c,ficpar);
                   13449: 
                   13450:    
1.290     brouard  13451:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   13452:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   13453:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
1.341     brouard  13454:   /* if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /\**< Time varying covariate (dummy and quantitative)*\/ */
                   13455:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);  /**< Might be better */
1.136     brouard  13456:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   13457:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   13458:      v1+v2*age+v2*v3 makes cptcovn = 3
                   13459:   */
                   13460:   if (strlen(model)>1) 
1.187     brouard  13461:     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  13462:   else
1.187     brouard  13463:     ncovmodel=2; /* Constant and age */
1.133     brouard  13464:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   13465:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  13466:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   13467:     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);
                   13468:     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);
                   13469:     fflush(stdout);
                   13470:     fclose (ficlog);
                   13471:     goto end;
                   13472:   }
1.126     brouard  13473:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   13474:   delti=delti3[1][1];
                   13475:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   13476:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  13477: /* We could also provide initial parameters values giving by simple logistic regression 
                   13478:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   13479:       /* for(i=1;i<nlstate;i++){ */
                   13480:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   13481:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   13482:       /* } */
1.126     brouard  13483:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  13484:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   13485:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  13486:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   13487:     fclose (ficparo);
                   13488:     fclose (ficlog);
                   13489:     goto end;
                   13490:     exit(0);
1.220     brouard  13491:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  13492:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  13493:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   13494:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  13495:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   13496:     matcov=matrix(1,npar,1,npar);
1.203     brouard  13497:     hess=matrix(1,npar,1,npar);
1.220     brouard  13498:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  13499:     /* Read guessed parameters */
1.126     brouard  13500:     /* Reads comments: lines beginning with '#' */
                   13501:     while((c=getc(ficpar))=='#' && c!= EOF){
                   13502:       ungetc(c,ficpar);
                   13503:       fgets(line, MAXLINE, ficpar);
                   13504:       numlinepar++;
1.141     brouard  13505:       fputs(line,stdout);
1.126     brouard  13506:       fputs(line,ficparo);
                   13507:       fputs(line,ficlog);
                   13508:     }
                   13509:     ungetc(c,ficpar);
                   13510:     
                   13511:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  13512:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  13513:     for(i=1; i <=nlstate; i++){
1.234     brouard  13514:       j=0;
1.126     brouard  13515:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  13516:        if(jj==i) continue;
                   13517:        j++;
1.292     brouard  13518:        while((c=getc(ficpar))=='#' && c!= EOF){
                   13519:          ungetc(c,ficpar);
                   13520:          fgets(line, MAXLINE, ficpar);
                   13521:          numlinepar++;
                   13522:          fputs(line,stdout);
                   13523:          fputs(line,ficparo);
                   13524:          fputs(line,ficlog);
                   13525:        }
                   13526:        ungetc(c,ficpar);
1.234     brouard  13527:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   13528:        if ((i1 != i) || (j1 != jj)){
                   13529:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  13530: It might be a problem of design; if ncovcol and the model are correct\n \
                   13531: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  13532:          exit(1);
                   13533:        }
                   13534:        fprintf(ficparo,"%1d%1d",i1,j1);
                   13535:        if(mle==1)
                   13536:          printf("%1d%1d",i,jj);
                   13537:        fprintf(ficlog,"%1d%1d",i,jj);
                   13538:        for(k=1; k<=ncovmodel;k++){
                   13539:          fscanf(ficpar," %lf",&param[i][j][k]);
                   13540:          if(mle==1){
                   13541:            printf(" %lf",param[i][j][k]);
                   13542:            fprintf(ficlog," %lf",param[i][j][k]);
                   13543:          }
                   13544:          else
                   13545:            fprintf(ficlog," %lf",param[i][j][k]);
                   13546:          fprintf(ficparo," %lf",param[i][j][k]);
                   13547:        }
                   13548:        fscanf(ficpar,"\n");
                   13549:        numlinepar++;
                   13550:        if(mle==1)
                   13551:          printf("\n");
                   13552:        fprintf(ficlog,"\n");
                   13553:        fprintf(ficparo,"\n");
1.126     brouard  13554:       }
                   13555:     }  
                   13556:     fflush(ficlog);
1.234     brouard  13557:     
1.251     brouard  13558:     /* Reads parameters values */
1.126     brouard  13559:     p=param[1][1];
1.251     brouard  13560:     pstart=paramstart[1][1];
1.126     brouard  13561:     
                   13562:     /* Reads comments: lines beginning with '#' */
                   13563:     while((c=getc(ficpar))=='#' && c!= EOF){
                   13564:       ungetc(c,ficpar);
                   13565:       fgets(line, MAXLINE, ficpar);
                   13566:       numlinepar++;
1.141     brouard  13567:       fputs(line,stdout);
1.126     brouard  13568:       fputs(line,ficparo);
                   13569:       fputs(line,ficlog);
                   13570:     }
                   13571:     ungetc(c,ficpar);
                   13572: 
                   13573:     for(i=1; i <=nlstate; i++){
                   13574:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  13575:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   13576:        if ( (i1-i) * (j1-j) != 0){
                   13577:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   13578:          exit(1);
                   13579:        }
                   13580:        printf("%1d%1d",i,j);
                   13581:        fprintf(ficparo,"%1d%1d",i1,j1);
                   13582:        fprintf(ficlog,"%1d%1d",i1,j1);
                   13583:        for(k=1; k<=ncovmodel;k++){
                   13584:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   13585:          printf(" %le",delti3[i][j][k]);
                   13586:          fprintf(ficparo," %le",delti3[i][j][k]);
                   13587:          fprintf(ficlog," %le",delti3[i][j][k]);
                   13588:        }
                   13589:        fscanf(ficpar,"\n");
                   13590:        numlinepar++;
                   13591:        printf("\n");
                   13592:        fprintf(ficparo,"\n");
                   13593:        fprintf(ficlog,"\n");
1.126     brouard  13594:       }
                   13595:     }
                   13596:     fflush(ficlog);
1.234     brouard  13597:     
1.145     brouard  13598:     /* Reads covariance matrix */
1.126     brouard  13599:     delti=delti3[1][1];
1.220     brouard  13600:                
                   13601:                
1.126     brouard  13602:     /* 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  13603:                
1.126     brouard  13604:     /* Reads comments: lines beginning with '#' */
                   13605:     while((c=getc(ficpar))=='#' && c!= EOF){
                   13606:       ungetc(c,ficpar);
                   13607:       fgets(line, MAXLINE, ficpar);
                   13608:       numlinepar++;
1.141     brouard  13609:       fputs(line,stdout);
1.126     brouard  13610:       fputs(line,ficparo);
                   13611:       fputs(line,ficlog);
                   13612:     }
                   13613:     ungetc(c,ficpar);
1.220     brouard  13614:                
1.126     brouard  13615:     matcov=matrix(1,npar,1,npar);
1.203     brouard  13616:     hess=matrix(1,npar,1,npar);
1.131     brouard  13617:     for(i=1; i <=npar; i++)
                   13618:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  13619:                
1.194     brouard  13620:     /* Scans npar lines */
1.126     brouard  13621:     for(i=1; i <=npar; i++){
1.226     brouard  13622:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  13623:       if(count != 3){
1.226     brouard  13624:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  13625: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   13626: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  13627:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  13628: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   13629: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  13630:        exit(1);
1.220     brouard  13631:       }else{
1.226     brouard  13632:        if(mle==1)
                   13633:          printf("%1d%1d%d",i1,j1,jk);
                   13634:       }
                   13635:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   13636:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  13637:       for(j=1; j <=i; j++){
1.226     brouard  13638:        fscanf(ficpar," %le",&matcov[i][j]);
                   13639:        if(mle==1){
                   13640:          printf(" %.5le",matcov[i][j]);
                   13641:        }
                   13642:        fprintf(ficlog," %.5le",matcov[i][j]);
                   13643:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  13644:       }
                   13645:       fscanf(ficpar,"\n");
                   13646:       numlinepar++;
                   13647:       if(mle==1)
1.220     brouard  13648:                                printf("\n");
1.126     brouard  13649:       fprintf(ficlog,"\n");
                   13650:       fprintf(ficparo,"\n");
                   13651:     }
1.194     brouard  13652:     /* End of read covariance matrix npar lines */
1.126     brouard  13653:     for(i=1; i <=npar; i++)
                   13654:       for(j=i+1;j<=npar;j++)
1.226     brouard  13655:        matcov[i][j]=matcov[j][i];
1.126     brouard  13656:     
                   13657:     if(mle==1)
                   13658:       printf("\n");
                   13659:     fprintf(ficlog,"\n");
                   13660:     
                   13661:     fflush(ficlog);
                   13662:     
                   13663:   }    /* End of mle != -3 */
1.218     brouard  13664:   
1.186     brouard  13665:   /*  Main data
                   13666:    */
1.290     brouard  13667:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   13668:   /* num=lvector(1,n); */
                   13669:   /* moisnais=vector(1,n); */
                   13670:   /* annais=vector(1,n); */
                   13671:   /* moisdc=vector(1,n); */
                   13672:   /* andc=vector(1,n); */
                   13673:   /* weight=vector(1,n); */
                   13674:   /* agedc=vector(1,n); */
                   13675:   /* cod=ivector(1,n); */
                   13676:   /* for(i=1;i<=n;i++){ */
                   13677:   num=lvector(firstobs,lastobs);
                   13678:   moisnais=vector(firstobs,lastobs);
                   13679:   annais=vector(firstobs,lastobs);
                   13680:   moisdc=vector(firstobs,lastobs);
                   13681:   andc=vector(firstobs,lastobs);
                   13682:   weight=vector(firstobs,lastobs);
                   13683:   agedc=vector(firstobs,lastobs);
                   13684:   cod=ivector(firstobs,lastobs);
                   13685:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  13686:     num[i]=0;
                   13687:     moisnais[i]=0;
                   13688:     annais[i]=0;
                   13689:     moisdc[i]=0;
                   13690:     andc[i]=0;
                   13691:     agedc[i]=0;
                   13692:     cod[i]=0;
                   13693:     weight[i]=1.0; /* Equal weights, 1 by default */
                   13694:   }
1.290     brouard  13695:   mint=matrix(1,maxwav,firstobs,lastobs);
                   13696:   anint=matrix(1,maxwav,firstobs,lastobs);
1.325     brouard  13697:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */
1.336     brouard  13698:   /* printf("BUG ncovmodel=%d NCOVMAX=%d 2**ncovmodel=%f BUG\n",ncovmodel,NCOVMAX,pow(2,ncovmodel)); */
1.126     brouard  13699:   tab=ivector(1,NCOVMAX);
1.144     brouard  13700:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  13701:   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  13702: 
1.136     brouard  13703:   /* Reads data from file datafile */
                   13704:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   13705:     goto end;
                   13706: 
                   13707:   /* Calculation of the number of parameters from char model */
1.234     brouard  13708:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  13709:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   13710:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   13711:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   13712:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  13713:   */
                   13714:   
                   13715:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   13716:   TvarsDind=ivector(1,NCOVMAX); /*  */
1.330     brouard  13717:   TnsdVar=ivector(1,NCOVMAX); /*  */
1.335     brouard  13718:     /* for(i=1; i<=NCOVMAX;i++) TnsdVar[i]=3; */
1.234     brouard  13719:   TvarsD=ivector(1,NCOVMAX); /*  */
                   13720:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   13721:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  13722:   TvarF=ivector(1,NCOVMAX); /*  */
                   13723:   TvarFind=ivector(1,NCOVMAX); /*  */
                   13724:   TvarV=ivector(1,NCOVMAX); /*  */
                   13725:   TvarVind=ivector(1,NCOVMAX); /*  */
                   13726:   TvarA=ivector(1,NCOVMAX); /*  */
                   13727:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  13728:   TvarFD=ivector(1,NCOVMAX); /*  */
                   13729:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   13730:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   13731:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   13732:   TvarVD=ivector(1,NCOVMAX); /*  */
                   13733:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   13734:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   13735:   TvarVQind=ivector(1,NCOVMAX); /*  */
1.339     brouard  13736:   TvarVV=ivector(1,NCOVMAX); /*  */
                   13737:   TvarVVind=ivector(1,NCOVMAX); /*  */
1.349     brouard  13738:   TvarVVA=ivector(1,NCOVMAX); /*  */
                   13739:   TvarVVAind=ivector(1,NCOVMAX); /*  */
                   13740:   TvarAVVA=ivector(1,NCOVMAX); /*  */
                   13741:   TvarAVVAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  13742: 
1.230     brouard  13743:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  13744:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  13745:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   13746:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   13747:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.349     brouard  13748:   DummyV=ivector(-1,NCOVMAX); /* 1 to 3 */
                   13749:   FixedV=ivector(-1,NCOVMAX); /* 1 to 3 */
                   13750: 
1.137     brouard  13751:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   13752:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   13753:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   13754:   */
                   13755:   /* For model-covariate k tells which data-covariate to use but
                   13756:     because this model-covariate is a construction we invent a new column
                   13757:     ncovcol + k1
                   13758:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   13759:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  13760:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   13761:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  13762:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   13763:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  13764:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  13765:   */
1.145     brouard  13766:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   13767:   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  13768:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   13769:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.351     brouard  13770:   Tvardk=imatrix(0,NCOVMAX,1,2);
1.145     brouard  13771:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  13772:                         4 covariates (3 plus signs)
                   13773:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
1.328     brouard  13774:                           */  
                   13775:   for(i=1;i<NCOVMAX;i++)
                   13776:     Tage[i]=0;
1.230     brouard  13777:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  13778:                                * individual dummy, fixed or varying:
                   13779:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   13780:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  13781:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   13782:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   13783:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   13784:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   13785:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  13786:                                * individual quantitative, fixed or varying:
                   13787:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   13788:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   13789:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.349     brouard  13790: 
                   13791: /* Probably useless zeroes */
                   13792:   for(i=1;i<NCOVMAX;i++){
                   13793:     DummyV[i]=0;
                   13794:     FixedV[i]=0;
                   13795:   }
                   13796: 
                   13797:   for(i=1; i <=ncovcol;i++){
                   13798:     DummyV[i]=0;
                   13799:     FixedV[i]=0;
                   13800:   }
                   13801:   for(i=ncovcol+1; i <=ncovcol+nqv;i++){
                   13802:     DummyV[i]=1;
                   13803:     FixedV[i]=0;
                   13804:   }
                   13805:   for(i=ncovcol+nqv+1; i <=ncovcol+nqv+ntv;i++){
                   13806:     DummyV[i]=0;
                   13807:     FixedV[i]=1;
                   13808:   }
                   13809:   for(i=ncovcol+nqv+ntv+1; i <=ncovcol+nqv+ntv+nqtv;i++){
                   13810:     DummyV[i]=1;
                   13811:     FixedV[i]=1;
                   13812:   }
                   13813:   for(i=1; i <=ncovcol+nqv+ntv+nqtv;i++){
                   13814:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",i,i,DummyV[i],i,FixedV[i]);
                   13815:     fprintf(ficlog,"Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",i,i,DummyV[i],i,FixedV[i]);
                   13816:   }
                   13817: 
                   13818: 
                   13819: 
1.186     brouard  13820: /* Main decodemodel */
                   13821: 
1.187     brouard  13822: 
1.223     brouard  13823:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  13824:     goto end;
                   13825: 
1.137     brouard  13826:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   13827:     nbwarn++;
                   13828:     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); 
                   13829:     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); 
                   13830:   }
1.136     brouard  13831:     /*  if(mle==1){*/
1.137     brouard  13832:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   13833:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  13834:   }
                   13835: 
                   13836:     /*-calculation of age at interview from date of interview and age at death -*/
                   13837:   agev=matrix(1,maxwav,1,imx);
                   13838: 
                   13839:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   13840:     goto end;
                   13841: 
1.126     brouard  13842: 
1.136     brouard  13843:   agegomp=(int)agemin;
1.290     brouard  13844:   free_vector(moisnais,firstobs,lastobs);
                   13845:   free_vector(annais,firstobs,lastobs);
1.126     brouard  13846:   /* free_matrix(mint,1,maxwav,1,n);
                   13847:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  13848:   /* free_vector(moisdc,1,n); */
                   13849:   /* free_vector(andc,1,n); */
1.145     brouard  13850:   /* */
                   13851:   
1.126     brouard  13852:   wav=ivector(1,imx);
1.214     brouard  13853:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13854:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13855:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13856:   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.*/
                   13857:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   13858:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  13859:    
                   13860:   /* Concatenates waves */
1.214     brouard  13861:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   13862:      Death is a valid wave (if date is known).
                   13863:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   13864:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   13865:      and mw[mi+1][i]. dh depends on stepm.
                   13866:   */
                   13867: 
1.126     brouard  13868:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  13869:   /* Concatenates waves */
1.145     brouard  13870:  
1.290     brouard  13871:   free_vector(moisdc,firstobs,lastobs);
                   13872:   free_vector(andc,firstobs,lastobs);
1.215     brouard  13873: 
1.126     brouard  13874:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   13875:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   13876:   ncodemax[1]=1;
1.145     brouard  13877:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  13878:   cptcoveff=0;
1.220     brouard  13879:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
1.335     brouard  13880:     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  13881:   }
                   13882:   
                   13883:   ncovcombmax=pow(2,cptcoveff);
1.338     brouard  13884:   invalidvarcomb=ivector(0, ncovcombmax); 
                   13885:   for(i=0;i<ncovcombmax;i++)
1.227     brouard  13886:     invalidvarcomb[i]=0;
                   13887:   
1.211     brouard  13888:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  13889:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  13890:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  13891:   
1.200     brouard  13892:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  13893:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  13894:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  13895:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   13896:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   13897:    * (currently 0 or 1) in the data.
                   13898:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   13899:    * corresponding modality (h,j).
                   13900:    */
                   13901: 
1.145     brouard  13902:   h=0;
                   13903:   /*if (cptcovn > 0) */
1.126     brouard  13904:   m=pow(2,cptcoveff);
                   13905:  
1.144     brouard  13906:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  13907:           * For k=4 covariates, h goes from 1 to m=2**k
                   13908:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   13909:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.329     brouard  13910:           *     h\k   1     2     3     4   *  h-1\k-1  4  3  2  1          
                   13911:           *______________________________   *______________________
                   13912:           *     1 i=1 1 i=1 1 i=1 1 i=1 1   *     0     0  0  0  0 
                   13913:           *     2     2     1     1     1   *     1     0  0  0  1 
                   13914:           *     3 i=2 1     2     1     1   *     2     0  0  1  0 
                   13915:           *     4     2     2     1     1   *     3     0  0  1  1 
                   13916:           *     5 i=3 1 i=2 1     2     1   *     4     0  1  0  0 
                   13917:           *     6     2     1     2     1   *     5     0  1  0  1 
                   13918:           *     7 i=4 1     2     2     1   *     6     0  1  1  0 
                   13919:           *     8     2     2     2     1   *     7     0  1  1  1 
                   13920:           *     9 i=5 1 i=3 1 i=2 1     2   *     8     1  0  0  0 
                   13921:           *    10     2     1     1     2   *     9     1  0  0  1 
                   13922:           *    11 i=6 1     2     1     2   *    10     1  0  1  0 
                   13923:           *    12     2     2     1     2   *    11     1  0  1  1 
                   13924:           *    13 i=7 1 i=4 1     2     2   *    12     1  1  0  0  
                   13925:           *    14     2     1     2     2   *    13     1  1  0  1 
                   13926:           *    15 i=8 1     2     2     2   *    14     1  1  1  0 
                   13927:           *    16     2     2     2     2   *    15     1  1  1  1          
                   13928:           */                                     
1.212     brouard  13929:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  13930:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   13931:      * and the value of each covariate?
                   13932:      * V1=1, V2=1, V3=2, V4=1 ?
                   13933:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   13934:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   13935:      * In order to get the real value in the data, we use nbcode
                   13936:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   13937:      * We are keeping this crazy system in order to be able (in the future?) 
                   13938:      * to have more than 2 values (0 or 1) for a covariate.
                   13939:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   13940:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   13941:      *              bbbbbbbb
                   13942:      *              76543210     
                   13943:      *   h-1        00000101 (6-1=5)
1.219     brouard  13944:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  13945:      *           &
                   13946:      *     1        00000001 (1)
1.219     brouard  13947:      *              00000000        = 1 & ((h-1) >> (k-1))
                   13948:      *          +1= 00000001 =1 
1.211     brouard  13949:      *
                   13950:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   13951:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   13952:      *    >>k'            11
                   13953:      *          &   00000001
                   13954:      *            = 00000001
                   13955:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   13956:      * Reverse h=6 and m=16?
                   13957:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   13958:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   13959:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   13960:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   13961:      * V3=decodtabm(14,3,2**4)=2
                   13962:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   13963:      *(h-1) >> (j-1)    0011 =13 >> 2
                   13964:      *          &1 000000001
                   13965:      *           = 000000001
                   13966:      *         +1= 000000010 =2
                   13967:      *                  2211
                   13968:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   13969:      *                  V3=2
1.220     brouard  13970:                 * codtabm and decodtabm are identical
1.211     brouard  13971:      */
                   13972: 
1.145     brouard  13973: 
                   13974:  free_ivector(Ndum,-1,NCOVMAX);
                   13975: 
                   13976: 
1.126     brouard  13977:     
1.186     brouard  13978:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  13979:   strcpy(optionfilegnuplot,optionfilefiname);
                   13980:   if(mle==-3)
1.201     brouard  13981:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  13982:   strcat(optionfilegnuplot,".gp");
                   13983: 
                   13984:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   13985:     printf("Problem with file %s",optionfilegnuplot);
                   13986:   }
                   13987:   else{
1.204     brouard  13988:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  13989:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  13990:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   13991:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  13992:   }
                   13993:   /*  fclose(ficgp);*/
1.186     brouard  13994: 
                   13995: 
                   13996:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  13997: 
                   13998:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   13999:   if(mle==-3)
1.201     brouard  14000:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  14001:   strcat(optionfilehtm,".htm");
                   14002:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  14003:     printf("Problem with %s \n",optionfilehtm);
                   14004:     exit(0);
1.126     brouard  14005:   }
                   14006: 
                   14007:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   14008:   strcat(optionfilehtmcov,"-cov.htm");
                   14009:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   14010:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   14011:   }
                   14012:   else{
                   14013:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   14014: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  14015: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  14016:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   14017:   }
                   14018: 
1.335     brouard  14019:   fprintf(fichtm,"<html><head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n\
                   14020: <title>IMaCh %s</title></head>\n\
                   14021:  <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n\
                   14022: <font size=\"3\">Sponsored by Copyright (C)  2002-2015 <a href=http://www.ined.fr>INED</a>\
                   14023: -EUROREVES-Institut de longévité-2013-2022-Japan Society for the Promotion of Sciences 日本学術振興会 \
                   14024: (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - \
                   14025: <a href=https://software.intel.com/en-us>Intel Software 2015-2018</a></font><br> \n", optionfilehtm);
                   14026:   
                   14027:   fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  14028: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  14029: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.337     brouard  14030: 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  14031: \n\
                   14032: <hr  size=\"2\" color=\"#EC5E5E\">\
                   14033:  <ul><li><h4>Parameter files</h4>\n\
                   14034:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   14035:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   14036:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   14037:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   14038:  - Date and time at start: %s</ul>\n",\
1.335     brouard  14039:          version,fullversion,optionfilehtm,optionfilehtm,title,datafile,datafile,firstpass,lastpass,stepm, weightopt, model, \
1.126     brouard  14040:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   14041:          fileres,fileres,\
                   14042:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   14043:   fflush(fichtm);
                   14044: 
                   14045:   strcpy(pathr,path);
                   14046:   strcat(pathr,optionfilefiname);
1.184     brouard  14047: #ifdef WIN32
                   14048:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   14049: #else
1.126     brouard  14050:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  14051: #endif
                   14052:          
1.126     brouard  14053:   
1.220     brouard  14054:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   14055:                 and for any valid combination of covariates
1.126     brouard  14056:      and prints on file fileres'p'. */
1.251     brouard  14057:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  14058:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  14059: 
                   14060:   fprintf(fichtm,"\n");
1.286     brouard  14061:   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  14062:          ftol, stepm);
                   14063:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   14064:   ncurrv=1;
                   14065:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   14066:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   14067:   ncurrv=i;
                   14068:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  14069:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  14070:   ncurrv=i;
                   14071:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  14072:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  14073:   ncurrv=i;
                   14074:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   14075:   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", \
                   14076:           nlstate, ndeath, maxwav, mle, weightopt);
                   14077: 
                   14078:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   14079: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   14080: 
                   14081:   
1.317     brouard  14082:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Number of (used) observations=%d <br>\n\
1.126     brouard  14083: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   14084: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  14085:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  14086:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  14087:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   14088:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   14089:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   14090:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  14091: 
1.126     brouard  14092:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   14093:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   14094:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   14095: 
                   14096:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  14097:   /* For mortality only */
1.126     brouard  14098:   if (mle==-3){
1.136     brouard  14099:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  14100:     for(i=1;i<=NDIM;i++)
                   14101:       for(j=1;j<=NDIM;j++)
                   14102:        ximort[i][j]=0.;
1.186     brouard  14103:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  14104:     cens=ivector(firstobs,lastobs);
                   14105:     ageexmed=vector(firstobs,lastobs);
                   14106:     agecens=vector(firstobs,lastobs);
                   14107:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  14108:                
1.126     brouard  14109:     for (i=1; i<=imx; i++){
                   14110:       dcwave[i]=-1;
                   14111:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  14112:        if (s[m][i]>nlstate) {
                   14113:          dcwave[i]=m;
                   14114:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   14115:          break;
                   14116:        }
1.126     brouard  14117:     }
1.226     brouard  14118:     
1.126     brouard  14119:     for (i=1; i<=imx; i++) {
                   14120:       if (wav[i]>0){
1.226     brouard  14121:        ageexmed[i]=agev[mw[1][i]][i];
                   14122:        j=wav[i];
                   14123:        agecens[i]=1.; 
                   14124:        
                   14125:        if (ageexmed[i]> 1 && wav[i] > 0){
                   14126:          agecens[i]=agev[mw[j][i]][i];
                   14127:          cens[i]= 1;
                   14128:        }else if (ageexmed[i]< 1) 
                   14129:          cens[i]= -1;
                   14130:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   14131:          cens[i]=0 ;
1.126     brouard  14132:       }
                   14133:       else cens[i]=-1;
                   14134:     }
                   14135:     
                   14136:     for (i=1;i<=NDIM;i++) {
                   14137:       for (j=1;j<=NDIM;j++)
1.226     brouard  14138:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  14139:     }
                   14140:     
1.302     brouard  14141:     p[1]=0.0268; p[NDIM]=0.083;
                   14142:     /* printf("%lf %lf", p[1], p[2]); */
1.126     brouard  14143:     
                   14144:     
1.136     brouard  14145: #ifdef GSL
                   14146:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  14147: #else
1.126     brouard  14148:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  14149: #endif
1.201     brouard  14150:     strcpy(filerespow,"POW-MORT_"); 
                   14151:     strcat(filerespow,fileresu);
1.126     brouard  14152:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   14153:       printf("Problem with resultfile: %s\n", filerespow);
                   14154:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   14155:     }
1.136     brouard  14156: #ifdef GSL
                   14157:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  14158: #else
1.126     brouard  14159:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  14160: #endif
1.126     brouard  14161:     /*  for (i=1;i<=nlstate;i++)
                   14162:        for(j=1;j<=nlstate+ndeath;j++)
                   14163:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   14164:     */
                   14165:     fprintf(ficrespow,"\n");
1.136     brouard  14166: #ifdef GSL
                   14167:     /* gsl starts here */ 
                   14168:     T = gsl_multimin_fminimizer_nmsimplex;
                   14169:     gsl_multimin_fminimizer *sfm = NULL;
                   14170:     gsl_vector *ss, *x;
                   14171:     gsl_multimin_function minex_func;
                   14172: 
                   14173:     /* Initial vertex size vector */
                   14174:     ss = gsl_vector_alloc (NDIM);
                   14175:     
                   14176:     if (ss == NULL){
                   14177:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   14178:     }
                   14179:     /* Set all step sizes to 1 */
                   14180:     gsl_vector_set_all (ss, 0.001);
                   14181: 
                   14182:     /* Starting point */
1.126     brouard  14183:     
1.136     brouard  14184:     x = gsl_vector_alloc (NDIM);
                   14185:     
                   14186:     if (x == NULL){
                   14187:       gsl_vector_free(ss);
                   14188:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   14189:     }
                   14190:   
                   14191:     /* Initialize method and iterate */
                   14192:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  14193:     /*     gsl_vector_set(x, 0, 0.0268); */
                   14194:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  14195:     gsl_vector_set(x, 0, p[1]);
                   14196:     gsl_vector_set(x, 1, p[2]);
                   14197: 
                   14198:     minex_func.f = &gompertz_f;
                   14199:     minex_func.n = NDIM;
                   14200:     minex_func.params = (void *)&p; /* ??? */
                   14201:     
                   14202:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   14203:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   14204:     
                   14205:     printf("Iterations beginning .....\n\n");
                   14206:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   14207: 
                   14208:     iteri=0;
                   14209:     while (rval == GSL_CONTINUE){
                   14210:       iteri++;
                   14211:       status = gsl_multimin_fminimizer_iterate(sfm);
                   14212:       
                   14213:       if (status) printf("error: %s\n", gsl_strerror (status));
                   14214:       fflush(0);
                   14215:       
                   14216:       if (status) 
                   14217:         break;
                   14218:       
                   14219:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   14220:       ssval = gsl_multimin_fminimizer_size (sfm);
                   14221:       
                   14222:       if (rval == GSL_SUCCESS)
                   14223:         printf ("converged to a local maximum at\n");
                   14224:       
                   14225:       printf("%5d ", iteri);
                   14226:       for (it = 0; it < NDIM; it++){
                   14227:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   14228:       }
                   14229:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   14230:     }
                   14231:     
                   14232:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   14233:     
                   14234:     gsl_vector_free(x); /* initial values */
                   14235:     gsl_vector_free(ss); /* inital step size */
                   14236:     for (it=0; it<NDIM; it++){
                   14237:       p[it+1]=gsl_vector_get(sfm->x,it);
                   14238:       fprintf(ficrespow," %.12lf", p[it]);
                   14239:     }
                   14240:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   14241: #endif
                   14242: #ifdef POWELL
                   14243:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   14244: #endif  
1.126     brouard  14245:     fclose(ficrespow);
                   14246:     
1.203     brouard  14247:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  14248: 
                   14249:     for(i=1; i <=NDIM; i++)
                   14250:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  14251:                                matcov[i][j]=matcov[j][i];
1.126     brouard  14252:     
                   14253:     printf("\nCovariance matrix\n ");
1.203     brouard  14254:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  14255:     for(i=1; i <=NDIM; i++) {
                   14256:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  14257:                                printf("%f ",matcov[i][j]);
                   14258:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  14259:       }
1.203     brouard  14260:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  14261:     }
                   14262:     
                   14263:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  14264:     for (i=1;i<=NDIM;i++) {
1.126     brouard  14265:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  14266:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   14267:     }
1.302     brouard  14268:     lsurv=vector(agegomp,AGESUP);
                   14269:     lpop=vector(agegomp,AGESUP);
                   14270:     tpop=vector(agegomp,AGESUP);
1.126     brouard  14271:     lsurv[agegomp]=100000;
                   14272:     
                   14273:     for (k=agegomp;k<=AGESUP;k++) {
                   14274:       agemortsup=k;
                   14275:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   14276:     }
                   14277:     
                   14278:     for (k=agegomp;k<agemortsup;k++)
                   14279:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   14280:     
                   14281:     for (k=agegomp;k<agemortsup;k++){
                   14282:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   14283:       sumlpop=sumlpop+lpop[k];
                   14284:     }
                   14285:     
                   14286:     tpop[agegomp]=sumlpop;
                   14287:     for (k=agegomp;k<(agemortsup-3);k++){
                   14288:       /*  tpop[k+1]=2;*/
                   14289:       tpop[k+1]=tpop[k]-lpop[k];
                   14290:     }
                   14291:     
                   14292:     
                   14293:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   14294:     for (k=agegomp;k<(agemortsup-2);k++) 
                   14295:       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]);
                   14296:     
                   14297:     
                   14298:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  14299:                ageminpar=50;
                   14300:                agemaxpar=100;
1.194     brouard  14301:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   14302:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   14303: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14304: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   14305:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   14306: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14307: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  14308:     }else{
                   14309:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   14310:                        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  14311:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  14312:                }
1.201     brouard  14313:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  14314:                     stepm, weightopt,\
                   14315:                     model,imx,p,matcov,agemortsup);
                   14316:     
1.302     brouard  14317:     free_vector(lsurv,agegomp,AGESUP);
                   14318:     free_vector(lpop,agegomp,AGESUP);
                   14319:     free_vector(tpop,agegomp,AGESUP);
1.220     brouard  14320:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  14321:     free_ivector(dcwave,firstobs,lastobs);
                   14322:     free_vector(agecens,firstobs,lastobs);
                   14323:     free_vector(ageexmed,firstobs,lastobs);
                   14324:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  14325: #ifdef GSL
1.136     brouard  14326: #endif
1.186     brouard  14327:   } /* Endof if mle==-3 mortality only */
1.205     brouard  14328:   /* Standard  */
                   14329:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   14330:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   14331:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  14332:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  14333:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   14334:     for (k=1; k<=npar;k++)
                   14335:       printf(" %d %8.5f",k,p[k]);
                   14336:     printf("\n");
1.205     brouard  14337:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   14338:       /* mlikeli uses func not funcone */
1.247     brouard  14339:       /* for(i=1;i<nlstate;i++){ */
                   14340:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   14341:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   14342:       /* } */
1.205     brouard  14343:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   14344:     }
                   14345:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   14346:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   14347:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   14348:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   14349:     }
                   14350:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  14351:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   14352:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
1.335     brouard  14353:           /* exit(0); */
1.126     brouard  14354:     for (k=1; k<=npar;k++)
                   14355:       printf(" %d %8.5f",k,p[k]);
                   14356:     printf("\n");
                   14357:     
                   14358:     /*--------- results files --------------*/
1.283     brouard  14359:     /* 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  14360:     
                   14361:     
                   14362:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  14363:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); /* Printing model equation */
1.126     brouard  14364:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  14365: 
                   14366:     printf("#model=  1      +     age ");
                   14367:     fprintf(ficres,"#model=  1      +     age ");
                   14368:     fprintf(ficlog,"#model=  1      +     age ");
                   14369:     fprintf(fichtm,"\n<ul><li> model=1+age+%s\n \
                   14370: </ul>", model);
                   14371: 
                   14372:     fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">\n");
                   14373:     fprintf(fichtm, "<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   14374:     if(nagesqr==1){
                   14375:       printf("  + age*age  ");
                   14376:       fprintf(ficres,"  + age*age  ");
                   14377:       fprintf(ficlog,"  + age*age  ");
                   14378:       fprintf(fichtm, "<th>+ age*age</th>");
                   14379:     }
                   14380:     for(j=1;j <=ncovmodel-2;j++){
                   14381:       if(Typevar[j]==0) {
                   14382:        printf("  +      V%d  ",Tvar[j]);
                   14383:        fprintf(ficres,"  +      V%d  ",Tvar[j]);
                   14384:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   14385:        fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   14386:       }else if(Typevar[j]==1) {
                   14387:        printf("  +    V%d*age ",Tvar[j]);
                   14388:        fprintf(ficres,"  +    V%d*age ",Tvar[j]);
                   14389:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   14390:        fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   14391:       }else if(Typevar[j]==2) {
                   14392:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14393:        fprintf(ficres,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14394:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14395:        fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  14396:       }else if(Typevar[j]==3) { /* TO VERIFY */
                   14397:        printf("  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14398:        fprintf(ficres,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14399:        fprintf(ficlog,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14400:        fprintf(fichtm, "<th>+  V%d*V%d*age</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.319     brouard  14401:       }
                   14402:     }
                   14403:     printf("\n");
                   14404:     fprintf(ficres,"\n");
                   14405:     fprintf(ficlog,"\n");
                   14406:     fprintf(fichtm, "</tr>");
                   14407:     fprintf(fichtm, "\n");
                   14408:     
                   14409:     
1.126     brouard  14410:     for(i=1,jk=1; i <=nlstate; i++){
                   14411:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  14412:        if (k != i) {
1.319     brouard  14413:          fprintf(fichtm, "<tr>");
1.225     brouard  14414:          printf("%d%d ",i,k);
                   14415:          fprintf(ficlog,"%d%d ",i,k);
                   14416:          fprintf(ficres,"%1d%1d ",i,k);
1.319     brouard  14417:          fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  14418:          for(j=1; j <=ncovmodel; j++){
                   14419:            printf("%12.7f ",p[jk]);
                   14420:            fprintf(ficlog,"%12.7f ",p[jk]);
                   14421:            fprintf(ficres,"%12.7f ",p[jk]);
1.319     brouard  14422:            fprintf(fichtm, "<td>%12.7f</td>",p[jk]);
1.225     brouard  14423:            jk++; 
                   14424:          }
                   14425:          printf("\n");
                   14426:          fprintf(ficlog,"\n");
                   14427:          fprintf(ficres,"\n");
1.319     brouard  14428:          fprintf(fichtm, "</tr>\n");
1.225     brouard  14429:        }
1.126     brouard  14430:       }
                   14431:     }
1.319     brouard  14432:     /* fprintf(fichtm,"</tr>\n"); */
                   14433:     fprintf(fichtm,"</table>\n");
                   14434:     fprintf(fichtm, "\n");
                   14435: 
1.203     brouard  14436:     if(mle != 0){
                   14437:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  14438:       ftolhess=ftol; /* Usually correct */
1.203     brouard  14439:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   14440:       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");
                   14441:       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  14442:       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  14443:       fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">");
                   14444:       fprintf(fichtm, "\n<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   14445:       if(nagesqr==1){
                   14446:        printf("  + age*age  ");
                   14447:        fprintf(ficres,"  + age*age  ");
                   14448:        fprintf(ficlog,"  + age*age  ");
                   14449:        fprintf(fichtm, "<th>+ age*age</th>");
                   14450:       }
                   14451:       for(j=1;j <=ncovmodel-2;j++){
                   14452:        if(Typevar[j]==0) {
                   14453:          printf("  +      V%d  ",Tvar[j]);
                   14454:          fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   14455:        }else if(Typevar[j]==1) {
                   14456:          printf("  +    V%d*age ",Tvar[j]);
                   14457:          fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   14458:        }else if(Typevar[j]==2) {
                   14459:          fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  14460:        }else if(Typevar[j]==3) { /* TO VERIFY */
                   14461:          fprintf(fichtm, "<th>+  V%d*V%d*age</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.319     brouard  14462:        }
                   14463:       }
                   14464:       fprintf(fichtm, "</tr>\n");
                   14465:  
1.203     brouard  14466:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  14467:        for(k=1; k <=(nlstate+ndeath); k++){
                   14468:          if (k != i) {
1.319     brouard  14469:            fprintf(fichtm, "<tr valign=top>");
1.225     brouard  14470:            printf("%d%d ",i,k);
                   14471:            fprintf(ficlog,"%d%d ",i,k);
1.319     brouard  14472:            fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  14473:            for(j=1; j <=ncovmodel; j++){
1.319     brouard  14474:              wald=p[jk]/sqrt(matcov[jk][jk]);
1.324     brouard  14475:              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]));
                   14476:              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  14477:              if(fabs(wald) > 1.96){
1.321     brouard  14478:                fprintf(fichtm, "<td><b>%12.7f</b></br> (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
1.319     brouard  14479:              }else{
                   14480:                fprintf(fichtm, "<td>%12.7f (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
                   14481:              }
1.324     brouard  14482:              fprintf(fichtm,"W=%8.3f</br>",wald);
1.319     brouard  14483:              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  14484:              jk++; 
                   14485:            }
                   14486:            printf("\n");
                   14487:            fprintf(ficlog,"\n");
1.319     brouard  14488:            fprintf(fichtm, "</tr>\n");
1.225     brouard  14489:          }
                   14490:        }
1.193     brouard  14491:       }
1.203     brouard  14492:     } /* end of hesscov and Wald tests */
1.319     brouard  14493:     fprintf(fichtm,"</table>\n");
1.225     brouard  14494:     
1.203     brouard  14495:     /*  */
1.126     brouard  14496:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   14497:     printf("# Scales (for hessian or gradient estimation)\n");
                   14498:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   14499:     for(i=1,jk=1; i <=nlstate; i++){
                   14500:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  14501:        if (j!=i) {
                   14502:          fprintf(ficres,"%1d%1d",i,j);
                   14503:          printf("%1d%1d",i,j);
                   14504:          fprintf(ficlog,"%1d%1d",i,j);
                   14505:          for(k=1; k<=ncovmodel;k++){
                   14506:            printf(" %.5e",delti[jk]);
                   14507:            fprintf(ficlog," %.5e",delti[jk]);
                   14508:            fprintf(ficres," %.5e",delti[jk]);
                   14509:            jk++;
                   14510:          }
                   14511:          printf("\n");
                   14512:          fprintf(ficlog,"\n");
                   14513:          fprintf(ficres,"\n");
                   14514:        }
1.126     brouard  14515:       }
                   14516:     }
                   14517:     
                   14518:     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.349     brouard  14519:     if(mle >= 1) /* Too big for the screen */
1.126     brouard  14520:       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");
                   14521:     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");
                   14522:     /* # 121 Var(a12)\n\ */
                   14523:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   14524:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   14525:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   14526:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   14527:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   14528:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   14529:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   14530:     
                   14531:     
                   14532:     /* Just to have a covariance matrix which will be more understandable
                   14533:        even is we still don't want to manage dictionary of variables
                   14534:     */
                   14535:     for(itimes=1;itimes<=2;itimes++){
                   14536:       jj=0;
                   14537:       for(i=1; i <=nlstate; i++){
1.225     brouard  14538:        for(j=1; j <=nlstate+ndeath; j++){
                   14539:          if(j==i) continue;
                   14540:          for(k=1; k<=ncovmodel;k++){
                   14541:            jj++;
                   14542:            ca[0]= k+'a'-1;ca[1]='\0';
                   14543:            if(itimes==1){
                   14544:              if(mle>=1)
                   14545:                printf("#%1d%1d%d",i,j,k);
                   14546:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   14547:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   14548:            }else{
                   14549:              if(mle>=1)
                   14550:                printf("%1d%1d%d",i,j,k);
                   14551:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   14552:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   14553:            }
                   14554:            ll=0;
                   14555:            for(li=1;li <=nlstate; li++){
                   14556:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   14557:                if(lj==li) continue;
                   14558:                for(lk=1;lk<=ncovmodel;lk++){
                   14559:                  ll++;
                   14560:                  if(ll<=jj){
                   14561:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   14562:                    if(ll<jj){
                   14563:                      if(itimes==1){
                   14564:                        if(mle>=1)
                   14565:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   14566:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   14567:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   14568:                      }else{
                   14569:                        if(mle>=1)
                   14570:                          printf(" %.5e",matcov[jj][ll]); 
                   14571:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   14572:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   14573:                      }
                   14574:                    }else{
                   14575:                      if(itimes==1){
                   14576:                        if(mle>=1)
                   14577:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   14578:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   14579:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   14580:                      }else{
                   14581:                        if(mle>=1)
                   14582:                          printf(" %.7e",matcov[jj][ll]); 
                   14583:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   14584:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   14585:                      }
                   14586:                    }
                   14587:                  }
                   14588:                } /* end lk */
                   14589:              } /* end lj */
                   14590:            } /* end li */
                   14591:            if(mle>=1)
                   14592:              printf("\n");
                   14593:            fprintf(ficlog,"\n");
                   14594:            fprintf(ficres,"\n");
                   14595:            numlinepar++;
                   14596:          } /* end k*/
                   14597:        } /*end j */
1.126     brouard  14598:       } /* end i */
                   14599:     } /* end itimes */
                   14600:     
                   14601:     fflush(ficlog);
                   14602:     fflush(ficres);
1.225     brouard  14603:     while(fgets(line, MAXLINE, ficpar)) {
                   14604:       /* If line starts with a # it is a comment */
                   14605:       if (line[0] == '#') {
                   14606:        numlinepar++;
                   14607:        fputs(line,stdout);
                   14608:        fputs(line,ficparo);
                   14609:        fputs(line,ficlog);
1.299     brouard  14610:        fputs(line,ficres);
1.225     brouard  14611:        continue;
                   14612:       }else
                   14613:        break;
                   14614:     }
                   14615:     
1.209     brouard  14616:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   14617:     /*   ungetc(c,ficpar); */
                   14618:     /*   fgets(line, MAXLINE, ficpar); */
                   14619:     /*   fputs(line,stdout); */
                   14620:     /*   fputs(line,ficparo); */
                   14621:     /* } */
                   14622:     /* ungetc(c,ficpar); */
1.126     brouard  14623:     
                   14624:     estepm=0;
1.209     brouard  14625:     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  14626:       
                   14627:       if (num_filled != 6) {
                   14628:        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);
                   14629:        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);
                   14630:        goto end;
                   14631:       }
                   14632:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   14633:     }
                   14634:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   14635:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   14636:     
1.209     brouard  14637:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  14638:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   14639:     if (fage <= 2) {
                   14640:       bage = ageminpar;
                   14641:       fage = agemaxpar;
                   14642:     }
                   14643:     
                   14644:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  14645:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   14646:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  14647:                
1.186     brouard  14648:     /* Other stuffs, more or less useful */    
1.254     brouard  14649:     while(fgets(line, MAXLINE, ficpar)) {
                   14650:       /* If line starts with a # it is a comment */
                   14651:       if (line[0] == '#') {
                   14652:        numlinepar++;
                   14653:        fputs(line,stdout);
                   14654:        fputs(line,ficparo);
                   14655:        fputs(line,ficlog);
1.299     brouard  14656:        fputs(line,ficres);
1.254     brouard  14657:        continue;
                   14658:       }else
                   14659:        break;
                   14660:     }
                   14661: 
                   14662:     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){
                   14663:       
                   14664:       if (num_filled != 7) {
                   14665:        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);
                   14666:        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);
                   14667:        goto end;
                   14668:       }
                   14669:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   14670:       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);
                   14671:       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);
                   14672:       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  14673:     }
1.254     brouard  14674: 
                   14675:     while(fgets(line, MAXLINE, ficpar)) {
                   14676:       /* If line starts with a # it is a comment */
                   14677:       if (line[0] == '#') {
                   14678:        numlinepar++;
                   14679:        fputs(line,stdout);
                   14680:        fputs(line,ficparo);
                   14681:        fputs(line,ficlog);
1.299     brouard  14682:        fputs(line,ficres);
1.254     brouard  14683:        continue;
                   14684:       }else
                   14685:        break;
1.126     brouard  14686:     }
                   14687:     
                   14688:     
                   14689:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   14690:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   14691:     
1.254     brouard  14692:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   14693:       if (num_filled != 1) {
                   14694:        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);
                   14695:        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);
                   14696:        goto end;
                   14697:       }
                   14698:       printf("pop_based=%d\n",popbased);
                   14699:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   14700:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   14701:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   14702:     }
                   14703:      
1.258     brouard  14704:     /* Results */
1.332     brouard  14705:     /* Value of covariate in each resultine will be compututed (if product) and sorted according to model rank */
                   14706:     /* It is precov[] because we need the varying age in order to compute the real cov[] of the model equation */  
                   14707:     precov=matrix(1,MAXRESULTLINESPONE,1,NCOVMAX+1);
1.307     brouard  14708:     endishere=0;
1.258     brouard  14709:     nresult=0;
1.308     brouard  14710:     parameterline=0;
1.258     brouard  14711:     do{
                   14712:       if(!fgets(line, MAXLINE, ficpar)){
                   14713:        endishere=1;
1.308     brouard  14714:        parameterline=15;
1.258     brouard  14715:       }else if (line[0] == '#') {
                   14716:        /* If line starts with a # it is a comment */
1.254     brouard  14717:        numlinepar++;
                   14718:        fputs(line,stdout);
                   14719:        fputs(line,ficparo);
                   14720:        fputs(line,ficlog);
1.299     brouard  14721:        fputs(line,ficres);
1.254     brouard  14722:        continue;
1.258     brouard  14723:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   14724:        parameterline=11;
1.296     brouard  14725:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  14726:        parameterline=12;
1.307     brouard  14727:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
1.258     brouard  14728:        parameterline=13;
1.307     brouard  14729:       }
1.258     brouard  14730:       else{
                   14731:        parameterline=14;
1.254     brouard  14732:       }
1.308     brouard  14733:       switch (parameterline){ /* =0 only if only comments */
1.258     brouard  14734:       case 11:
1.296     brouard  14735:        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)){
                   14736:                  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  14737:          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);
                   14738:          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);
                   14739:          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);
                   14740:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  14741:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   14742:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  14743:           prvforecast = 1;
                   14744:        } 
                   14745:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.313     brouard  14746:          printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   14747:          fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   14748:          fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  14749:           prvforecast = 2;
                   14750:        }
                   14751:        else {
                   14752:          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);
                   14753:          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);
                   14754:          goto end;
1.258     brouard  14755:        }
1.254     brouard  14756:        break;
1.258     brouard  14757:       case 12:
1.296     brouard  14758:        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)){
                   14759:           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);
                   14760:          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);
                   14761:          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);
                   14762:          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);
                   14763:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  14764:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   14765:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  14766:           prvbackcast = 1;
                   14767:        } 
                   14768:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.313     brouard  14769:          printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   14770:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   14771:          fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  14772:           prvbackcast = 2;
                   14773:        }
                   14774:        else {
                   14775:          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);
                   14776:          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);
                   14777:          goto end;
1.258     brouard  14778:        }
1.230     brouard  14779:        break;
1.258     brouard  14780:       case 13:
1.332     brouard  14781:        num_filled=sscanf(line,"result:%[^\n]\n",resultlineori);
1.307     brouard  14782:        nresult++; /* Sum of resultlines */
1.342     brouard  14783:        /* printf("Result %d: result:%s\n",nresult, resultlineori); */
1.332     brouard  14784:        /* removefirstspace(&resultlineori); */
                   14785:        
                   14786:        if(strstr(resultlineori,"v") !=0){
                   14787:          printf("Error. 'v' must be in upper case 'V' result: %s ",resultlineori);
                   14788:          fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultlineori);fflush(ficlog);
                   14789:          return 1;
                   14790:        }
                   14791:        trimbb(resultline, resultlineori); /* Suppressing double blank in the resultline */
1.342     brouard  14792:        /* printf("Decoderesult resultline=\"%s\" resultlineori=\"%s\"\n", resultline, resultlineori); */
1.318     brouard  14793:        if(nresult > MAXRESULTLINESPONE-1){
                   14794:          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);
                   14795:          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  14796:          goto end;
                   14797:        }
1.332     brouard  14798:        
1.310     brouard  14799:        if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.314     brouard  14800:          fprintf(ficparo,"result: %s\n",resultline);
                   14801:          fprintf(ficres,"result: %s\n",resultline);
                   14802:          fprintf(ficlog,"result: %s\n",resultline);
1.310     brouard  14803:        } else
                   14804:          goto end;
1.307     brouard  14805:        break;
                   14806:       case 14:
                   14807:        printf("Error: Unknown command '%s'\n",line);
                   14808:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
1.314     brouard  14809:        if(line[0] == ' ' || line[0] == '\n'){
                   14810:          printf("It should not be an empty line '%s'\n",line);
                   14811:          fprintf(ficlog,"It should not be an empty line '%s'\n",line);
                   14812:        }         
1.307     brouard  14813:        if(ncovmodel >=2 && nresult==0 ){
                   14814:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   14815:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  14816:        }
1.307     brouard  14817:        /* goto end; */
                   14818:        break;
1.308     brouard  14819:       case 15:
                   14820:        printf("End of resultlines.\n");
                   14821:        fprintf(ficlog,"End of resultlines.\n");
                   14822:        break;
                   14823:       default: /* parameterline =0 */
1.307     brouard  14824:        nresult=1;
                   14825:        decoderesult(".",nresult ); /* No covariate */
1.258     brouard  14826:       } /* End switch parameterline */
                   14827:     }while(endishere==0); /* End do */
1.126     brouard  14828:     
1.230     brouard  14829:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  14830:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  14831:     
                   14832:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  14833:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  14834:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  14835: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14836: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  14837:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  14838: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14839: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  14840:     }else{
1.270     brouard  14841:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  14842:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   14843:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   14844:       if(prvforecast==1){
                   14845:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   14846:         jprojd=jproj1;
                   14847:         mprojd=mproj1;
                   14848:         anprojd=anproj1;
                   14849:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   14850:         jprojf=jproj2;
                   14851:         mprojf=mproj2;
                   14852:         anprojf=anproj2;
                   14853:       } else if(prvforecast == 2){
                   14854:         dateprojd=dateintmean;
                   14855:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   14856:         dateprojf=dateintmean+yrfproj;
                   14857:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   14858:       }
                   14859:       if(prvbackcast==1){
                   14860:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   14861:         jbackd=jback1;
                   14862:         mbackd=mback1;
                   14863:         anbackd=anback1;
                   14864:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   14865:         jbackf=jback2;
                   14866:         mbackf=mback2;
                   14867:         anbackf=anback2;
                   14868:       } else if(prvbackcast == 2){
                   14869:         datebackd=dateintmean;
                   14870:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   14871:         datebackf=dateintmean-yrbproj;
                   14872:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   14873:       }
                   14874:       
1.350     brouard  14875:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);/* HERE valgrind Tvard*/
1.220     brouard  14876:     }
                   14877:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  14878:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   14879:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  14880:                
1.225     brouard  14881:     /*------------ free_vector  -------------*/
                   14882:     /*  chdir(path); */
1.220     brouard  14883:                
1.215     brouard  14884:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   14885:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   14886:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   14887:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  14888:     free_lvector(num,firstobs,lastobs);
                   14889:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  14890:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   14891:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   14892:     fclose(ficparo);
                   14893:     fclose(ficres);
1.220     brouard  14894:                
                   14895:                
1.186     brouard  14896:     /* Other results (useful)*/
1.220     brouard  14897:                
                   14898:                
1.126     brouard  14899:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  14900:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   14901:     prlim=matrix(1,nlstate,1,nlstate);
1.332     brouard  14902:     /* Computes the prevalence limit for each combination k of the dummy covariates by calling prevalim(k) */
1.209     brouard  14903:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  14904:     fclose(ficrespl);
                   14905: 
                   14906:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  14907:     /*#include "hpijx.h"*/
1.332     brouard  14908:     /** 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?*/
                   14909:     /* calls hpxij with combination k */
1.180     brouard  14910:     hPijx(p, bage, fage);
1.145     brouard  14911:     fclose(ficrespij);
1.227     brouard  14912:     
1.220     brouard  14913:     /* ncovcombmax=  pow(2,cptcoveff); */
1.332     brouard  14914:     /*-------------- Variance of one-step probabilities for a combination ij or for nres ?---*/
1.145     brouard  14915:     k=1;
1.126     brouard  14916:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  14917:     
1.269     brouard  14918:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   14919:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   14920:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  14921:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  14922:        for(k=1;k<=ncovcombmax;k++)
                   14923:          probs[i][j][k]=0.;
1.269     brouard  14924:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   14925:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  14926:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  14927:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   14928:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  14929:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  14930:          for(k=1;k<=ncovcombmax;k++)
                   14931:            mobaverages[i][j][k]=0.;
1.219     brouard  14932:       mobaverage=mobaverages;
                   14933:       if (mobilav!=0) {
1.235     brouard  14934:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  14935:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  14936:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   14937:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   14938:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   14939:        }
1.269     brouard  14940:       } else if (mobilavproj !=0) {
1.235     brouard  14941:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  14942:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  14943:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   14944:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   14945:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   14946:        }
1.269     brouard  14947:       }else{
                   14948:        printf("Internal error moving average\n");
                   14949:        fflush(stdout);
                   14950:        exit(1);
1.219     brouard  14951:       }
                   14952:     }/* end if moving average */
1.227     brouard  14953:     
1.126     brouard  14954:     /*---------- Forecasting ------------------*/
1.296     brouard  14955:     if(prevfcast==1){ 
                   14956:       /*   /\*    if(stepm ==1){*\/ */
                   14957:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   14958:       /*This done previously after freqsummary.*/
                   14959:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   14960:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   14961:       
                   14962:       /* } else if (prvforecast==2){ */
                   14963:       /*   /\*    if(stepm ==1){*\/ */
                   14964:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   14965:       /* } */
                   14966:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   14967:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  14968:     }
1.269     brouard  14969: 
1.296     brouard  14970:     /* Prevbcasting */
                   14971:     if(prevbcast==1){
1.219     brouard  14972:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   14973:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   14974:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   14975: 
                   14976:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   14977: 
                   14978:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  14979: 
1.219     brouard  14980:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   14981:       fclose(ficresplb);
                   14982: 
1.222     brouard  14983:       hBijx(p, bage, fage, mobaverage);
                   14984:       fclose(ficrespijb);
1.219     brouard  14985: 
1.296     brouard  14986:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   14987:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   14988:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   14989:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   14990:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   14991:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   14992: 
                   14993:       
1.269     brouard  14994:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  14995: 
                   14996:       
1.269     brouard  14997:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  14998:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   14999:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   15000:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  15001:     }    /* end  Prevbcasting */
1.268     brouard  15002:  
1.186     brouard  15003:  
                   15004:     /* ------ Other prevalence ratios------------ */
1.126     brouard  15005: 
1.215     brouard  15006:     free_ivector(wav,1,imx);
                   15007:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   15008:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   15009:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  15010:                
                   15011:                
1.127     brouard  15012:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  15013:                
1.201     brouard  15014:     strcpy(filerese,"E_");
                   15015:     strcat(filerese,fileresu);
1.126     brouard  15016:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   15017:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   15018:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   15019:     }
1.208     brouard  15020:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   15021:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  15022: 
                   15023:     pstamp(ficreseij);
1.219     brouard  15024:                
1.351     brouard  15025:     /* i1=pow(2,cptcoveff); /\* Number of combination of dummy covariates *\/ */
                   15026:     /* if (cptcovn < 1){i1=1;} */
1.235     brouard  15027:     
1.351     brouard  15028:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   15029:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   15030:       /* if(i1 != 1 && TKresult[nres]!= k) */
                   15031:       /*       continue; */
1.219     brouard  15032:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  15033:       printf("\n#****** ");
1.351     brouard  15034:       for(j=1;j<=cptcovs;j++){
                   15035:       /* for(j=1;j<=cptcoveff;j++) { */
                   15036:        /* fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15037:        fprintf(ficreseij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   15038:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   15039:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.235     brouard  15040:       }
                   15041:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.337     brouard  15042:        printf(" V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]); /* TvarsQ[j] gives the name of the jth quantitative (fixed or time v) */
                   15043:        fprintf(ficreseij,"V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]);
1.219     brouard  15044:       }
                   15045:       fprintf(ficreseij,"******\n");
1.235     brouard  15046:       printf("******\n");
1.219     brouard  15047:       
                   15048:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   15049:       oldm=oldms;savm=savms;
1.330     brouard  15050:       /* 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  15051:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  15052:       
1.219     brouard  15053:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  15054:     }
                   15055:     fclose(ficreseij);
1.208     brouard  15056:     printf("done evsij\n");fflush(stdout);
                   15057:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  15058: 
1.218     brouard  15059:                
1.227     brouard  15060:     /*---------- State-specific expectancies and variances ------------*/
1.336     brouard  15061:     /* Should be moved in a function */                
1.201     brouard  15062:     strcpy(filerest,"T_");
                   15063:     strcat(filerest,fileresu);
1.127     brouard  15064:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   15065:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   15066:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   15067:     }
1.208     brouard  15068:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   15069:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  15070:     strcpy(fileresstde,"STDE_");
                   15071:     strcat(fileresstde,fileresu);
1.126     brouard  15072:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  15073:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   15074:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  15075:     }
1.227     brouard  15076:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   15077:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  15078: 
1.201     brouard  15079:     strcpy(filerescve,"CVE_");
                   15080:     strcat(filerescve,fileresu);
1.126     brouard  15081:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  15082:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   15083:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  15084:     }
1.227     brouard  15085:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   15086:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  15087: 
1.201     brouard  15088:     strcpy(fileresv,"V_");
                   15089:     strcat(fileresv,fileresu);
1.126     brouard  15090:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   15091:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   15092:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   15093:     }
1.227     brouard  15094:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   15095:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  15096: 
1.235     brouard  15097:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   15098:     if (cptcovn < 1){i1=1;}
                   15099:     
1.334     brouard  15100:     for(nres=1; nres <= nresult; nres++) /* For each resultline, find the combination and output results according to the values of dummies and then quanti.  */
                   15101:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying. For each nres and each value at position k
                   15102:                          * we know Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline
                   15103:                          * Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline 
                   15104:                          * and Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
                   15105:       /* */
                   15106:       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  15107:        continue;
1.350     brouard  15108:       printf("\n# model %s \n#****** Result for:", model);  /* HERE model is empty */
1.321     brouard  15109:       fprintf(ficrest,"\n# model %s \n#****** Result for:", model);
                   15110:       fprintf(ficlog,"\n# model %s \n#****** Result for:", model);
1.334     brouard  15111:       /* It might not be a good idea to mix dummies and quantitative */
                   15112:       /* 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 *\/ */
                   15113:       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 */
                   15114:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* Output by variables in the resultline *\/ */
                   15115:        /* Tvaraff[j] is the name of the dummy variable in position j in the equation model:
                   15116:         * Tvaraff[1]@9={4, 3, 0, 0, 0, 0, 0, 0, 0}, in model=V5+V4+V3+V4*V3+V5*age
                   15117:         * (V5 is quanti) V4 and V3 are dummies
                   15118:         * TnsdVar[4] is the position 1 and TnsdVar[3]=2 in codtabm(k,l)(V4  V3)=V4  V3
                   15119:         *                                                              l=1 l=2
                   15120:         *                                                           k=1  1   1   0   0
                   15121:         *                                                           k=2  2   1   1   0
                   15122:         *                                                           k=3 [1] [2]  0   1
                   15123:         *                                                           k=4  2   2   1   1
                   15124:         * If nres=1 result: V3=1 V4=0 then k=3 and outputs
                   15125:         * If nres=2 result: V4=1 V3=0 then k=2 and outputs
                   15126:         * nres=1 =>k=3 j=1 V4= nbcode[4][codtabm(3,1)=1)=0; j=2  V3= nbcode[3][codtabm(3,2)=2]=1
                   15127:         * nres=2 =>k=2 j=1 V4= nbcode[4][codtabm(2,1)=2)=1; j=2  V3= nbcode[3][codtabm(2,2)=1]=0
                   15128:         */
                   15129:        /* Tvresult[nres][j] Name of the variable at position j in this resultline */
                   15130:        /* Tresult[nres][j] Value of this variable at position j could be a float if quantitative  */
                   15131: /* We give up with the combinations!! */
1.342     brouard  15132:        /* if(debugILK) */
                   15133:        /*   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  15134: 
                   15135:        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  15136:          /* 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] */
                   15137:          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  */
                   15138:          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  */
                   15139:          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  15140:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   15141:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   15142:          }else{
                   15143:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   15144:          }
                   15145:          /* fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15146:          /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15147:        }else if(Dummy[modelresult[nres][j]]==1){ /* Quanti variable */
                   15148:          /* For each selected (single) quantitative value */
1.337     brouard  15149:          printf(" V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   15150:          fprintf(ficlog," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   15151:          fprintf(ficrest," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
1.334     brouard  15152:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   15153:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   15154:          }else{
                   15155:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   15156:          }
                   15157:        }else{
                   15158:          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 */
                   15159:          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 */
                   15160:          exit(1);
                   15161:        }
1.335     brouard  15162:       } /* End loop for each variable in the resultline */
1.334     brouard  15163:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   15164:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /\* Wrong j is not in the equation model *\/ */
                   15165:       /*       fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   15166:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   15167:       /* }      */
1.208     brouard  15168:       fprintf(ficrest,"******\n");
1.227     brouard  15169:       fprintf(ficlog,"******\n");
                   15170:       printf("******\n");
1.208     brouard  15171:       
                   15172:       fprintf(ficresstdeij,"\n#****** ");
                   15173:       fprintf(ficrescveij,"\n#****** ");
1.337     brouard  15174:       /* It could have been: for(j=1;j<=cptcoveff;j++) {printf("V=%d=%lg",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);} */
                   15175:       /* But it won't be sorted and depends on how the resultline is ordered */
1.225     brouard  15176:       for(j=1;j<=cptcoveff;j++) {
1.334     brouard  15177:        fprintf(ficresstdeij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   15178:        /* fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15179:        /* fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15180:       }
                   15181:       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  15182:        fprintf(ficresstdeij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
                   15183:        fprintf(ficrescveij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
1.235     brouard  15184:       }        
1.208     brouard  15185:       fprintf(ficresstdeij,"******\n");
                   15186:       fprintf(ficrescveij,"******\n");
                   15187:       
                   15188:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  15189:       /* pstamp(ficresvij); */
1.225     brouard  15190:       for(j=1;j<=cptcoveff;j++) 
1.335     brouard  15191:        fprintf(ficresvij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   15192:        /* fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[TnsdVar[Tvaraff[j]]])]); */
1.235     brouard  15193:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  15194:        /* fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]); /\* To solve *\/ */
1.337     brouard  15195:        fprintf(ficresvij," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /* Solved */
1.235     brouard  15196:       }        
1.208     brouard  15197:       fprintf(ficresvij,"******\n");
                   15198:       
                   15199:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   15200:       oldm=oldms;savm=savms;
1.235     brouard  15201:       printf(" cvevsij ");
                   15202:       fprintf(ficlog, " cvevsij ");
                   15203:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  15204:       printf(" end cvevsij \n ");
                   15205:       fprintf(ficlog, " end cvevsij \n ");
                   15206:       
                   15207:       /*
                   15208:        */
                   15209:       /* goto endfree; */
                   15210:       
                   15211:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   15212:       pstamp(ficrest);
                   15213:       
1.269     brouard  15214:       epj=vector(1,nlstate+1);
1.208     brouard  15215:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  15216:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   15217:        cptcod= 0; /* To be deleted */
                   15218:        printf("varevsij vpopbased=%d \n",vpopbased);
                   15219:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  15220:        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  15221:        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 ");
                   15222:        if(vpopbased==1)
                   15223:          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);
                   15224:        else
1.288     brouard  15225:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
1.335     brouard  15226:        fprintf(ficrest,"# Age popbased mobilav e.. (std) "); /* Adding covariate values? */
1.227     brouard  15227:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   15228:        fprintf(ficrest,"\n");
                   15229:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  15230:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   15231:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  15232:        for(age=bage; age <=fage ;age++){
1.235     brouard  15233:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  15234:          if (vpopbased==1) {
                   15235:            if(mobilav ==0){
                   15236:              for(i=1; i<=nlstate;i++)
                   15237:                prlim[i][i]=probs[(int)age][i][k];
                   15238:            }else{ /* mobilav */ 
                   15239:              for(i=1; i<=nlstate;i++)
                   15240:                prlim[i][i]=mobaverage[(int)age][i][k];
                   15241:            }
                   15242:          }
1.219     brouard  15243:          
1.227     brouard  15244:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   15245:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   15246:          /* printf(" age %4.0f ",age); */
                   15247:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   15248:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   15249:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   15250:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   15251:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   15252:            }
                   15253:            epj[nlstate+1] +=epj[j];
                   15254:          }
                   15255:          /* printf(" age %4.0f \n",age); */
1.219     brouard  15256:          
1.227     brouard  15257:          for(i=1, vepp=0.;i <=nlstate;i++)
                   15258:            for(j=1;j <=nlstate;j++)
                   15259:              vepp += vareij[i][j][(int)age];
                   15260:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   15261:          for(j=1;j <=nlstate;j++){
                   15262:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   15263:          }
                   15264:          fprintf(ficrest,"\n");
                   15265:        }
1.208     brouard  15266:       } /* End vpopbased */
1.269     brouard  15267:       free_vector(epj,1,nlstate+1);
1.208     brouard  15268:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   15269:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  15270:       printf("done selection\n");fflush(stdout);
                   15271:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  15272:       
1.335     brouard  15273:     } /* End k selection or end covariate selection for nres */
1.227     brouard  15274: 
                   15275:     printf("done State-specific expectancies\n");fflush(stdout);
                   15276:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   15277: 
1.335     brouard  15278:     /* variance-covariance of forward period prevalence */
1.269     brouard  15279:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  15280: 
1.227     brouard  15281:     
1.290     brouard  15282:     free_vector(weight,firstobs,lastobs);
1.351     brouard  15283:     free_imatrix(Tvardk,0,NCOVMAX,1,2);
1.227     brouard  15284:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  15285:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   15286:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   15287:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   15288:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  15289:     free_ivector(tab,1,NCOVMAX);
                   15290:     fclose(ficresstdeij);
                   15291:     fclose(ficrescveij);
                   15292:     fclose(ficresvij);
                   15293:     fclose(ficrest);
                   15294:     fclose(ficpar);
                   15295:     
                   15296:     
1.126     brouard  15297:     /*---------- End : free ----------------*/
1.219     brouard  15298:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  15299:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   15300:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  15301:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   15302:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  15303:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  15304:   /* endfree:*/
                   15305:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   15306:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   15307:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.341     brouard  15308:   /* if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs); */
                   15309:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);
1.290     brouard  15310:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   15311:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   15312:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  15313:   free_matrix(matcov,1,npar,1,npar);
                   15314:   free_matrix(hess,1,npar,1,npar);
                   15315:   /*free_vector(delti,1,npar);*/
                   15316:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   15317:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  15318:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  15319:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   15320:   
                   15321:   free_ivector(ncodemax,1,NCOVMAX);
                   15322:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   15323:   free_ivector(Dummy,-1,NCOVMAX);
                   15324:   free_ivector(Fixed,-1,NCOVMAX);
1.349     brouard  15325:   free_ivector(DummyV,-1,NCOVMAX);
                   15326:   free_ivector(FixedV,-1,NCOVMAX);
1.227     brouard  15327:   free_ivector(Typevar,-1,NCOVMAX);
                   15328:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  15329:   free_ivector(TvarsQ,1,NCOVMAX);
                   15330:   free_ivector(TvarsQind,1,NCOVMAX);
                   15331:   free_ivector(TvarsD,1,NCOVMAX);
1.330     brouard  15332:   free_ivector(TnsdVar,1,NCOVMAX);
1.234     brouard  15333:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  15334:   free_ivector(TvarFD,1,NCOVMAX);
                   15335:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  15336:   free_ivector(TvarF,1,NCOVMAX);
                   15337:   free_ivector(TvarFind,1,NCOVMAX);
                   15338:   free_ivector(TvarV,1,NCOVMAX);
                   15339:   free_ivector(TvarVind,1,NCOVMAX);
                   15340:   free_ivector(TvarA,1,NCOVMAX);
                   15341:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  15342:   free_ivector(TvarFQ,1,NCOVMAX);
                   15343:   free_ivector(TvarFQind,1,NCOVMAX);
                   15344:   free_ivector(TvarVD,1,NCOVMAX);
                   15345:   free_ivector(TvarVDind,1,NCOVMAX);
                   15346:   free_ivector(TvarVQ,1,NCOVMAX);
                   15347:   free_ivector(TvarVQind,1,NCOVMAX);
1.349     brouard  15348:   free_ivector(TvarAVVA,1,NCOVMAX);
                   15349:   free_ivector(TvarAVVAind,1,NCOVMAX);
                   15350:   free_ivector(TvarVVA,1,NCOVMAX);
                   15351:   free_ivector(TvarVVAind,1,NCOVMAX);
1.339     brouard  15352:   free_ivector(TvarVV,1,NCOVMAX);
                   15353:   free_ivector(TvarVVind,1,NCOVMAX);
                   15354:   
1.230     brouard  15355:   free_ivector(Tvarsel,1,NCOVMAX);
                   15356:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  15357:   free_ivector(Tposprod,1,NCOVMAX);
                   15358:   free_ivector(Tprod,1,NCOVMAX);
                   15359:   free_ivector(Tvaraff,1,NCOVMAX);
1.338     brouard  15360:   free_ivector(invalidvarcomb,0,ncovcombmax);
1.227     brouard  15361:   free_ivector(Tage,1,NCOVMAX);
                   15362:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  15363:   free_ivector(TmodelInvind,1,NCOVMAX);
                   15364:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.332     brouard  15365: 
                   15366:   free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /* Could be elsewhere ?*/
                   15367: 
1.227     brouard  15368:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   15369:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  15370:   fflush(fichtm);
                   15371:   fflush(ficgp);
                   15372:   
1.227     brouard  15373:   
1.126     brouard  15374:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  15375:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   15376:     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  15377:   }else{
                   15378:     printf("End of Imach\n");
                   15379:     fprintf(ficlog,"End of Imach\n");
                   15380:   }
                   15381:   printf("See log file on %s\n",filelog);
                   15382:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  15383:   /*(void) gettimeofday(&end_time,&tzp);*/
                   15384:   rend_time = time(NULL);  
                   15385:   end_time = *localtime(&rend_time);
                   15386:   /* tml = *localtime(&end_time.tm_sec); */
                   15387:   strcpy(strtend,asctime(&end_time));
1.126     brouard  15388:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   15389:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  15390:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  15391:   
1.157     brouard  15392:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   15393:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   15394:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  15395:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   15396: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   15397:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   15398:   fclose(fichtm);
                   15399:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   15400:   fclose(fichtmcov);
                   15401:   fclose(ficgp);
                   15402:   fclose(ficlog);
                   15403:   /*------ End -----------*/
1.227     brouard  15404:   
1.281     brouard  15405: 
                   15406: /* Executes gnuplot */
1.227     brouard  15407:   
                   15408:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  15409: #ifdef WIN32
1.227     brouard  15410:   if (_chdir(pathcd) != 0)
                   15411:     printf("Can't move to directory %s!\n",path);
                   15412:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  15413: #else
1.227     brouard  15414:     if(chdir(pathcd) != 0)
                   15415:       printf("Can't move to directory %s!\n", path);
                   15416:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  15417: #endif 
1.126     brouard  15418:     printf("Current directory %s!\n",pathcd);
                   15419:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   15420:   sprintf(plotcmd,"gnuplot");
1.157     brouard  15421: #ifdef _WIN32
1.126     brouard  15422:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   15423: #endif
                   15424:   if(!stat(plotcmd,&info)){
1.158     brouard  15425:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  15426:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  15427:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  15428:     }else
                   15429:       strcpy(pplotcmd,plotcmd);
1.157     brouard  15430: #ifdef __unix
1.126     brouard  15431:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   15432:     if(!stat(plotcmd,&info)){
1.158     brouard  15433:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  15434:     }else
                   15435:       strcpy(pplotcmd,plotcmd);
                   15436: #endif
                   15437:   }else
                   15438:     strcpy(pplotcmd,plotcmd);
                   15439:   
                   15440:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  15441:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  15442:   strcpy(pplotcmd,plotcmd);
1.227     brouard  15443:   
1.126     brouard  15444:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  15445:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  15446:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  15447:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  15448:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  15449:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  15450:       strcpy(plotcmd,pplotcmd);
                   15451:     }
1.126     brouard  15452:   }
1.158     brouard  15453:   printf(" Successful, please wait...");
1.126     brouard  15454:   while (z[0] != 'q') {
                   15455:     /* chdir(path); */
1.154     brouard  15456:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  15457:     scanf("%s",z);
                   15458: /*     if (z[0] == 'c') system("./imach"); */
                   15459:     if (z[0] == 'e') {
1.158     brouard  15460: #ifdef __APPLE__
1.152     brouard  15461:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  15462: #elif __linux
                   15463:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  15464: #else
1.152     brouard  15465:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  15466: #endif
                   15467:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   15468:       system(pplotcmd);
1.126     brouard  15469:     }
                   15470:     else if (z[0] == 'g') system(plotcmd);
                   15471:     else if (z[0] == 'q') exit(0);
                   15472:   }
1.227     brouard  15473: end:
1.126     brouard  15474:   while (z[0] != 'q') {
1.195     brouard  15475:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  15476:     scanf("%s",z);
                   15477:   }
1.283     brouard  15478:   printf("End\n");
1.282     brouard  15479:   exit(0);
1.126     brouard  15480: }

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