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

1.358   ! brouard     1: /* $Id: imach.c,v 1.357 2023/06/14 14:55:52 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.358   ! brouard     4:   Revision 1.357  2023/06/14 14:55:52  brouard
        !             5:   * imach.c (Module): Testing if conjugate gradient could be quicker when lot of variables POWELLORIGINCONJUGATE
        !             6: 
1.357     brouard     7:   Revision 1.356  2023/05/23 12:08:43  brouard
                      8:   Summary: 0.99r46
                      9: 
                     10:   * imach.c (Module): Fixed PROB_r
                     11: 
1.356     brouard    12:   Revision 1.355  2023/05/22 17:03:18  brouard
                     13:   Summary: 0.99r46
                     14: 
                     15:   * imach.c (Module): In the ILK....txt file, the number of columns
                     16:   before the covariates values is dependent of the number of states (16+nlstate): 0.99r46
                     17: 
1.355     brouard    18:   Revision 1.354  2023/05/21 05:05:17  brouard
                     19:   Summary: Temporary change for imachprax
                     20: 
1.354     brouard    21:   Revision 1.353  2023/05/08 18:48:22  brouard
                     22:   *** empty log message ***
                     23: 
1.353     brouard    24:   Revision 1.352  2023/04/29 10:46:21  brouard
                     25:   *** empty log message ***
                     26: 
1.352     brouard    27:   Revision 1.351  2023/04/29 10:43:47  brouard
                     28:   Summary: 099r45
                     29: 
1.351     brouard    30:   Revision 1.350  2023/04/24 11:38:06  brouard
                     31:   *** empty log message ***
                     32: 
1.350     brouard    33:   Revision 1.349  2023/01/31 09:19:37  brouard
                     34:   Summary: Improvements in models with age*Vn*Vm
                     35: 
1.348     brouard    36:   Revision 1.347  2022/09/18 14:36:44  brouard
                     37:   Summary: version 0.99r42
                     38: 
1.347     brouard    39:   Revision 1.346  2022/09/16 13:52:36  brouard
                     40:   * src/imach.c (Module): 0.99r41 Was an error when product of timevarying and fixed. Using FixedV[of name] now. Thank you  Feinuo
                     41: 
1.346     brouard    42:   Revision 1.345  2022/09/16 13:40:11  brouard
                     43:   Summary: Version 0.99r41
                     44: 
                     45:   * imach.c (Module): 0.99r41 Was an error when product of timevarying and fixed. Using FixedV[of name] now. Thank you  Feinuo
                     46: 
1.345     brouard    47:   Revision 1.344  2022/09/14 19:33:30  brouard
                     48:   Summary: version 0.99r40
                     49: 
                     50:   * imach.c (Module): Fixing names of variables in T_ (thanks to Feinuo)
                     51: 
1.344     brouard    52:   Revision 1.343  2022/09/14 14:22:16  brouard
                     53:   Summary: version 0.99r39
                     54: 
                     55:   * imach.c (Module): Version 0.99r39 with colored dummy covariates
                     56:   (fixed or time varying), using new last columns of
                     57:   ILK_parameter.txt file.
                     58: 
1.343     brouard    59:   Revision 1.342  2022/09/11 19:54:09  brouard
                     60:   Summary: 0.99r38
                     61: 
                     62:   * imach.c (Module): Adding timevarying products of any kinds,
                     63:   should work before shifting cotvar from ncovcol+nqv columns in
                     64:   order to have a correspondance between the column of cotvar and
                     65:   the id of column.
                     66:   (Module): Some cleaning and adding covariates in ILK.txt
                     67: 
1.342     brouard    68:   Revision 1.341  2022/09/11 07:58:42  brouard
                     69:   Summary: Version 0.99r38
                     70: 
                     71:   After adding change in cotvar.
                     72: 
1.341     brouard    73:   Revision 1.340  2022/09/11 07:53:11  brouard
                     74:   Summary: Version imach 0.99r37
                     75: 
                     76:   * imach.c (Module): Adding timevarying products of any kinds,
                     77:   should work before shifting cotvar from ncovcol+nqv columns in
                     78:   order to have a correspondance between the column of cotvar and
                     79:   the id of column.
                     80: 
1.340     brouard    81:   Revision 1.339  2022/09/09 17:55:22  brouard
                     82:   Summary: version 0.99r37
                     83: 
                     84:   * imach.c (Module): Many improvements for fixing products of fixed
                     85:   timevarying as well as fixed * fixed, and test with quantitative
                     86:   covariate.
                     87: 
1.339     brouard    88:   Revision 1.338  2022/09/04 17:40:33  brouard
                     89:   Summary: 0.99r36
                     90: 
                     91:   * imach.c (Module): Now the easy runs i.e. without result or
                     92:   model=1+age only did not work. The defautl combination should be 1
                     93:   and not 0 because everything hasn't been tranformed yet.
                     94: 
1.338     brouard    95:   Revision 1.337  2022/09/02 14:26:02  brouard
                     96:   Summary: version 0.99r35
                     97: 
                     98:   * src/imach.c: Version 0.99r35 because it outputs same results with
                     99:   1+age+V1+V1*age for females and 1+age for females only
                    100:   (education=1 noweight)
                    101: 
1.337     brouard   102:   Revision 1.336  2022/08/31 09:52:36  brouard
                    103:   *** empty log message ***
                    104: 
1.336     brouard   105:   Revision 1.335  2022/08/31 08:23:16  brouard
                    106:   Summary: improvements...
                    107: 
1.335     brouard   108:   Revision 1.334  2022/08/25 09:08:41  brouard
                    109:   Summary: In progress for quantitative
                    110: 
1.334     brouard   111:   Revision 1.333  2022/08/21 09:10:30  brouard
                    112:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                    113:   reassigning covariates: my first idea was that people will always
                    114:   use the first covariate V1 into the model but in fact they are
                    115:   producing data with many covariates and can use an equation model
                    116:   with some of the covariate; it means that in a model V2+V3 instead
                    117:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                    118:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                    119:   the equation model is restricted to two variables only (V2, V3)
                    120:   and the combination for V2 should be codtabm(k,1) instead of
                    121:   (codtabm(k,2), and the code should be
                    122:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                    123:   made. All of these should be simplified once a day like we did in
                    124:   hpxij() for example by using precov[nres] which is computed in
                    125:   decoderesult for each nres of each resultline. Loop should be done
                    126:   on the equation model globally by distinguishing only product with
                    127:   age (which are changing with age) and no more on type of
                    128:   covariates, single dummies, single covariates.
                    129: 
1.333     brouard   130:   Revision 1.332  2022/08/21 09:06:25  brouard
                    131:   Summary: Version 0.99r33
                    132: 
                    133:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                    134:   reassigning covariates: my first idea was that people will always
                    135:   use the first covariate V1 into the model but in fact they are
                    136:   producing data with many covariates and can use an equation model
                    137:   with some of the covariate; it means that in a model V2+V3 instead
                    138:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                    139:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                    140:   the equation model is restricted to two variables only (V2, V3)
                    141:   and the combination for V2 should be codtabm(k,1) instead of
                    142:   (codtabm(k,2), and the code should be
                    143:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                    144:   made. All of these should be simplified once a day like we did in
                    145:   hpxij() for example by using precov[nres] which is computed in
                    146:   decoderesult for each nres of each resultline. Loop should be done
                    147:   on the equation model globally by distinguishing only product with
                    148:   age (which are changing with age) and no more on type of
                    149:   covariates, single dummies, single covariates.
                    150: 
1.332     brouard   151:   Revision 1.331  2022/08/07 05:40:09  brouard
                    152:   *** empty log message ***
                    153: 
1.331     brouard   154:   Revision 1.330  2022/08/06 07:18:25  brouard
                    155:   Summary: last 0.99r31
                    156: 
                    157:   *  imach.c (Module): Version of imach using partly decoderesult to rebuild xpxij function
                    158: 
1.330     brouard   159:   Revision 1.329  2022/08/03 17:29:54  brouard
                    160:   *  imach.c (Module): Many errors in graphs fixed with Vn*age covariates.
                    161: 
1.329     brouard   162:   Revision 1.328  2022/07/27 17:40:48  brouard
                    163:   Summary: valgrind bug fixed by initializing to zero DummyV as well as Tage
                    164: 
1.328     brouard   165:   Revision 1.327  2022/07/27 14:47:35  brouard
                    166:   Summary: Still a problem for one-step probabilities in case of quantitative variables
                    167: 
1.327     brouard   168:   Revision 1.326  2022/07/26 17:33:55  brouard
                    169:   Summary: some test with nres=1
                    170: 
1.326     brouard   171:   Revision 1.325  2022/07/25 14:27:23  brouard
                    172:   Summary: r30
                    173: 
                    174:   * imach.c (Module): Error cptcovn instead of nsd in bmij (was
                    175:   coredumped, revealed by Feiuno, thank you.
                    176: 
1.325     brouard   177:   Revision 1.324  2022/07/23 17:44:26  brouard
                    178:   *** empty log message ***
                    179: 
1.324     brouard   180:   Revision 1.323  2022/07/22 12:30:08  brouard
                    181:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    182: 
1.323     brouard   183:   Revision 1.322  2022/07/22 12:27:48  brouard
                    184:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    185: 
1.322     brouard   186:   Revision 1.321  2022/07/22 12:04:24  brouard
                    187:   Summary: r28
                    188: 
                    189:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    190: 
1.321     brouard   191:   Revision 1.320  2022/06/02 05:10:11  brouard
                    192:   *** empty log message ***
                    193: 
1.320     brouard   194:   Revision 1.319  2022/06/02 04:45:11  brouard
                    195:   * imach.c (Module): Adding the Wald tests from the log to the main
                    196:   htm for better display of the maximum likelihood estimators.
                    197: 
1.319     brouard   198:   Revision 1.318  2022/05/24 08:10:59  brouard
                    199:   * imach.c (Module): Some attempts to find a bug of wrong estimates
                    200:   of confidencce intervals with product in the equation modelC
                    201: 
1.318     brouard   202:   Revision 1.317  2022/05/15 15:06:23  brouard
                    203:   * imach.c (Module):  Some minor improvements
                    204: 
1.317     brouard   205:   Revision 1.316  2022/05/11 15:11:31  brouard
                    206:   Summary: r27
                    207: 
1.316     brouard   208:   Revision 1.315  2022/05/11 15:06:32  brouard
                    209:   *** empty log message ***
                    210: 
1.315     brouard   211:   Revision 1.314  2022/04/13 17:43:09  brouard
                    212:   * imach.c (Module): Adding link to text data files
                    213: 
1.314     brouard   214:   Revision 1.313  2022/04/11 15:57:42  brouard
                    215:   * imach.c (Module): Error in rewriting the 'r' file with yearsfproj or yearsbproj fixed
                    216: 
1.313     brouard   217:   Revision 1.312  2022/04/05 21:24:39  brouard
                    218:   *** empty log message ***
                    219: 
1.312     brouard   220:   Revision 1.311  2022/04/05 21:03:51  brouard
                    221:   Summary: Fixed quantitative covariates
                    222: 
                    223:          Fixed covariates (dummy or quantitative)
                    224:        with missing values have never been allowed but are ERRORS and
                    225:        program quits. Standard deviations of fixed covariates were
                    226:        wrongly computed. Mean and standard deviations of time varying
                    227:        covariates are still not computed.
                    228: 
1.311     brouard   229:   Revision 1.310  2022/03/17 08:45:53  brouard
                    230:   Summary: 99r25
                    231: 
                    232:   Improving detection of errors: result lines should be compatible with
                    233:   the model.
                    234: 
1.310     brouard   235:   Revision 1.309  2021/05/20 12:39:14  brouard
                    236:   Summary: Version 0.99r24
                    237: 
1.309     brouard   238:   Revision 1.308  2021/03/31 13:11:57  brouard
                    239:   Summary: Version 0.99r23
                    240: 
                    241: 
                    242:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
                    243: 
1.308     brouard   244:   Revision 1.307  2021/03/08 18:11:32  brouard
                    245:   Summary: 0.99r22 fixed bug on result:
                    246: 
1.307     brouard   247:   Revision 1.306  2021/02/20 15:44:02  brouard
                    248:   Summary: Version 0.99r21
                    249: 
                    250:   * imach.c (Module): Fix bug on quitting after result lines!
                    251:   (Module): Version 0.99r21
                    252: 
1.306     brouard   253:   Revision 1.305  2021/02/20 15:28:30  brouard
                    254:   * imach.c (Module): Fix bug on quitting after result lines!
                    255: 
1.305     brouard   256:   Revision 1.304  2021/02/12 11:34:20  brouard
                    257:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
                    258: 
1.304     brouard   259:   Revision 1.303  2021/02/11 19:50:15  brouard
                    260:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
                    261: 
1.303     brouard   262:   Revision 1.302  2020/02/22 21:00:05  brouard
                    263:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
                    264:   and life table from the data without any state)
                    265: 
1.302     brouard   266:   Revision 1.301  2019/06/04 13:51:20  brouard
                    267:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                    268: 
1.301     brouard   269:   Revision 1.300  2019/05/22 19:09:45  brouard
                    270:   Summary: version 0.99r19 of May 2019
                    271: 
1.300     brouard   272:   Revision 1.299  2019/05/22 18:37:08  brouard
                    273:   Summary: Cleaned 0.99r19
                    274: 
1.299     brouard   275:   Revision 1.298  2019/05/22 18:19:56  brouard
                    276:   *** empty log message ***
                    277: 
1.298     brouard   278:   Revision 1.297  2019/05/22 17:56:10  brouard
                    279:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                    280: 
1.297     brouard   281:   Revision 1.296  2019/05/20 13:03:18  brouard
                    282:   Summary: Projection syntax simplified
                    283: 
                    284: 
                    285:   We can now start projections, forward or backward, from the mean date
                    286:   of inteviews up to or down to a number of years of projection:
                    287:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                    288:   or
                    289:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                    290:   or
                    291:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                    292:   or
                    293:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                    294: 
1.296     brouard   295:   Revision 1.295  2019/05/18 09:52:50  brouard
                    296:   Summary: doxygen tex bug
                    297: 
1.295     brouard   298:   Revision 1.294  2019/05/16 14:54:33  brouard
                    299:   Summary: There was some wrong lines added
                    300: 
1.294     brouard   301:   Revision 1.293  2019/05/09 15:17:34  brouard
                    302:   *** empty log message ***
                    303: 
1.293     brouard   304:   Revision 1.292  2019/05/09 14:17:20  brouard
                    305:   Summary: Some updates
                    306: 
1.292     brouard   307:   Revision 1.291  2019/05/09 13:44:18  brouard
                    308:   Summary: Before ncovmax
                    309: 
1.291     brouard   310:   Revision 1.290  2019/05/09 13:39:37  brouard
                    311:   Summary: 0.99r18 unlimited number of individuals
                    312: 
                    313:   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.
                    314: 
1.290     brouard   315:   Revision 1.289  2018/12/13 09:16:26  brouard
                    316:   Summary: Bug for young ages (<-30) will be in r17
                    317: 
1.289     brouard   318:   Revision 1.288  2018/05/02 20:58:27  brouard
                    319:   Summary: Some bugs fixed
                    320: 
1.288     brouard   321:   Revision 1.287  2018/05/01 17:57:25  brouard
                    322:   Summary: Bug fixed by providing frequencies only for non missing covariates
                    323: 
1.287     brouard   324:   Revision 1.286  2018/04/27 14:27:04  brouard
                    325:   Summary: some minor bugs
                    326: 
1.286     brouard   327:   Revision 1.285  2018/04/21 21:02:16  brouard
                    328:   Summary: Some bugs fixed, valgrind tested
                    329: 
1.285     brouard   330:   Revision 1.284  2018/04/20 05:22:13  brouard
                    331:   Summary: Computing mean and stdeviation of fixed quantitative variables
                    332: 
1.284     brouard   333:   Revision 1.283  2018/04/19 14:49:16  brouard
                    334:   Summary: Some minor bugs fixed
                    335: 
1.283     brouard   336:   Revision 1.282  2018/02/27 22:50:02  brouard
                    337:   *** empty log message ***
                    338: 
1.282     brouard   339:   Revision 1.281  2018/02/27 19:25:23  brouard
                    340:   Summary: Adding second argument for quitting
                    341: 
1.281     brouard   342:   Revision 1.280  2018/02/21 07:58:13  brouard
                    343:   Summary: 0.99r15
                    344: 
                    345:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                    346: 
1.280     brouard   347:   Revision 1.279  2017/07/20 13:35:01  brouard
                    348:   Summary: temporary working
                    349: 
1.279     brouard   350:   Revision 1.278  2017/07/19 14:09:02  brouard
                    351:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                    352: 
1.278     brouard   353:   Revision 1.277  2017/07/17 08:53:49  brouard
                    354:   Summary: BOM files can be read now
                    355: 
1.277     brouard   356:   Revision 1.276  2017/06/30 15:48:31  brouard
                    357:   Summary: Graphs improvements
                    358: 
1.276     brouard   359:   Revision 1.275  2017/06/30 13:39:33  brouard
                    360:   Summary: Saito's color
                    361: 
1.275     brouard   362:   Revision 1.274  2017/06/29 09:47:08  brouard
                    363:   Summary: Version 0.99r14
                    364: 
1.274     brouard   365:   Revision 1.273  2017/06/27 11:06:02  brouard
                    366:   Summary: More documentation on projections
                    367: 
1.273     brouard   368:   Revision 1.272  2017/06/27 10:22:40  brouard
                    369:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    370: 
1.272     brouard   371:   Revision 1.271  2017/06/27 10:17:50  brouard
                    372:   Summary: Some bug with rint
                    373: 
1.271     brouard   374:   Revision 1.270  2017/05/24 05:45:29  brouard
                    375:   *** empty log message ***
                    376: 
1.270     brouard   377:   Revision 1.269  2017/05/23 08:39:25  brouard
                    378:   Summary: Code into subroutine, cleanings
                    379: 
1.269     brouard   380:   Revision 1.268  2017/05/18 20:09:32  brouard
                    381:   Summary: backprojection and confidence intervals of backprevalence
                    382: 
1.268     brouard   383:   Revision 1.267  2017/05/13 10:25:05  brouard
                    384:   Summary: temporary save for backprojection
                    385: 
1.267     brouard   386:   Revision 1.266  2017/05/13 07:26:12  brouard
                    387:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    388: 
1.266     brouard   389:   Revision 1.265  2017/04/26 16:22:11  brouard
                    390:   Summary: imach 0.99r13 Some bugs fixed
                    391: 
1.265     brouard   392:   Revision 1.264  2017/04/26 06:01:29  brouard
                    393:   Summary: Labels in graphs
                    394: 
1.264     brouard   395:   Revision 1.263  2017/04/24 15:23:15  brouard
                    396:   Summary: to save
                    397: 
1.263     brouard   398:   Revision 1.262  2017/04/18 16:48:12  brouard
                    399:   *** empty log message ***
                    400: 
1.262     brouard   401:   Revision 1.261  2017/04/05 10:14:09  brouard
                    402:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    403: 
1.261     brouard   404:   Revision 1.260  2017/04/04 17:46:59  brouard
                    405:   Summary: Gnuplot indexations fixed (humm)
                    406: 
1.260     brouard   407:   Revision 1.259  2017/04/04 13:01:16  brouard
                    408:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    409: 
1.259     brouard   410:   Revision 1.258  2017/04/03 10:17:47  brouard
                    411:   Summary: Version 0.99r12
                    412: 
                    413:   Some cleanings, conformed with updated documentation.
                    414: 
1.258     brouard   415:   Revision 1.257  2017/03/29 16:53:30  brouard
                    416:   Summary: Temp
                    417: 
1.257     brouard   418:   Revision 1.256  2017/03/27 05:50:23  brouard
                    419:   Summary: Temporary
                    420: 
1.256     brouard   421:   Revision 1.255  2017/03/08 16:02:28  brouard
                    422:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    423: 
1.255     brouard   424:   Revision 1.254  2017/03/08 07:13:00  brouard
                    425:   Summary: Fixing data parameter line
                    426: 
1.254     brouard   427:   Revision 1.253  2016/12/15 11:59:41  brouard
                    428:   Summary: 0.99 in progress
                    429: 
1.253     brouard   430:   Revision 1.252  2016/09/15 21:15:37  brouard
                    431:   *** empty log message ***
                    432: 
1.252     brouard   433:   Revision 1.251  2016/09/15 15:01:13  brouard
                    434:   Summary: not working
                    435: 
1.251     brouard   436:   Revision 1.250  2016/09/08 16:07:27  brouard
                    437:   Summary: continue
                    438: 
1.250     brouard   439:   Revision 1.249  2016/09/07 17:14:18  brouard
                    440:   Summary: Starting values from frequencies
                    441: 
1.249     brouard   442:   Revision 1.248  2016/09/07 14:10:18  brouard
                    443:   *** empty log message ***
                    444: 
1.248     brouard   445:   Revision 1.247  2016/09/02 11:11:21  brouard
                    446:   *** empty log message ***
                    447: 
1.247     brouard   448:   Revision 1.246  2016/09/02 08:49:22  brouard
                    449:   *** empty log message ***
                    450: 
1.246     brouard   451:   Revision 1.245  2016/09/02 07:25:01  brouard
                    452:   *** empty log message ***
                    453: 
1.245     brouard   454:   Revision 1.244  2016/09/02 07:17:34  brouard
                    455:   *** empty log message ***
                    456: 
1.244     brouard   457:   Revision 1.243  2016/09/02 06:45:35  brouard
                    458:   *** empty log message ***
                    459: 
1.243     brouard   460:   Revision 1.242  2016/08/30 15:01:20  brouard
                    461:   Summary: Fixing a lots
                    462: 
1.242     brouard   463:   Revision 1.241  2016/08/29 17:17:25  brouard
                    464:   Summary: gnuplot problem in Back projection to fix
                    465: 
1.241     brouard   466:   Revision 1.240  2016/08/29 07:53:18  brouard
                    467:   Summary: Better
                    468: 
1.240     brouard   469:   Revision 1.239  2016/08/26 15:51:03  brouard
                    470:   Summary: Improvement in Powell output in order to copy and paste
                    471: 
                    472:   Author:
                    473: 
1.239     brouard   474:   Revision 1.238  2016/08/26 14:23:35  brouard
                    475:   Summary: Starting tests of 0.99
                    476: 
1.238     brouard   477:   Revision 1.237  2016/08/26 09:20:19  brouard
                    478:   Summary: to valgrind
                    479: 
1.237     brouard   480:   Revision 1.236  2016/08/25 10:50:18  brouard
                    481:   *** empty log message ***
                    482: 
1.236     brouard   483:   Revision 1.235  2016/08/25 06:59:23  brouard
                    484:   *** empty log message ***
                    485: 
1.235     brouard   486:   Revision 1.234  2016/08/23 16:51:20  brouard
                    487:   *** empty log message ***
                    488: 
1.234     brouard   489:   Revision 1.233  2016/08/23 07:40:50  brouard
                    490:   Summary: not working
                    491: 
1.233     brouard   492:   Revision 1.232  2016/08/22 14:20:21  brouard
                    493:   Summary: not working
                    494: 
1.232     brouard   495:   Revision 1.231  2016/08/22 07:17:15  brouard
                    496:   Summary: not working
                    497: 
1.231     brouard   498:   Revision 1.230  2016/08/22 06:55:53  brouard
                    499:   Summary: Not working
                    500: 
1.230     brouard   501:   Revision 1.229  2016/07/23 09:45:53  brouard
                    502:   Summary: Completing for func too
                    503: 
1.229     brouard   504:   Revision 1.228  2016/07/22 17:45:30  brouard
                    505:   Summary: Fixing some arrays, still debugging
                    506: 
1.227     brouard   507:   Revision 1.226  2016/07/12 18:42:34  brouard
                    508:   Summary: temp
                    509: 
1.226     brouard   510:   Revision 1.225  2016/07/12 08:40:03  brouard
                    511:   Summary: saving but not running
                    512: 
1.225     brouard   513:   Revision 1.224  2016/07/01 13:16:01  brouard
                    514:   Summary: Fixes
                    515: 
1.224     brouard   516:   Revision 1.223  2016/02/19 09:23:35  brouard
                    517:   Summary: temporary
                    518: 
1.223     brouard   519:   Revision 1.222  2016/02/17 08:14:50  brouard
                    520:   Summary: Probably last 0.98 stable version 0.98r6
                    521: 
1.222     brouard   522:   Revision 1.221  2016/02/15 23:35:36  brouard
                    523:   Summary: minor bug
                    524: 
1.220     brouard   525:   Revision 1.219  2016/02/15 00:48:12  brouard
                    526:   *** empty log message ***
                    527: 
1.219     brouard   528:   Revision 1.218  2016/02/12 11:29:23  brouard
                    529:   Summary: 0.99 Back projections
                    530: 
1.218     brouard   531:   Revision 1.217  2015/12/23 17:18:31  brouard
                    532:   Summary: Experimental backcast
                    533: 
1.217     brouard   534:   Revision 1.216  2015/12/18 17:32:11  brouard
                    535:   Summary: 0.98r4 Warning and status=-2
                    536: 
                    537:   Version 0.98r4 is now:
                    538:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    539:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    540:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    541: 
1.216     brouard   542:   Revision 1.215  2015/12/16 08:52:24  brouard
                    543:   Summary: 0.98r4 working
                    544: 
1.215     brouard   545:   Revision 1.214  2015/12/16 06:57:54  brouard
                    546:   Summary: temporary not working
                    547: 
1.214     brouard   548:   Revision 1.213  2015/12/11 18:22:17  brouard
                    549:   Summary: 0.98r4
                    550: 
1.213     brouard   551:   Revision 1.212  2015/11/21 12:47:24  brouard
                    552:   Summary: minor typo
                    553: 
1.212     brouard   554:   Revision 1.211  2015/11/21 12:41:11  brouard
                    555:   Summary: 0.98r3 with some graph of projected cross-sectional
                    556: 
                    557:   Author: Nicolas Brouard
                    558: 
1.211     brouard   559:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   560:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   561:   Summary: Adding ftolpl parameter
                    562:   Author: N Brouard
                    563: 
                    564:   We had difficulties to get smoothed confidence intervals. It was due
                    565:   to the period prevalence which wasn't computed accurately. The inner
                    566:   parameter ftolpl is now an outer parameter of the .imach parameter
                    567:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    568:   computation are long.
                    569: 
1.209     brouard   570:   Revision 1.208  2015/11/17 14:31:57  brouard
                    571:   Summary: temporary
                    572: 
1.208     brouard   573:   Revision 1.207  2015/10/27 17:36:57  brouard
                    574:   *** empty log message ***
                    575: 
1.207     brouard   576:   Revision 1.206  2015/10/24 07:14:11  brouard
                    577:   *** empty log message ***
                    578: 
1.206     brouard   579:   Revision 1.205  2015/10/23 15:50:53  brouard
                    580:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    581: 
1.205     brouard   582:   Revision 1.204  2015/10/01 16:20:26  brouard
                    583:   Summary: Some new graphs of contribution to likelihood
                    584: 
1.204     brouard   585:   Revision 1.203  2015/09/30 17:45:14  brouard
                    586:   Summary: looking at better estimation of the hessian
                    587: 
                    588:   Also a better criteria for convergence to the period prevalence And
                    589:   therefore adding the number of years needed to converge. (The
                    590:   prevalence in any alive state shold sum to one
                    591: 
1.203     brouard   592:   Revision 1.202  2015/09/22 19:45:16  brouard
                    593:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    594: 
1.202     brouard   595:   Revision 1.201  2015/09/15 17:34:58  brouard
                    596:   Summary: 0.98r0
                    597: 
                    598:   - Some new graphs like suvival functions
                    599:   - Some bugs fixed like model=1+age+V2.
                    600: 
1.201     brouard   601:   Revision 1.200  2015/09/09 16:53:55  brouard
                    602:   Summary: Big bug thanks to Flavia
                    603: 
                    604:   Even model=1+age+V2. did not work anymore
                    605: 
1.200     brouard   606:   Revision 1.199  2015/09/07 14:09:23  brouard
                    607:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    608: 
1.199     brouard   609:   Revision 1.198  2015/09/03 07:14:39  brouard
                    610:   Summary: 0.98q5 Flavia
                    611: 
1.198     brouard   612:   Revision 1.197  2015/09/01 18:24:39  brouard
                    613:   *** empty log message ***
                    614: 
1.197     brouard   615:   Revision 1.196  2015/08/18 23:17:52  brouard
                    616:   Summary: 0.98q5
                    617: 
1.196     brouard   618:   Revision 1.195  2015/08/18 16:28:39  brouard
                    619:   Summary: Adding a hack for testing purpose
                    620: 
                    621:   After reading the title, ftol and model lines, if the comment line has
                    622:   a q, starting with #q, the answer at the end of the run is quit. It
                    623:   permits to run test files in batch with ctest. The former workaround was
                    624:   $ echo q | imach foo.imach
                    625: 
1.195     brouard   626:   Revision 1.194  2015/08/18 13:32:00  brouard
                    627:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    628: 
1.194     brouard   629:   Revision 1.193  2015/08/04 07:17:42  brouard
                    630:   Summary: 0.98q4
                    631: 
1.193     brouard   632:   Revision 1.192  2015/07/16 16:49:02  brouard
                    633:   Summary: Fixing some outputs
                    634: 
1.192     brouard   635:   Revision 1.191  2015/07/14 10:00:33  brouard
                    636:   Summary: Some fixes
                    637: 
1.191     brouard   638:   Revision 1.190  2015/05/05 08:51:13  brouard
                    639:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    640: 
                    641:   Fix 1+age+.
                    642: 
1.190     brouard   643:   Revision 1.189  2015/04/30 14:45:16  brouard
                    644:   Summary: 0.98q2
                    645: 
1.189     brouard   646:   Revision 1.188  2015/04/30 08:27:53  brouard
                    647:   *** empty log message ***
                    648: 
1.188     brouard   649:   Revision 1.187  2015/04/29 09:11:15  brouard
                    650:   *** empty log message ***
                    651: 
1.187     brouard   652:   Revision 1.186  2015/04/23 12:01:52  brouard
                    653:   Summary: V1*age is working now, version 0.98q1
                    654: 
                    655:   Some codes had been disabled in order to simplify and Vn*age was
                    656:   working in the optimization phase, ie, giving correct MLE parameters,
                    657:   but, as usual, outputs were not correct and program core dumped.
                    658: 
1.186     brouard   659:   Revision 1.185  2015/03/11 13:26:42  brouard
                    660:   Summary: Inclusion of compile and links command line for Intel Compiler
                    661: 
1.185     brouard   662:   Revision 1.184  2015/03/11 11:52:39  brouard
                    663:   Summary: Back from Windows 8. Intel Compiler
                    664: 
1.184     brouard   665:   Revision 1.183  2015/03/10 20:34:32  brouard
                    666:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    667: 
                    668:   We use directest instead of original Powell test; probably no
                    669:   incidence on the results, but better justifications;
                    670:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    671:   wrong results.
                    672: 
1.183     brouard   673:   Revision 1.182  2015/02/12 08:19:57  brouard
                    674:   Summary: Trying to keep directest which seems simpler and more general
                    675:   Author: Nicolas Brouard
                    676: 
1.182     brouard   677:   Revision 1.181  2015/02/11 23:22:24  brouard
                    678:   Summary: Comments on Powell added
                    679: 
                    680:   Author:
                    681: 
1.181     brouard   682:   Revision 1.180  2015/02/11 17:33:45  brouard
                    683:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    684: 
1.180     brouard   685:   Revision 1.179  2015/01/04 09:57:06  brouard
                    686:   Summary: back to OS/X
                    687: 
1.179     brouard   688:   Revision 1.178  2015/01/04 09:35:48  brouard
                    689:   *** empty log message ***
                    690: 
1.178     brouard   691:   Revision 1.177  2015/01/03 18:40:56  brouard
                    692:   Summary: Still testing ilc32 on OSX
                    693: 
1.177     brouard   694:   Revision 1.176  2015/01/03 16:45:04  brouard
                    695:   *** empty log message ***
                    696: 
1.176     brouard   697:   Revision 1.175  2015/01/03 16:33:42  brouard
                    698:   *** empty log message ***
                    699: 
1.175     brouard   700:   Revision 1.174  2015/01/03 16:15:49  brouard
                    701:   Summary: Still in cross-compilation
                    702: 
1.174     brouard   703:   Revision 1.173  2015/01/03 12:06:26  brouard
                    704:   Summary: trying to detect cross-compilation
                    705: 
1.173     brouard   706:   Revision 1.172  2014/12/27 12:07:47  brouard
                    707:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    708: 
1.172     brouard   709:   Revision 1.171  2014/12/23 13:26:59  brouard
                    710:   Summary: Back from Visual C
                    711: 
                    712:   Still problem with utsname.h on Windows
                    713: 
1.171     brouard   714:   Revision 1.170  2014/12/23 11:17:12  brouard
                    715:   Summary: Cleaning some \%% back to %%
                    716: 
                    717:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    718: 
1.170     brouard   719:   Revision 1.169  2014/12/22 23:08:31  brouard
                    720:   Summary: 0.98p
                    721: 
                    722:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    723: 
1.169     brouard   724:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   725:   Summary: update
1.169     brouard   726: 
1.168     brouard   727:   Revision 1.167  2014/12/22 13:50:56  brouard
                    728:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    729: 
                    730:   Testing on Linux 64
                    731: 
1.167     brouard   732:   Revision 1.166  2014/12/22 11:40:47  brouard
                    733:   *** empty log message ***
                    734: 
1.166     brouard   735:   Revision 1.165  2014/12/16 11:20:36  brouard
                    736:   Summary: After compiling on Visual C
                    737: 
                    738:   * imach.c (Module): Merging 1.61 to 1.162
                    739: 
1.165     brouard   740:   Revision 1.164  2014/12/16 10:52:11  brouard
                    741:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    742: 
                    743:   * imach.c (Module): Merging 1.61 to 1.162
                    744: 
1.164     brouard   745:   Revision 1.163  2014/12/16 10:30:11  brouard
                    746:   * imach.c (Module): Merging 1.61 to 1.162
                    747: 
1.163     brouard   748:   Revision 1.162  2014/09/25 11:43:39  brouard
                    749:   Summary: temporary backup 0.99!
                    750: 
1.162     brouard   751:   Revision 1.1  2014/09/16 11:06:58  brouard
                    752:   Summary: With some code (wrong) for nlopt
                    753: 
                    754:   Author:
                    755: 
                    756:   Revision 1.161  2014/09/15 20:41:41  brouard
                    757:   Summary: Problem with macro SQR on Intel compiler
                    758: 
1.161     brouard   759:   Revision 1.160  2014/09/02 09:24:05  brouard
                    760:   *** empty log message ***
                    761: 
1.160     brouard   762:   Revision 1.159  2014/09/01 10:34:10  brouard
                    763:   Summary: WIN32
                    764:   Author: Brouard
                    765: 
1.159     brouard   766:   Revision 1.158  2014/08/27 17:11:51  brouard
                    767:   *** empty log message ***
                    768: 
1.158     brouard   769:   Revision 1.157  2014/08/27 16:26:55  brouard
                    770:   Summary: Preparing windows Visual studio version
                    771:   Author: Brouard
                    772: 
                    773:   In order to compile on Visual studio, time.h is now correct and time_t
                    774:   and tm struct should be used. difftime should be used but sometimes I
                    775:   just make the differences in raw time format (time(&now).
                    776:   Trying to suppress #ifdef LINUX
                    777:   Add xdg-open for __linux in order to open default browser.
                    778: 
1.157     brouard   779:   Revision 1.156  2014/08/25 20:10:10  brouard
                    780:   *** empty log message ***
                    781: 
1.156     brouard   782:   Revision 1.155  2014/08/25 18:32:34  brouard
                    783:   Summary: New compile, minor changes
                    784:   Author: Brouard
                    785: 
1.155     brouard   786:   Revision 1.154  2014/06/20 17:32:08  brouard
                    787:   Summary: Outputs now all graphs of convergence to period prevalence
                    788: 
1.154     brouard   789:   Revision 1.153  2014/06/20 16:45:46  brouard
                    790:   Summary: If 3 live state, convergence to period prevalence on same graph
                    791:   Author: Brouard
                    792: 
1.153     brouard   793:   Revision 1.152  2014/06/18 17:54:09  brouard
                    794:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    795: 
1.152     brouard   796:   Revision 1.151  2014/06/18 16:43:30  brouard
                    797:   *** empty log message ***
                    798: 
1.151     brouard   799:   Revision 1.150  2014/06/18 16:42:35  brouard
                    800:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    801:   Author: brouard
                    802: 
1.150     brouard   803:   Revision 1.149  2014/06/18 15:51:14  brouard
                    804:   Summary: Some fixes in parameter files errors
                    805:   Author: Nicolas Brouard
                    806: 
1.149     brouard   807:   Revision 1.148  2014/06/17 17:38:48  brouard
                    808:   Summary: Nothing new
                    809:   Author: Brouard
                    810: 
                    811:   Just a new packaging for OS/X version 0.98nS
                    812: 
1.148     brouard   813:   Revision 1.147  2014/06/16 10:33:11  brouard
                    814:   *** empty log message ***
                    815: 
1.147     brouard   816:   Revision 1.146  2014/06/16 10:20:28  brouard
                    817:   Summary: Merge
                    818:   Author: Brouard
                    819: 
                    820:   Merge, before building revised version.
                    821: 
1.146     brouard   822:   Revision 1.145  2014/06/10 21:23:15  brouard
                    823:   Summary: Debugging with valgrind
                    824:   Author: Nicolas Brouard
                    825: 
                    826:   Lot of changes in order to output the results with some covariates
                    827:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    828:   improve the code.
                    829:   No more memory valgrind error but a lot has to be done in order to
                    830:   continue the work of splitting the code into subroutines.
                    831:   Also, decodemodel has been improved. Tricode is still not
                    832:   optimal. nbcode should be improved. Documentation has been added in
                    833:   the source code.
                    834: 
1.144     brouard   835:   Revision 1.143  2014/01/26 09:45:38  brouard
                    836:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    837: 
                    838:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    839:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    840: 
1.143     brouard   841:   Revision 1.142  2014/01/26 03:57:36  brouard
                    842:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    843: 
                    844:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    845: 
1.142     brouard   846:   Revision 1.141  2014/01/26 02:42:01  brouard
                    847:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    848: 
1.141     brouard   849:   Revision 1.140  2011/09/02 10:37:54  brouard
                    850:   Summary: times.h is ok with mingw32 now.
                    851: 
1.140     brouard   852:   Revision 1.139  2010/06/14 07:50:17  brouard
                    853:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    854:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    855: 
1.139     brouard   856:   Revision 1.138  2010/04/30 18:19:40  brouard
                    857:   *** empty log message ***
                    858: 
1.138     brouard   859:   Revision 1.137  2010/04/29 18:11:38  brouard
                    860:   (Module): Checking covariates for more complex models
                    861:   than V1+V2. A lot of change to be done. Unstable.
                    862: 
1.137     brouard   863:   Revision 1.136  2010/04/26 20:30:53  brouard
                    864:   (Module): merging some libgsl code. Fixing computation
                    865:   of likelione (using inter/intrapolation if mle = 0) in order to
                    866:   get same likelihood as if mle=1.
                    867:   Some cleaning of code and comments added.
                    868: 
1.136     brouard   869:   Revision 1.135  2009/10/29 15:33:14  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.135     brouard   872:   Revision 1.134  2009/10/29 13:18:53  brouard
                    873:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    874: 
1.134     brouard   875:   Revision 1.133  2009/07/06 10:21:25  brouard
                    876:   just nforces
                    877: 
1.133     brouard   878:   Revision 1.132  2009/07/06 08:22:05  brouard
                    879:   Many tings
                    880: 
1.132     brouard   881:   Revision 1.131  2009/06/20 16:22:47  brouard
                    882:   Some dimensions resccaled
                    883: 
1.131     brouard   884:   Revision 1.130  2009/05/26 06:44:34  brouard
                    885:   (Module): Max Covariate is now set to 20 instead of 8. A
                    886:   lot of cleaning with variables initialized to 0. Trying to make
                    887:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    888: 
1.130     brouard   889:   Revision 1.129  2007/08/31 13:49:27  lievre
                    890:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    891: 
1.129     lievre    892:   Revision 1.128  2006/06/30 13:02:05  brouard
                    893:   (Module): Clarifications on computing e.j
                    894: 
1.128     brouard   895:   Revision 1.127  2006/04/28 18:11:50  brouard
                    896:   (Module): Yes the sum of survivors was wrong since
                    897:   imach-114 because nhstepm was no more computed in the age
                    898:   loop. Now we define nhstepma in the age loop.
                    899:   (Module): In order to speed up (in case of numerous covariates) we
                    900:   compute health expectancies (without variances) in a first step
                    901:   and then all the health expectancies with variances or standard
                    902:   deviation (needs data from the Hessian matrices) which slows the
                    903:   computation.
                    904:   In the future we should be able to stop the program is only health
                    905:   expectancies and graph are needed without standard deviations.
                    906: 
1.127     brouard   907:   Revision 1.126  2006/04/28 17:23:28  brouard
                    908:   (Module): Yes the sum of survivors was wrong since
                    909:   imach-114 because nhstepm was no more computed in the age
                    910:   loop. Now we define nhstepma in the age loop.
                    911:   Version 0.98h
                    912: 
1.126     brouard   913:   Revision 1.125  2006/04/04 15:20:31  lievre
                    914:   Errors in calculation of health expectancies. Age was not initialized.
                    915:   Forecasting file added.
                    916: 
                    917:   Revision 1.124  2006/03/22 17:13:53  lievre
                    918:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    919:   The log-likelihood is printed in the log file
                    920: 
                    921:   Revision 1.123  2006/03/20 10:52:43  brouard
                    922:   * imach.c (Module): <title> changed, corresponds to .htm file
                    923:   name. <head> headers where missing.
                    924: 
                    925:   * imach.c (Module): Weights can have a decimal point as for
                    926:   English (a comma might work with a correct LC_NUMERIC environment,
                    927:   otherwise the weight is truncated).
                    928:   Modification of warning when the covariates values are not 0 or
                    929:   1.
                    930:   Version 0.98g
                    931: 
                    932:   Revision 1.122  2006/03/20 09:45:41  brouard
                    933:   (Module): Weights can have a decimal point as for
                    934:   English (a comma might work with a correct LC_NUMERIC environment,
                    935:   otherwise the weight is truncated).
                    936:   Modification of warning when the covariates values are not 0 or
                    937:   1.
                    938:   Version 0.98g
                    939: 
                    940:   Revision 1.121  2006/03/16 17:45:01  lievre
                    941:   * imach.c (Module): Comments concerning covariates added
                    942: 
                    943:   * imach.c (Module): refinements in the computation of lli if
                    944:   status=-2 in order to have more reliable computation if stepm is
                    945:   not 1 month. Version 0.98f
                    946: 
                    947:   Revision 1.120  2006/03/16 15:10:38  lievre
                    948:   (Module): refinements in the computation of lli if
                    949:   status=-2 in order to have more reliable computation if stepm is
                    950:   not 1 month. Version 0.98f
                    951: 
                    952:   Revision 1.119  2006/03/15 17:42:26  brouard
                    953:   (Module): Bug if status = -2, the loglikelihood was
                    954:   computed as likelihood omitting the logarithm. Version O.98e
                    955: 
                    956:   Revision 1.118  2006/03/14 18:20:07  brouard
                    957:   (Module): varevsij Comments added explaining the second
                    958:   table of variances if popbased=1 .
                    959:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    960:   (Module): Function pstamp added
                    961:   (Module): Version 0.98d
                    962: 
                    963:   Revision 1.117  2006/03/14 17:16:22  brouard
                    964:   (Module): varevsij Comments added explaining the second
                    965:   table of variances if popbased=1 .
                    966:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    967:   (Module): Function pstamp added
                    968:   (Module): Version 0.98d
                    969: 
                    970:   Revision 1.116  2006/03/06 10:29:27  brouard
                    971:   (Module): Variance-covariance wrong links and
                    972:   varian-covariance of ej. is needed (Saito).
                    973: 
                    974:   Revision 1.115  2006/02/27 12:17:45  brouard
                    975:   (Module): One freematrix added in mlikeli! 0.98c
                    976: 
                    977:   Revision 1.114  2006/02/26 12:57:58  brouard
                    978:   (Module): Some improvements in processing parameter
                    979:   filename with strsep.
                    980: 
                    981:   Revision 1.113  2006/02/24 14:20:24  brouard
                    982:   (Module): Memory leaks checks with valgrind and:
                    983:   datafile was not closed, some imatrix were not freed and on matrix
                    984:   allocation too.
                    985: 
                    986:   Revision 1.112  2006/01/30 09:55:26  brouard
                    987:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    988: 
                    989:   Revision 1.111  2006/01/25 20:38:18  brouard
                    990:   (Module): Lots of cleaning and bugs added (Gompertz)
                    991:   (Module): Comments can be added in data file. Missing date values
                    992:   can be a simple dot '.'.
                    993: 
                    994:   Revision 1.110  2006/01/25 00:51:50  brouard
                    995:   (Module): Lots of cleaning and bugs added (Gompertz)
                    996: 
                    997:   Revision 1.109  2006/01/24 19:37:15  brouard
                    998:   (Module): Comments (lines starting with a #) are allowed in data.
                    999: 
                   1000:   Revision 1.108  2006/01/19 18:05:42  lievre
                   1001:   Gnuplot problem appeared...
                   1002:   To be fixed
                   1003: 
                   1004:   Revision 1.107  2006/01/19 16:20:37  brouard
                   1005:   Test existence of gnuplot in imach path
                   1006: 
                   1007:   Revision 1.106  2006/01/19 13:24:36  brouard
                   1008:   Some cleaning and links added in html output
                   1009: 
                   1010:   Revision 1.105  2006/01/05 20:23:19  lievre
                   1011:   *** empty log message ***
                   1012: 
                   1013:   Revision 1.104  2005/09/30 16:11:43  lievre
                   1014:   (Module): sump fixed, loop imx fixed, and simplifications.
                   1015:   (Module): If the status is missing at the last wave but we know
                   1016:   that the person is alive, then we can code his/her status as -2
                   1017:   (instead of missing=-1 in earlier versions) and his/her
                   1018:   contributions to the likelihood is 1 - Prob of dying from last
                   1019:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                   1020:   the healthy state at last known wave). Version is 0.98
                   1021: 
                   1022:   Revision 1.103  2005/09/30 15:54:49  lievre
                   1023:   (Module): sump fixed, loop imx fixed, and simplifications.
                   1024: 
                   1025:   Revision 1.102  2004/09/15 17:31:30  brouard
                   1026:   Add the possibility to read data file including tab characters.
                   1027: 
                   1028:   Revision 1.101  2004/09/15 10:38:38  brouard
                   1029:   Fix on curr_time
                   1030: 
                   1031:   Revision 1.100  2004/07/12 18:29:06  brouard
                   1032:   Add version for Mac OS X. Just define UNIX in Makefile
                   1033: 
                   1034:   Revision 1.99  2004/06/05 08:57:40  brouard
                   1035:   *** empty log message ***
                   1036: 
                   1037:   Revision 1.98  2004/05/16 15:05:56  brouard
                   1038:   New version 0.97 . First attempt to estimate force of mortality
                   1039:   directly from the data i.e. without the need of knowing the health
                   1040:   state at each age, but using a Gompertz model: log u =a + b*age .
                   1041:   This is the basic analysis of mortality and should be done before any
                   1042:   other analysis, in order to test if the mortality estimated from the
                   1043:   cross-longitudinal survey is different from the mortality estimated
                   1044:   from other sources like vital statistic data.
                   1045: 
                   1046:   The same imach parameter file can be used but the option for mle should be -3.
                   1047: 
1.324     brouard  1048:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard  1049:   former routines in order to include the new code within the former code.
                   1050: 
                   1051:   The output is very simple: only an estimate of the intercept and of
                   1052:   the slope with 95% confident intervals.
                   1053: 
                   1054:   Current limitations:
                   1055:   A) Even if you enter covariates, i.e. with the
                   1056:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                   1057:   B) There is no computation of Life Expectancy nor Life Table.
                   1058: 
                   1059:   Revision 1.97  2004/02/20 13:25:42  lievre
                   1060:   Version 0.96d. Population forecasting command line is (temporarily)
                   1061:   suppressed.
                   1062: 
                   1063:   Revision 1.96  2003/07/15 15:38:55  brouard
                   1064:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                   1065:   rewritten within the same printf. Workaround: many printfs.
                   1066: 
                   1067:   Revision 1.95  2003/07/08 07:54:34  brouard
                   1068:   * imach.c (Repository):
                   1069:   (Repository): Using imachwizard code to output a more meaningful covariance
                   1070:   matrix (cov(a12,c31) instead of numbers.
                   1071: 
                   1072:   Revision 1.94  2003/06/27 13:00:02  brouard
                   1073:   Just cleaning
                   1074: 
                   1075:   Revision 1.93  2003/06/25 16:33:55  brouard
                   1076:   (Module): On windows (cygwin) function asctime_r doesn't
                   1077:   exist so I changed back to asctime which exists.
                   1078:   (Module): Version 0.96b
                   1079: 
                   1080:   Revision 1.92  2003/06/25 16:30:45  brouard
                   1081:   (Module): On windows (cygwin) function asctime_r doesn't
                   1082:   exist so I changed back to asctime which exists.
                   1083: 
                   1084:   Revision 1.91  2003/06/25 15:30:29  brouard
                   1085:   * imach.c (Repository): Duplicated warning errors corrected.
                   1086:   (Repository): Elapsed time after each iteration is now output. It
                   1087:   helps to forecast when convergence will be reached. Elapsed time
                   1088:   is stamped in powell.  We created a new html file for the graphs
                   1089:   concerning matrix of covariance. It has extension -cov.htm.
                   1090: 
                   1091:   Revision 1.90  2003/06/24 12:34:15  brouard
                   1092:   (Module): Some bugs corrected for windows. Also, when
                   1093:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1094:   of the covariance matrix to be input.
                   1095: 
                   1096:   Revision 1.89  2003/06/24 12:30:52  brouard
                   1097:   (Module): Some bugs corrected for windows. Also, when
                   1098:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1099:   of the covariance matrix to be input.
                   1100: 
                   1101:   Revision 1.88  2003/06/23 17:54:56  brouard
                   1102:   * 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.
                   1103: 
                   1104:   Revision 1.87  2003/06/18 12:26:01  brouard
                   1105:   Version 0.96
                   1106: 
                   1107:   Revision 1.86  2003/06/17 20:04:08  brouard
                   1108:   (Module): Change position of html and gnuplot routines and added
                   1109:   routine fileappend.
                   1110: 
                   1111:   Revision 1.85  2003/06/17 13:12:43  brouard
                   1112:   * imach.c (Repository): Check when date of death was earlier that
                   1113:   current date of interview. It may happen when the death was just
                   1114:   prior to the death. In this case, dh was negative and likelihood
                   1115:   was wrong (infinity). We still send an "Error" but patch by
                   1116:   assuming that the date of death was just one stepm after the
                   1117:   interview.
                   1118:   (Repository): Because some people have very long ID (first column)
                   1119:   we changed int to long in num[] and we added a new lvector for
                   1120:   memory allocation. But we also truncated to 8 characters (left
                   1121:   truncation)
                   1122:   (Repository): No more line truncation errors.
                   1123: 
                   1124:   Revision 1.84  2003/06/13 21:44:43  brouard
                   1125:   * imach.c (Repository): Replace "freqsummary" at a correct
                   1126:   place. It differs from routine "prevalence" which may be called
                   1127:   many times. Probs is memory consuming and must be used with
                   1128:   parcimony.
                   1129:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                   1130: 
                   1131:   Revision 1.83  2003/06/10 13:39:11  lievre
                   1132:   *** empty log message ***
                   1133: 
                   1134:   Revision 1.82  2003/06/05 15:57:20  brouard
                   1135:   Add log in  imach.c and  fullversion number is now printed.
                   1136: 
                   1137: */
                   1138: /*
                   1139:    Interpolated Markov Chain
                   1140: 
                   1141:   Short summary of the programme:
                   1142:   
1.227     brouard  1143:   This program computes Healthy Life Expectancies or State-specific
                   1144:   (if states aren't health statuses) Expectancies from
                   1145:   cross-longitudinal data. Cross-longitudinal data consist in: 
                   1146: 
                   1147:   -1- a first survey ("cross") where individuals from different ages
                   1148:   are interviewed on their health status or degree of disability (in
                   1149:   the case of a health survey which is our main interest)
                   1150: 
                   1151:   -2- at least a second wave of interviews ("longitudinal") which
                   1152:   measure each change (if any) in individual health status.  Health
                   1153:   expectancies are computed from the time spent in each health state
                   1154:   according to a model. More health states you consider, more time is
                   1155:   necessary to reach the Maximum Likelihood of the parameters involved
                   1156:   in the model.  The simplest model is the multinomial logistic model
                   1157:   where pij is the probability to be observed in state j at the second
                   1158:   wave conditional to be observed in state i at the first
                   1159:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                   1160:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                   1161:   have a more complex model than "constant and age", you should modify
                   1162:   the program where the markup *Covariates have to be included here
                   1163:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard  1164:   convergence.
                   1165: 
                   1166:   The advantage of this computer programme, compared to a simple
                   1167:   multinomial logistic model, is clear when the delay between waves is not
                   1168:   identical for each individual. Also, if a individual missed an
                   1169:   intermediate interview, the information is lost, but taken into
                   1170:   account using an interpolation or extrapolation.  
                   1171: 
                   1172:   hPijx is the probability to be observed in state i at age x+h
                   1173:   conditional to the observed state i at age x. The delay 'h' can be
                   1174:   split into an exact number (nh*stepm) of unobserved intermediate
                   1175:   states. This elementary transition (by month, quarter,
                   1176:   semester or year) is modelled as a multinomial logistic.  The hPx
                   1177:   matrix is simply the matrix product of nh*stepm elementary matrices
                   1178:   and the contribution of each individual to the likelihood is simply
                   1179:   hPijx.
                   1180: 
                   1181:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard  1182:   of the life expectancies. It also computes the period (stable) prevalence.
                   1183: 
                   1184: Back prevalence and projections:
1.227     brouard  1185: 
                   1186:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                   1187:    double agemaxpar, double ftolpl, int *ncvyearp, double
                   1188:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                   1189:    mobilavproj)
                   1190: 
                   1191:     Computes the back prevalence limit for any combination of
                   1192:     covariate values k at any age between ageminpar and agemaxpar and
                   1193:     returns it in **bprlim. In the loops,
                   1194: 
                   1195:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                   1196:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                   1197: 
                   1198:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard  1199:    Computes for any combination of covariates k and any age between bage and fage 
                   1200:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1201:                        oldm=oldms;savm=savms;
1.227     brouard  1202: 
1.267     brouard  1203:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard  1204:      Computes the transition matrix starting at age 'age' over
                   1205:      'nhstepm*hstepm*stepm' months (i.e. until
                   1206:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard  1207:      nhstepm*hstepm matrices. 
                   1208: 
                   1209:      Returns p3mat[i][j][h] after calling
                   1210:      p3mat[i][j][h]=matprod2(newm,
                   1211:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                   1212:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                   1213:      oldm);
1.226     brouard  1214: 
                   1215: Important routines
                   1216: 
                   1217: - func (or funcone), computes logit (pij) distinguishing
                   1218:   o fixed variables (single or product dummies or quantitative);
                   1219:   o varying variables by:
                   1220:    (1) wave (single, product dummies, quantitative), 
                   1221:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                   1222:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                   1223:        % varying dummy (not done) or quantitative (not done);
                   1224: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                   1225:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                   1226: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
1.325     brouard  1227:   o There are 2**cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
1.226     brouard  1228:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard  1229: 
1.226     brouard  1230: 
                   1231:   
1.324     brouard  1232:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                   1233:            Institut national d'études démographiques, Paris.
1.126     brouard  1234:   This software have been partly granted by Euro-REVES, a concerted action
                   1235:   from the European Union.
                   1236:   It is copyrighted identically to a GNU software product, ie programme and
                   1237:   software can be distributed freely for non commercial use. Latest version
                   1238:   can be accessed at http://euroreves.ined.fr/imach .
                   1239: 
                   1240:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                   1241:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                   1242:   
                   1243:   **********************************************************************/
                   1244: /*
                   1245:   main
                   1246:   read parameterfile
                   1247:   read datafile
                   1248:   concatwav
                   1249:   freqsummary
                   1250:   if (mle >= 1)
                   1251:     mlikeli
                   1252:   print results files
                   1253:   if mle==1 
                   1254:      computes hessian
                   1255:   read end of parameter file: agemin, agemax, bage, fage, estepm
                   1256:       begin-prev-date,...
                   1257:   open gnuplot file
                   1258:   open html file
1.145     brouard  1259:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1260:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1261:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1262:     freexexit2 possible for memory heap.
                   1263: 
                   1264:   h Pij x                         | pij_nom  ficrestpij
                   1265:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1266:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1267:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1268: 
                   1269:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1270:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1271:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1272:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1273:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1274: 
1.126     brouard  1275:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1276:   health expectancies
                   1277:   Variance-covariance of DFLE
                   1278:   prevalence()
                   1279:    movingaverage()
                   1280:   varevsij() 
                   1281:   if popbased==1 varevsij(,popbased)
                   1282:   total life expectancies
                   1283:   Variance of period (stable) prevalence
                   1284:  end
                   1285: */
                   1286: 
1.187     brouard  1287: /* #define DEBUG */
                   1288: /* #define DEBUGBRENT */
1.203     brouard  1289: /* #define DEBUGLINMIN */
                   1290: /* #define DEBUGHESS */
                   1291: #define DEBUGHESSIJ
1.224     brouard  1292: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1293: #define POWELL /* Instead of NLOPT */
1.224     brouard  1294: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1295: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1296: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.319     brouard  1297: /* #define FLATSUP  *//* Suppresses directions where likelihood is flat */
1.357     brouard  1298: #define POWELLORIGINCONJUGATE  /* Don't use conjugate but biggest decrease if valuable */
1.126     brouard  1299: 
                   1300: #include <math.h>
                   1301: #include <stdio.h>
                   1302: #include <stdlib.h>
                   1303: #include <string.h>
1.226     brouard  1304: #include <ctype.h>
1.159     brouard  1305: 
                   1306: #ifdef _WIN32
                   1307: #include <io.h>
1.172     brouard  1308: #include <windows.h>
                   1309: #include <tchar.h>
1.159     brouard  1310: #else
1.126     brouard  1311: #include <unistd.h>
1.159     brouard  1312: #endif
1.126     brouard  1313: 
                   1314: #include <limits.h>
                   1315: #include <sys/types.h>
1.171     brouard  1316: 
                   1317: #if defined(__GNUC__)
                   1318: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1319: #endif
                   1320: 
1.126     brouard  1321: #include <sys/stat.h>
                   1322: #include <errno.h>
1.159     brouard  1323: /* extern int errno; */
1.126     brouard  1324: 
1.157     brouard  1325: /* #ifdef LINUX */
                   1326: /* #include <time.h> */
                   1327: /* #include "timeval.h" */
                   1328: /* #else */
                   1329: /* #include <sys/time.h> */
                   1330: /* #endif */
                   1331: 
1.126     brouard  1332: #include <time.h>
                   1333: 
1.136     brouard  1334: #ifdef GSL
                   1335: #include <gsl/gsl_errno.h>
                   1336: #include <gsl/gsl_multimin.h>
                   1337: #endif
                   1338: 
1.167     brouard  1339: 
1.162     brouard  1340: #ifdef NLOPT
                   1341: #include <nlopt.h>
                   1342: typedef struct {
                   1343:   double (* function)(double [] );
                   1344: } myfunc_data ;
                   1345: #endif
                   1346: 
1.126     brouard  1347: /* #include <libintl.h> */
                   1348: /* #define _(String) gettext (String) */
                   1349: 
1.349     brouard  1350: #define MAXLINE 16384 /* Was 256 and 1024 and 2048. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1351: 
                   1352: #define GNUPLOTPROGRAM "gnuplot"
1.343     brouard  1353: #define GNUPLOTVERSION 5.1
                   1354: double gnuplotversion=GNUPLOTVERSION;
1.126     brouard  1355: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
1.329     brouard  1356: #define FILENAMELENGTH 256
1.126     brouard  1357: 
                   1358: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1359: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1360: 
1.349     brouard  1361: #define MAXPARM 216 /**< Maximum number of parameters for the optimization was 128 */
1.144     brouard  1362: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1363: 
                   1364: #define NINTERVMAX 8
1.144     brouard  1365: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1366: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.325     brouard  1367: #define NCOVMAX 30  /**< Maximum number of covariates used in the model, including generated covariates V1*V2 or V1*age */
1.197     brouard  1368: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1369: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1370: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1371: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1372: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1373: /* #define AGESUP 130 */
1.288     brouard  1374: /* #define AGESUP 150 */
                   1375: #define AGESUP 200
1.268     brouard  1376: #define AGEINF 0
1.218     brouard  1377: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1378: #define AGEBASE 40
1.194     brouard  1379: #define AGEOVERFLOW 1.e20
1.164     brouard  1380: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1381: #ifdef _WIN32
                   1382: #define DIRSEPARATOR '\\'
                   1383: #define CHARSEPARATOR "\\"
                   1384: #define ODIRSEPARATOR '/'
                   1385: #else
1.126     brouard  1386: #define DIRSEPARATOR '/'
                   1387: #define CHARSEPARATOR "/"
                   1388: #define ODIRSEPARATOR '\\'
                   1389: #endif
                   1390: 
1.358   ! brouard  1391: /* $Id: imach.c,v 1.357 2023/06/14 14:55:52 brouard Exp $ */
1.126     brouard  1392: /* $State: Exp $ */
1.196     brouard  1393: #include "version.h"
                   1394: char version[]=__IMACH_VERSION__;
1.358   ! brouard  1395: char copyright[]="Testing conjugate 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";
        !          1396: char fullversion[]="$Revision: 1.357 $ $Date: 2023/06/14 14:55:52 $"; 
1.126     brouard  1397: char strstart[80];
                   1398: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1399: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.342     brouard  1400: int debugILK=0; /* debugILK is set by a #d in a comment line */
1.187     brouard  1401: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.330     brouard  1402: /* Number of covariates model (1)=V2+V1+ V3*age+V2*V4 */
                   1403: /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
1.335     brouard  1404: 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  1405: 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  1406: int cptcovs=0; /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   1407: int cptcovsnq=0; /**< cptcovsnq number of SIMPLE covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1408: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
1.349     brouard  1409: int cptcovprodage=0; /**< Number of fixed covariates with age: V3*age or V2*V3*age 1 */
                   1410: int cptcovprodvage=0; /**< Number of varying covariates with age: V7*age or V7*V6*age */
                   1411: int cptcovdageprod=0; /**< Number of doubleproducts with age, since 0.99r44 only: age*Vn*Vm for gnuplot printing*/
1.145     brouard  1412: int cptcovprodnoage=0; /**< Number of covariate products without age */   
1.335     brouard  1413: 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  1414: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1415: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.339     brouard  1416: int ncovvt=0; /* Total number of effective (wave) varying covariates (dummy or quantitative or products [without age]) in the model */
1.349     brouard  1417: 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 */
                   1418: 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 */
                   1419: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (single or product, dummy or quantitative) in the model */
                   1420: 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  1421: int nsd=0; /**< Total number of single dummy variables (output) */
                   1422: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1423: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1424: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1425: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1426: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1427: int cptcov=0; /* Working variable */
1.334     brouard  1428: int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs+1 declared globally ;*/
1.290     brouard  1429: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1430: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.302     brouard  1431: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
1.126     brouard  1432: int nlstate=2; /* Number of live states */
                   1433: int ndeath=1; /* Number of dead states */
1.130     brouard  1434: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.339     brouard  1435: int nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable*/
                   1436: int ncovcolt=0; /* ncovcolt=ncovcol+nqv+ntv+nqtv; total of covariates in the data, not in the model equation*/ 
1.126     brouard  1437: int popbased=0;
                   1438: 
                   1439: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1440: int maxwav=0; /* Maxim number of waves */
                   1441: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1442: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1443: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard  1444:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1445: int mle=1, weightopt=0;
1.126     brouard  1446: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1447: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1448: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1449:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1450: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1451: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1452: 
1.130     brouard  1453: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1454: double **matprod2(); /* test */
1.126     brouard  1455: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1456: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1457: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1458: 
1.136     brouard  1459: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1460: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1461: FILE *ficlog, *ficrespow;
1.130     brouard  1462: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1463: double fretone; /* Only one call to likelihood */
1.130     brouard  1464: long ipmx=0; /* Number of contributions */
1.126     brouard  1465: double sw; /* Sum of weights */
                   1466: char filerespow[FILENAMELENGTH];
                   1467: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1468: FILE *ficresilk;
                   1469: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1470: FILE *ficresprobmorprev;
                   1471: FILE *fichtm, *fichtmcov; /* Html File */
                   1472: FILE *ficreseij;
                   1473: char filerese[FILENAMELENGTH];
                   1474: FILE *ficresstdeij;
                   1475: char fileresstde[FILENAMELENGTH];
                   1476: FILE *ficrescveij;
                   1477: char filerescve[FILENAMELENGTH];
                   1478: FILE  *ficresvij;
                   1479: char fileresv[FILENAMELENGTH];
1.269     brouard  1480: 
1.126     brouard  1481: char title[MAXLINE];
1.234     brouard  1482: char model[MAXLINE]; /**< The model line */
1.217     brouard  1483: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1484: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1485: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1486: char command[FILENAMELENGTH];
                   1487: int  outcmd=0;
                   1488: 
1.217     brouard  1489: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1490: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1491: char filelog[FILENAMELENGTH]; /* Log file */
                   1492: char filerest[FILENAMELENGTH];
                   1493: char fileregp[FILENAMELENGTH];
                   1494: char popfile[FILENAMELENGTH];
                   1495: 
                   1496: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1497: 
1.157     brouard  1498: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1499: /* struct timezone tzp; */
                   1500: /* extern int gettimeofday(); */
                   1501: struct tm tml, *gmtime(), *localtime();
                   1502: 
                   1503: extern time_t time();
                   1504: 
                   1505: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1506: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
1.349     brouard  1507: time_t   rlast_btime; /* raw time */
1.157     brouard  1508: struct tm tm;
                   1509: 
1.126     brouard  1510: char strcurr[80], strfor[80];
                   1511: 
                   1512: char *endptr;
                   1513: long lval;
                   1514: double dval;
                   1515: 
                   1516: #define NR_END 1
                   1517: #define FREE_ARG char*
                   1518: #define FTOL 1.0e-10
                   1519: 
                   1520: #define NRANSI 
1.240     brouard  1521: #define ITMAX 200
                   1522: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1523: 
                   1524: #define TOL 2.0e-4 
                   1525: 
                   1526: #define CGOLD 0.3819660 
                   1527: #define ZEPS 1.0e-10 
                   1528: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1529: 
                   1530: #define GOLD 1.618034 
                   1531: #define GLIMIT 100.0 
                   1532: #define TINY 1.0e-20 
                   1533: 
                   1534: static double maxarg1,maxarg2;
                   1535: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1536: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1537:   
                   1538: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1539: #define rint(a) floor(a+0.5)
1.166     brouard  1540: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1541: #define mytinydouble 1.0e-16
1.166     brouard  1542: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1543: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1544: /* static double dsqrarg; */
                   1545: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1546: static double sqrarg;
                   1547: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1548: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1549: int agegomp= AGEGOMP;
                   1550: 
                   1551: int imx; 
                   1552: int stepm=1;
                   1553: /* Stepm, step in month: minimum step interpolation*/
                   1554: 
                   1555: int estepm;
                   1556: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1557: 
                   1558: int m,nb;
                   1559: long *num;
1.197     brouard  1560: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1561: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1562:                   covariate for which somebody answered excluding 
                   1563:                   undefined. Usually 2: 0 and 1. */
                   1564: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1565:                             covariate for which somebody answered including 
                   1566:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1567: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1568: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1569: double ***mobaverage, ***mobaverages; /* New global variable */
1.332     brouard  1570: 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  1571: double *ageexmed,*agecens;
                   1572: double dateintmean=0;
1.296     brouard  1573:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1574:   double anprojf, mprojf, jprojf;
1.126     brouard  1575: 
1.296     brouard  1576:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1577:   double anbackf, mbackf, jbackf;
                   1578:   double jintmean,mintmean,aintmean;  
1.126     brouard  1579: double *weight;
                   1580: int **s; /* Status */
1.141     brouard  1581: double *agedc;
1.145     brouard  1582: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1583:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1584:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1585: double **coqvar; /* Fixed quantitative covariate nqv */
1.341     brouard  1586: double ***cotvar; /* Time varying covariate start at ncovcol + nqv + (1 to ntv) */
1.225     brouard  1587: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1588: double  idx; 
                   1589: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.319     brouard  1590: /* Some documentation */
                   1591:       /*   Design original data
                   1592:        *  V1   V2   V3   V4  V5  V6  V7  V8  Weight ddb ddth d1st s1 V9 V10 V11 V12 s2 V9 V10 V11 V12 
                   1593:        *  <          ncovcol=6   >   nqv=2 (V7 V8)                   dv dv  dv  qtv    dv dv  dvv qtv
                   1594:        *                                                             ntv=3     nqtv=1
1.330     brouard  1595:        *  cptcovn number of covariates (not including constant and age or age*age) = number of plus sign + 1 = 10+1=11
1.319     brouard  1596:        * For time varying covariate, quanti or dummies
                   1597:        *       cotqvar[wav][iv(1 to nqtv)][i]= [1][12][i]=(V12) quanti
1.341     brouard  1598:        *       cotvar[wav][ncovcol+nqv+ iv(1 to nqtv)][i]= [(1 to nqtv)][i]=(V12) quanti
1.319     brouard  1599:        *       cotvar[wav][iv(1 to ntv)][i]= [1][1][i]=(V9) dummies at wav 1
                   1600:        *       cotvar[wav][iv(1 to ntv)][i]= [1][2][i]=(V10) dummies at wav 1
1.332     brouard  1601:        *       covar[Vk,i], value of the Vkth fixed covariate dummy or quanti for individual i:
1.319     brouard  1602:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   1603:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 + V9 + V9*age + V10
                   1604:        *   k=  1    2      3       4     5       6      7        8   9     10       11 
                   1605:        */
                   1606: /* According to the model, more columns can be added to covar by the product of covariates */
1.318     brouard  1607: /* 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
                   1608:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1609:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1610: */
1.349     brouard  1611: /*           V5+V4+ V3+V4*V3 +V5*age+V2 +V1*V2+V1*age+V1+V4*V3*age */
                   1612: /*    kmodel  1  2   3    4     5     6    7     8     9    10 */
                   1613: /*Typevar[k]=  0  0   0   2     1    0    2     1     0    3 *//*0 for simple covariate (dummy, quantitative,*/
                   1614:                                                                /* fixed or varying), 1 for age product, 2 for*/
                   1615:                                                                /* product without age, 3 for age and double product   */
                   1616: /*Dummy[k]=    1  0   0   1     3    1    1     2     0     3  *//*Dummy[k] 0=dummy (0 1), 1 quantitative */
                   1617:                                                                 /*(single or product without age), 2 dummy*/
                   1618:                                                                /* with age product, 3 quant with age product*/
                   1619: /*Tvar[k]=     5  4   3   6     5    2    7     1     1     6 */
                   1620: /*    nsd         1   2                               3 */ /* Counting single dummies covar fixed or tv */
                   1621: /*TnsdVar[Tvar]   1   2                               3 */ 
                   1622: /*Tvaraff[nsd]    4   3                               1 */ /* ID of single dummy cova fixed or timevary*/
                   1623: /*TvarsD[nsd]     4   3                               1 */ /* ID of single dummy cova fixed or timevary*/
                   1624: /*TvarsDind[nsd]  2   3                               9 */ /* position K of single dummy cova */
                   1625: /*    nsq      1                     2                  */ /* Counting single quantit tv */
                   1626: /* TvarsQ[k]   5                     2                  */ /* Number of single quantitative cova */
                   1627: /* TvarsQind   1                     6                  */ /* position K of single quantitative cova */
                   1628: /* Tprod[i]=k             1               2             */ /* Position in model of the ith prod without age */
                   1629: /* cptcovage                    1               2         3 */ /* Counting cov*age in the model equation */
                   1630: /* Tage[cptcovage]=k            5               8         10 */ /* Position in the model of ith cov*age */
1.350     brouard  1631: /* 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"*/
                   1632: /*  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  1633: /*  p Tvard[2][1]@21 = {7, 2, 6, 3, 7, 3, 6, 4, 7, 4, 0 <repeats 11 times>} */
1.350     brouard  1634: /* 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}*/
                   1635: /* 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  1636: /* Tvard[1][1]@4={4,3,1,2}    V4*V3 V1*V2               */ /* Position in model of the ith prod without age */
1.330     brouard  1637: /* 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  1638: /* 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  1639: /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.234     brouard  1640: /* Type                    */
                   1641: /* V         1  2  3  4  5 */
                   1642: /*           F  F  V  V  V */
                   1643: /*           D  Q  D  D  Q */
                   1644: /*                         */
                   1645: int *TvarsD;
1.330     brouard  1646: int *TnsdVar;
1.234     brouard  1647: int *TvarsDind;
                   1648: int *TvarsQ;
                   1649: int *TvarsQind;
                   1650: 
1.318     brouard  1651: #define MAXRESULTLINESPONE 10+1
1.235     brouard  1652: int nresult=0;
1.258     brouard  1653: int parameterline=0; /* # of the parameter (type) line */
1.334     brouard  1654: int TKresult[MAXRESULTLINESPONE]; /* TKresult[nres]=k for each resultline nres give the corresponding combination of dummies */
                   1655: int resultmodel[MAXRESULTLINESPONE][NCOVMAX];/* resultmodel[k1]=k3: k1th position in the model corresponds to the k3 position in the resultline */
                   1656: int modelresult[MAXRESULTLINESPONE][NCOVMAX];/* modelresult[k3]=k1: k1th position in the model corresponds to the k3 position in the resultline */
                   1657: int Tresult[MAXRESULTLINESPONE][NCOVMAX];/* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1658: int Tinvresult[MAXRESULTLINESPONE][NCOVMAX];/* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line  */
                   1659: double TinvDoQresult[MAXRESULTLINESPONE][NCOVMAX];/* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line */
1.334     brouard  1660: int Tvresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1661: double Tqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
1.318     brouard  1662: double Tqinvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
1.332     brouard  1663: int Tvqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline */
1.318     brouard  1664: 
                   1665: /* 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
                   1666:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1667:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1668: */
1.234     brouard  1669: /* 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  1670: 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 */
                   1671: 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 */
                   1672: 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 */
                   1673: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1674: 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 */
                   1675: 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  1676: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1677: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1678: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1679: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1680: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1681: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1682: 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 */
                   1683: 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  1684: int *TvarVV; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1685: int *TvarVVind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
1.349     brouard  1686: int *TvarVVA; /* We count ncovvt time varying covariates (single or products with age) and put their name into TvarVVA */
                   1687: int *TvarVVAind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1688: int *TvarAVVA; /* We count ALL ncovta time varying covariates (single or products with age) and put their name into TvarVVA */
                   1689: int *TvarAVVAind; /* We count ALL ncovta time varying covariates (single or products without age) and put their name into TvarVV */
1.339     brouard  1690:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
1.349     brouard  1691:       /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age */
                   1692:       /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   1693:       /* TvarVV={3,1,3,1,3}, for V3 and then the product V1*V3 is decomposed into V1 and V3 */        
                   1694:       /* 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  1695: int *Tvarsel; /**< Selected covariates for output */
                   1696: double *Tvalsel; /**< Selected modality value of covariate for output */
1.349     brouard  1697: 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  1698: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1699: 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  1700: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1701: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1702: int *Tage;
1.227     brouard  1703: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1704: 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  1705: 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*/ 
                   1706: 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  1707: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1708: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1709: int **Tvard;
1.330     brouard  1710: int **Tvardk;
1.227     brouard  1711: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1712: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1713: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1714:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1715:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1716: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1717: double *lsurv, *lpop, *tpop;
                   1718: 
1.231     brouard  1719: #define FD 1; /* Fixed dummy covariate */
                   1720: #define FQ 2; /* Fixed quantitative covariate */
                   1721: #define FP 3; /* Fixed product covariate */
                   1722: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1723: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1724: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1725: #define VD 10; /* Varying dummy covariate */
                   1726: #define VQ 11; /* Varying quantitative covariate */
                   1727: #define VP 12; /* Varying product covariate */
                   1728: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1729: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1730: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1731: #define APFD 16; /* Age product * fixed dummy covariate */
                   1732: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1733: #define APVD 18; /* Age product * varying dummy covariate */
                   1734: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1735: 
                   1736: #define FTYPE 1; /* Fixed covariate */
                   1737: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1738: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1739: 
                   1740: struct kmodel{
                   1741:        int maintype; /* main type */
                   1742:        int subtype; /* subtype */
                   1743: };
                   1744: struct kmodel modell[NCOVMAX];
                   1745: 
1.143     brouard  1746: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1747: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1748: 
                   1749: /**************** split *************************/
                   1750: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1751: {
                   1752:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1753:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1754:   */ 
                   1755:   char *ss;                            /* pointer */
1.186     brouard  1756:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1757: 
                   1758:   l1 = strlen(path );                  /* length of path */
                   1759:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1760:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1761:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1762:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1763:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1764:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1765:     /* get current working directory */
                   1766:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1767: #ifdef WIN32
                   1768:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1769: #else
                   1770:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1771: #endif
1.126     brouard  1772:       return( GLOCK_ERROR_GETCWD );
                   1773:     }
                   1774:     /* got dirc from getcwd*/
                   1775:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1776:   } else {                             /* strip directory from path */
1.126     brouard  1777:     ss++;                              /* after this, the filename */
                   1778:     l2 = strlen( ss );                 /* length of filename */
                   1779:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1780:     strcpy( name, ss );                /* save file name */
                   1781:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1782:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1783:     printf(" DIRC2 = %s \n",dirc);
                   1784:   }
                   1785:   /* We add a separator at the end of dirc if not exists */
                   1786:   l1 = strlen( dirc );                 /* length of directory */
                   1787:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1788:     dirc[l1] =  DIRSEPARATOR;
                   1789:     dirc[l1+1] = 0; 
                   1790:     printf(" DIRC3 = %s \n",dirc);
                   1791:   }
                   1792:   ss = strrchr( name, '.' );           /* find last / */
                   1793:   if (ss >0){
                   1794:     ss++;
                   1795:     strcpy(ext,ss);                    /* save extension */
                   1796:     l1= strlen( name);
                   1797:     l2= strlen(ss)+1;
                   1798:     strncpy( finame, name, l1-l2);
                   1799:     finame[l1-l2]= 0;
                   1800:   }
                   1801: 
                   1802:   return( 0 );                         /* we're done */
                   1803: }
                   1804: 
                   1805: 
                   1806: /******************************************/
                   1807: 
                   1808: void replace_back_to_slash(char *s, char*t)
                   1809: {
                   1810:   int i;
                   1811:   int lg=0;
                   1812:   i=0;
                   1813:   lg=strlen(t);
                   1814:   for(i=0; i<= lg; i++) {
                   1815:     (s[i] = t[i]);
                   1816:     if (t[i]== '\\') s[i]='/';
                   1817:   }
                   1818: }
                   1819: 
1.132     brouard  1820: char *trimbb(char *out, char *in)
1.137     brouard  1821: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1822:   char *s;
                   1823:   s=out;
                   1824:   while (*in != '\0'){
1.137     brouard  1825:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1826:       in++;
                   1827:     }
                   1828:     *out++ = *in++;
                   1829:   }
                   1830:   *out='\0';
                   1831:   return s;
                   1832: }
                   1833: 
1.351     brouard  1834: char *trimbtab(char *out, char *in)
                   1835: { /* Trim  blanks or tabs in line but keeps first blanks if line starts with blanks */
                   1836:   char *s;
                   1837:   s=out;
                   1838:   while (*in != '\0'){
                   1839:     while( (*in == ' ' || *in == '\t')){ /* && *(in+1) != '\0'){*/
                   1840:       in++;
                   1841:     }
                   1842:     *out++ = *in++;
                   1843:   }
                   1844:   *out='\0';
                   1845:   return s;
                   1846: }
                   1847: 
1.187     brouard  1848: /* char *substrchaine(char *out, char *in, char *chain) */
                   1849: /* { */
                   1850: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1851: /*   char *s, *t; */
                   1852: /*   t=in;s=out; */
                   1853: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1854: /*     *out++ = *in++; */
                   1855: /*   } */
                   1856: 
                   1857: /*   /\* *in matches *chain *\/ */
                   1858: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1859: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1860: /*   } */
                   1861: /*   in--; chain--; */
                   1862: /*   while ( (*in != '\0')){ */
                   1863: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1864: /*     *out++ = *in++; */
                   1865: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1866: /*   } */
                   1867: /*   *out='\0'; */
                   1868: /*   out=s; */
                   1869: /*   return out; */
                   1870: /* } */
                   1871: char *substrchaine(char *out, char *in, char *chain)
                   1872: {
                   1873:   /* Substract chain 'chain' from 'in', return and output 'out' */
1.349     brouard  1874:   /* in="V1+V1*age+age*age+V2", chain="+age*age" out="V1+V1*age+V2" */
1.187     brouard  1875: 
                   1876:   char *strloc;
                   1877: 
1.349     brouard  1878:   strcpy (out, in);                   /* out="V1+V1*age+age*age+V2" */
                   1879:   strloc = strstr(out, chain); /* strloc points to out at "+age*age+V2"  */
                   1880:   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  1881:   if(strloc != NULL){ 
1.349     brouard  1882:     /* will affect out */ /* strloc+strlen(chain)=|+V2 = "V1+V1*age+age*age|+V2" */ /* Will also work in Unicodek */
                   1883:     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)*/
                   1884:     /* equivalent to strcpy (strloc, strloc +strlen(chain)) if no overlap; Copies from "+V2" to V1+V1*age+ */
1.187     brouard  1885:   }
1.349     brouard  1886:   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  1887:   return out;
                   1888: }
                   1889: 
                   1890: 
1.145     brouard  1891: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1892: {
1.187     brouard  1893:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.349     brouard  1894:      and alocc starts after first occurence of char 'occ' : ex cutl(blocc,alocc,"abcdef2ghi2j",'2')
1.310     brouard  1895:      gives alocc="abcdef" and blocc="ghi2j".
1.145     brouard  1896:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1897:   */
1.160     brouard  1898:   char *s, *t;
1.145     brouard  1899:   t=in;s=in;
                   1900:   while ((*in != occ) && (*in != '\0')){
                   1901:     *alocc++ = *in++;
                   1902:   }
                   1903:   if( *in == occ){
                   1904:     *(alocc)='\0';
                   1905:     s=++in;
                   1906:   }
                   1907:  
                   1908:   if (s == t) {/* occ not found */
                   1909:     *(alocc-(in-s))='\0';
                   1910:     in=s;
                   1911:   }
                   1912:   while ( *in != '\0'){
                   1913:     *blocc++ = *in++;
                   1914:   }
                   1915: 
                   1916:   *blocc='\0';
                   1917:   return t;
                   1918: }
1.137     brouard  1919: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1920: {
1.187     brouard  1921:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1922:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1923:      gives blocc="abcdef2ghi" and alocc="j".
                   1924:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1925:   */
                   1926:   char *s, *t;
                   1927:   t=in;s=in;
                   1928:   while (*in != '\0'){
                   1929:     while( *in == occ){
                   1930:       *blocc++ = *in++;
                   1931:       s=in;
                   1932:     }
                   1933:     *blocc++ = *in++;
                   1934:   }
                   1935:   if (s == t) /* occ not found */
                   1936:     *(blocc-(in-s))='\0';
                   1937:   else
                   1938:     *(blocc-(in-s)-1)='\0';
                   1939:   in=s;
                   1940:   while ( *in != '\0'){
                   1941:     *alocc++ = *in++;
                   1942:   }
                   1943: 
                   1944:   *alocc='\0';
                   1945:   return s;
                   1946: }
                   1947: 
1.126     brouard  1948: int nbocc(char *s, char occ)
                   1949: {
                   1950:   int i,j=0;
                   1951:   int lg=20;
                   1952:   i=0;
                   1953:   lg=strlen(s);
                   1954:   for(i=0; i<= lg; i++) {
1.234     brouard  1955:     if  (s[i] == occ ) j++;
1.126     brouard  1956:   }
                   1957:   return j;
                   1958: }
                   1959: 
1.349     brouard  1960: int nboccstr(char *textin, char *chain)
                   1961: {
                   1962:   /* Counts the number of occurence of "chain"  in string textin */
                   1963:   /*  in="+V7*V4+age*V2+age*V3+age*V4"  chain="age" */
                   1964:   char *strloc;
                   1965:   
                   1966:   int i,j=0;
                   1967: 
                   1968:   i=0;
                   1969: 
                   1970:   strloc=textin; /* strloc points to "^+V7*V4+age+..." in textin */
                   1971:   for(;;) {
                   1972:     strloc= strstr(strloc,chain); /* strloc points to first character of chain in textin if found. Example strloc points^ to "+V7*V4+^age" in textin  */
                   1973:     if(strloc != NULL){
                   1974:       strloc = strloc+strlen(chain); /* strloc points to "+V7*V4+age^" in textin */
                   1975:       j++;
                   1976:     }else
                   1977:       break;
                   1978:   }
                   1979:   return j;
                   1980:   
                   1981: }
1.137     brouard  1982: /* void cutv(char *u,char *v, char*t, char occ) */
                   1983: /* { */
                   1984: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1985: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1986: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1987: /*   int i,lg,j,p=0; */
                   1988: /*   i=0; */
                   1989: /*   lg=strlen(t); */
                   1990: /*   for(j=0; j<=lg-1; j++) { */
                   1991: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1992: /*   } */
1.126     brouard  1993: 
1.137     brouard  1994: /*   for(j=0; j<p; j++) { */
                   1995: /*     (u[j] = t[j]); */
                   1996: /*   } */
                   1997: /*      u[p]='\0'; */
1.126     brouard  1998: 
1.137     brouard  1999: /*    for(j=0; j<= lg; j++) { */
                   2000: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   2001: /*   } */
                   2002: /* } */
1.126     brouard  2003: 
1.160     brouard  2004: #ifdef _WIN32
                   2005: char * strsep(char **pp, const char *delim)
                   2006: {
                   2007:   char *p, *q;
                   2008:          
                   2009:   if ((p = *pp) == NULL)
                   2010:     return 0;
                   2011:   if ((q = strpbrk (p, delim)) != NULL)
                   2012:   {
                   2013:     *pp = q + 1;
                   2014:     *q = '\0';
                   2015:   }
                   2016:   else
                   2017:     *pp = 0;
                   2018:   return p;
                   2019: }
                   2020: #endif
                   2021: 
1.126     brouard  2022: /********************** nrerror ********************/
                   2023: 
                   2024: void nrerror(char error_text[])
                   2025: {
                   2026:   fprintf(stderr,"ERREUR ...\n");
                   2027:   fprintf(stderr,"%s\n",error_text);
                   2028:   exit(EXIT_FAILURE);
                   2029: }
                   2030: /*********************** vector *******************/
                   2031: double *vector(int nl, int nh)
                   2032: {
                   2033:   double *v;
                   2034:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   2035:   if (!v) nrerror("allocation failure in vector");
                   2036:   return v-nl+NR_END;
                   2037: }
                   2038: 
                   2039: /************************ free vector ******************/
                   2040: void free_vector(double*v, int nl, int nh)
                   2041: {
                   2042:   free((FREE_ARG)(v+nl-NR_END));
                   2043: }
                   2044: 
                   2045: /************************ivector *******************************/
                   2046: int *ivector(long nl,long nh)
                   2047: {
                   2048:   int *v;
                   2049:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   2050:   if (!v) nrerror("allocation failure in ivector");
                   2051:   return v-nl+NR_END;
                   2052: }
                   2053: 
                   2054: /******************free ivector **************************/
                   2055: void free_ivector(int *v, long nl, long nh)
                   2056: {
                   2057:   free((FREE_ARG)(v+nl-NR_END));
                   2058: }
                   2059: 
                   2060: /************************lvector *******************************/
                   2061: long *lvector(long nl,long nh)
                   2062: {
                   2063:   long *v;
                   2064:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   2065:   if (!v) nrerror("allocation failure in ivector");
                   2066:   return v-nl+NR_END;
                   2067: }
                   2068: 
                   2069: /******************free lvector **************************/
                   2070: void free_lvector(long *v, long nl, long nh)
                   2071: {
                   2072:   free((FREE_ARG)(v+nl-NR_END));
                   2073: }
                   2074: 
                   2075: /******************* imatrix *******************************/
                   2076: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   2077:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   2078: { 
                   2079:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   2080:   int **m; 
                   2081:   
                   2082:   /* allocate pointers to rows */ 
                   2083:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   2084:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   2085:   m += NR_END; 
                   2086:   m -= nrl; 
                   2087:   
                   2088:   
                   2089:   /* allocate rows and set pointers to them */ 
                   2090:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   2091:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   2092:   m[nrl] += NR_END; 
                   2093:   m[nrl] -= ncl; 
                   2094:   
                   2095:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   2096:   
                   2097:   /* return pointer to array of pointers to rows */ 
                   2098:   return m; 
                   2099: } 
                   2100: 
                   2101: /****************** free_imatrix *************************/
                   2102: void free_imatrix(m,nrl,nrh,ncl,nch)
                   2103:       int **m;
                   2104:       long nch,ncl,nrh,nrl; 
                   2105:      /* free an int matrix allocated by imatrix() */ 
                   2106: { 
                   2107:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   2108:   free((FREE_ARG) (m+nrl-NR_END)); 
                   2109: } 
                   2110: 
                   2111: /******************* matrix *******************************/
                   2112: double **matrix(long nrl, long nrh, long ncl, long nch)
                   2113: {
                   2114:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   2115:   double **m;
                   2116: 
                   2117:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2118:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2119:   m += NR_END;
                   2120:   m -= nrl;
                   2121: 
                   2122:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2123:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2124:   m[nrl] += NR_END;
                   2125:   m[nrl] -= ncl;
                   2126: 
                   2127:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2128:   return m;
1.145     brouard  2129:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   2130: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   2131: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  2132:    */
                   2133: }
                   2134: 
                   2135: /*************************free matrix ************************/
                   2136: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   2137: {
                   2138:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2139:   free((FREE_ARG)(m+nrl-NR_END));
                   2140: }
                   2141: 
                   2142: /******************* ma3x *******************************/
                   2143: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   2144: {
                   2145:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   2146:   double ***m;
                   2147: 
                   2148:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2149:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2150:   m += NR_END;
                   2151:   m -= nrl;
                   2152: 
                   2153:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2154:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2155:   m[nrl] += NR_END;
                   2156:   m[nrl] -= ncl;
                   2157: 
                   2158:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2159: 
                   2160:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   2161:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   2162:   m[nrl][ncl] += NR_END;
                   2163:   m[nrl][ncl] -= nll;
                   2164:   for (j=ncl+1; j<=nch; j++) 
                   2165:     m[nrl][j]=m[nrl][j-1]+nlay;
                   2166:   
                   2167:   for (i=nrl+1; i<=nrh; i++) {
                   2168:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   2169:     for (j=ncl+1; j<=nch; j++) 
                   2170:       m[i][j]=m[i][j-1]+nlay;
                   2171:   }
                   2172:   return m; 
                   2173:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   2174:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   2175:   */
                   2176: }
                   2177: 
                   2178: /*************************free ma3x ************************/
                   2179: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   2180: {
                   2181:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   2182:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2183:   free((FREE_ARG)(m+nrl-NR_END));
                   2184: }
                   2185: 
                   2186: /*************** function subdirf ***********/
                   2187: char *subdirf(char fileres[])
                   2188: {
                   2189:   /* Caution optionfilefiname is hidden */
                   2190:   strcpy(tmpout,optionfilefiname);
                   2191:   strcat(tmpout,"/"); /* Add to the right */
                   2192:   strcat(tmpout,fileres);
                   2193:   return tmpout;
                   2194: }
                   2195: 
                   2196: /*************** function subdirf2 ***********/
                   2197: char *subdirf2(char fileres[], char *preop)
                   2198: {
1.314     brouard  2199:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
                   2200:  Errors in subdirf, 2, 3 while printing tmpout is
1.315     brouard  2201:  rewritten within the same printf. Workaround: many printfs */
1.126     brouard  2202:   /* Caution optionfilefiname is hidden */
                   2203:   strcpy(tmpout,optionfilefiname);
                   2204:   strcat(tmpout,"/");
                   2205:   strcat(tmpout,preop);
                   2206:   strcat(tmpout,fileres);
                   2207:   return tmpout;
                   2208: }
                   2209: 
                   2210: /*************** function subdirf3 ***********/
                   2211: char *subdirf3(char fileres[], char *preop, char *preop2)
                   2212: {
                   2213:   
                   2214:   /* Caution optionfilefiname is hidden */
                   2215:   strcpy(tmpout,optionfilefiname);
                   2216:   strcat(tmpout,"/");
                   2217:   strcat(tmpout,preop);
                   2218:   strcat(tmpout,preop2);
                   2219:   strcat(tmpout,fileres);
                   2220:   return tmpout;
                   2221: }
1.213     brouard  2222:  
                   2223: /*************** function subdirfext ***********/
                   2224: char *subdirfext(char fileres[], char *preop, char *postop)
                   2225: {
                   2226:   
                   2227:   strcpy(tmpout,preop);
                   2228:   strcat(tmpout,fileres);
                   2229:   strcat(tmpout,postop);
                   2230:   return tmpout;
                   2231: }
1.126     brouard  2232: 
1.213     brouard  2233: /*************** function subdirfext3 ***********/
                   2234: char *subdirfext3(char fileres[], char *preop, char *postop)
                   2235: {
                   2236:   
                   2237:   /* Caution optionfilefiname is hidden */
                   2238:   strcpy(tmpout,optionfilefiname);
                   2239:   strcat(tmpout,"/");
                   2240:   strcat(tmpout,preop);
                   2241:   strcat(tmpout,fileres);
                   2242:   strcat(tmpout,postop);
                   2243:   return tmpout;
                   2244: }
                   2245:  
1.162     brouard  2246: char *asc_diff_time(long time_sec, char ascdiff[])
                   2247: {
                   2248:   long sec_left, days, hours, minutes;
                   2249:   days = (time_sec) / (60*60*24);
                   2250:   sec_left = (time_sec) % (60*60*24);
                   2251:   hours = (sec_left) / (60*60) ;
                   2252:   sec_left = (sec_left) %(60*60);
                   2253:   minutes = (sec_left) /60;
                   2254:   sec_left = (sec_left) % (60);
                   2255:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   2256:   return ascdiff;
                   2257: }
                   2258: 
1.126     brouard  2259: /***************** f1dim *************************/
                   2260: extern int ncom; 
                   2261: extern double *pcom,*xicom;
                   2262: extern double (*nrfunc)(double []); 
                   2263:  
                   2264: double f1dim(double x) 
                   2265: { 
                   2266:   int j; 
                   2267:   double f;
                   2268:   double *xt; 
                   2269:  
                   2270:   xt=vector(1,ncom); 
                   2271:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   2272:   f=(*nrfunc)(xt); 
                   2273:   free_vector(xt,1,ncom); 
                   2274:   return f; 
                   2275: } 
                   2276: 
                   2277: /*****************brent *************************/
                   2278: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  2279: {
                   2280:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   2281:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   2282:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   2283:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   2284:    * returned function value. 
                   2285:   */
1.126     brouard  2286:   int iter; 
                   2287:   double a,b,d,etemp;
1.159     brouard  2288:   double fu=0,fv,fw,fx;
1.164     brouard  2289:   double ftemp=0.;
1.126     brouard  2290:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   2291:   double e=0.0; 
                   2292:  
                   2293:   a=(ax < cx ? ax : cx); 
                   2294:   b=(ax > cx ? ax : cx); 
                   2295:   x=w=v=bx; 
                   2296:   fw=fv=fx=(*f)(x); 
                   2297:   for (iter=1;iter<=ITMAX;iter++) { 
                   2298:     xm=0.5*(a+b); 
                   2299:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   2300:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   2301:     printf(".");fflush(stdout);
                   2302:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  2303: #ifdef DEBUGBRENT
1.126     brouard  2304:     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);
                   2305:     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);
                   2306:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   2307: #endif
                   2308:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   2309:       *xmin=x; 
                   2310:       return fx; 
                   2311:     } 
                   2312:     ftemp=fu;
                   2313:     if (fabs(e) > tol1) { 
                   2314:       r=(x-w)*(fx-fv); 
                   2315:       q=(x-v)*(fx-fw); 
                   2316:       p=(x-v)*q-(x-w)*r; 
                   2317:       q=2.0*(q-r); 
                   2318:       if (q > 0.0) p = -p; 
                   2319:       q=fabs(q); 
                   2320:       etemp=e; 
                   2321:       e=d; 
                   2322:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  2323:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  2324:       else { 
1.224     brouard  2325:                                d=p/q; 
                   2326:                                u=x+d; 
                   2327:                                if (u-a < tol2 || b-u < tol2) 
                   2328:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  2329:       } 
                   2330:     } else { 
                   2331:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2332:     } 
                   2333:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   2334:     fu=(*f)(u); 
                   2335:     if (fu <= fx) { 
                   2336:       if (u >= x) a=x; else b=x; 
                   2337:       SHFT(v,w,x,u) 
1.183     brouard  2338:       SHFT(fv,fw,fx,fu) 
                   2339:     } else { 
                   2340:       if (u < x) a=u; else b=u; 
                   2341:       if (fu <= fw || w == x) { 
1.224     brouard  2342:                                v=w; 
                   2343:                                w=u; 
                   2344:                                fv=fw; 
                   2345:                                fw=fu; 
1.183     brouard  2346:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  2347:                                v=u; 
                   2348:                                fv=fu; 
1.183     brouard  2349:       } 
                   2350:     } 
1.126     brouard  2351:   } 
                   2352:   nrerror("Too many iterations in brent"); 
                   2353:   *xmin=x; 
                   2354:   return fx; 
                   2355: } 
                   2356: 
                   2357: /****************** mnbrak ***********************/
                   2358: 
                   2359: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2360:            double (*func)(double)) 
1.183     brouard  2361: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2362: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2363: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2364: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2365:    */
1.126     brouard  2366:   double ulim,u,r,q, dum;
                   2367:   double fu; 
1.187     brouard  2368: 
                   2369:   double scale=10.;
                   2370:   int iterscale=0;
                   2371: 
                   2372:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2373:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2374: 
                   2375: 
                   2376:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2377:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2378:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2379:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2380:   /* } */
                   2381: 
1.126     brouard  2382:   if (*fb > *fa) { 
                   2383:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2384:     SHFT(dum,*fb,*fa,dum) 
                   2385:   } 
1.126     brouard  2386:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2387:   *fc=(*func)(*cx); 
1.183     brouard  2388: #ifdef DEBUG
1.224     brouard  2389:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2390:   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  2391: #endif
1.224     brouard  2392:   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  2393:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2394:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2395:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2396:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2397:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2398:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2399:       fu=(*func)(u); 
1.163     brouard  2400: #ifdef DEBUG
                   2401:       /* f(x)=A(x-u)**2+f(u) */
                   2402:       double A, fparabu; 
                   2403:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2404:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2405:       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);
                   2406:       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  2407:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2408:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2409:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2410:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2411: #endif 
1.184     brouard  2412: #ifdef MNBRAKORIGINAL
1.183     brouard  2413: #else
1.191     brouard  2414: /*       if (fu > *fc) { */
                   2415: /* #ifdef DEBUG */
                   2416: /*       printf("mnbrak4  fu > fc \n"); */
                   2417: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2418: /* #endif */
                   2419: /*     /\* 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 *\\/  *\/ */
                   2420: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2421: /*     dum=u; /\* Shifting c and u *\/ */
                   2422: /*     u = *cx; */
                   2423: /*     *cx = dum; */
                   2424: /*     dum = fu; */
                   2425: /*     fu = *fc; */
                   2426: /*     *fc =dum; */
                   2427: /*       } else { /\* end *\/ */
                   2428: /* #ifdef DEBUG */
                   2429: /*       printf("mnbrak3  fu < fc \n"); */
                   2430: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2431: /* #endif */
                   2432: /*     dum=u; /\* Shifting c and u *\/ */
                   2433: /*     u = *cx; */
                   2434: /*     *cx = dum; */
                   2435: /*     dum = fu; */
                   2436: /*     fu = *fc; */
                   2437: /*     *fc =dum; */
                   2438: /*       } */
1.224     brouard  2439: #ifdef DEBUGMNBRAK
                   2440:                 double A, fparabu; 
                   2441:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2442:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2443:      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);
                   2444:      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  2445: #endif
1.191     brouard  2446:       dum=u; /* Shifting c and u */
                   2447:       u = *cx;
                   2448:       *cx = dum;
                   2449:       dum = fu;
                   2450:       fu = *fc;
                   2451:       *fc =dum;
1.183     brouard  2452: #endif
1.162     brouard  2453:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2454: #ifdef DEBUG
1.224     brouard  2455:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2456:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2457: #endif
1.126     brouard  2458:       fu=(*func)(u); 
                   2459:       if (fu < *fc) { 
1.183     brouard  2460: #ifdef DEBUG
1.224     brouard  2461:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2462:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2463: #endif
                   2464:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2465:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2466: #ifdef DEBUG
                   2467:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2468: #endif
                   2469:       } 
1.162     brouard  2470:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2471: #ifdef DEBUG
1.224     brouard  2472:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2473:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2474: #endif
1.126     brouard  2475:       u=ulim; 
                   2476:       fu=(*func)(u); 
1.183     brouard  2477:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2478: #ifdef DEBUG
1.224     brouard  2479:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2480:       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  2481: #endif
1.126     brouard  2482:       u=(*cx)+GOLD*(*cx-*bx); 
                   2483:       fu=(*func)(u); 
1.224     brouard  2484: #ifdef DEBUG
                   2485:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2486:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2487: #endif
1.183     brouard  2488:     } /* end tests */
1.126     brouard  2489:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2490:     SHFT(*fa,*fb,*fc,fu) 
                   2491: #ifdef DEBUG
1.224     brouard  2492:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2493:       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  2494: #endif
                   2495:   } /* 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  2496: } 
                   2497: 
                   2498: /*************** linmin ************************/
1.162     brouard  2499: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2500: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2501: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2502: the value of func at the returned location p . This is actually all accomplished by calling the
                   2503: routines mnbrak and brent .*/
1.126     brouard  2504: int ncom; 
                   2505: double *pcom,*xicom;
                   2506: double (*nrfunc)(double []); 
                   2507:  
1.224     brouard  2508: #ifdef LINMINORIGINAL
1.126     brouard  2509: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2510: #else
                   2511: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2512: #endif
1.126     brouard  2513: { 
                   2514:   double brent(double ax, double bx, double cx, 
                   2515:               double (*f)(double), double tol, double *xmin); 
                   2516:   double f1dim(double x); 
                   2517:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2518:              double *fc, double (*func)(double)); 
                   2519:   int j; 
                   2520:   double xx,xmin,bx,ax; 
                   2521:   double fx,fb,fa;
1.187     brouard  2522: 
1.203     brouard  2523: #ifdef LINMINORIGINAL
                   2524: #else
                   2525:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2526: #endif
                   2527:   
1.126     brouard  2528:   ncom=n; 
                   2529:   pcom=vector(1,n); 
                   2530:   xicom=vector(1,n); 
                   2531:   nrfunc=func; 
                   2532:   for (j=1;j<=n;j++) { 
                   2533:     pcom[j]=p[j]; 
1.202     brouard  2534:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2535:   } 
1.187     brouard  2536: 
1.203     brouard  2537: #ifdef LINMINORIGINAL
                   2538:   xx=1.;
                   2539: #else
                   2540:   axs=0.0;
                   2541:   xxs=1.;
                   2542:   do{
                   2543:     xx= xxs;
                   2544: #endif
1.187     brouard  2545:     ax=0.;
                   2546:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2547:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2548:     /* 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))   */
                   2549:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2550:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2551:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2552:     /* 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  2553: #ifdef LINMINORIGINAL
                   2554: #else
                   2555:     if (fx != fx){
1.224     brouard  2556:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2557:                        printf("|");
                   2558:                        fprintf(ficlog,"|");
1.203     brouard  2559: #ifdef DEBUGLINMIN
1.224     brouard  2560:                        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  2561: #endif
                   2562:     }
1.224     brouard  2563:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2564: #endif
                   2565:   
1.191     brouard  2566: #ifdef DEBUGLINMIN
                   2567:   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  2568:   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  2569: #endif
1.224     brouard  2570: #ifdef LINMINORIGINAL
                   2571: #else
1.317     brouard  2572:   if(fb == fx){ /* Flat function in the direction */
                   2573:     xmin=xx;
1.224     brouard  2574:     *flat=1;
1.317     brouard  2575:   }else{
1.224     brouard  2576:     *flat=0;
                   2577: #endif
                   2578:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2579:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2580:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2581:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2582:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2583:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2584: #ifdef DEBUG
1.224     brouard  2585:   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);
                   2586:   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);
                   2587: #endif
                   2588: #ifdef LINMINORIGINAL
                   2589: #else
                   2590:                        }
1.126     brouard  2591: #endif
1.191     brouard  2592: #ifdef DEBUGLINMIN
                   2593:   printf("linmin end ");
1.202     brouard  2594:   fprintf(ficlog,"linmin end ");
1.191     brouard  2595: #endif
1.126     brouard  2596:   for (j=1;j<=n;j++) { 
1.203     brouard  2597: #ifdef LINMINORIGINAL
                   2598:     xi[j] *= xmin; 
                   2599: #else
                   2600: #ifdef DEBUGLINMIN
                   2601:     if(xxs <1.0)
                   2602:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2603: #endif
                   2604:     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) */
                   2605: #ifdef DEBUGLINMIN
                   2606:     if(xxs <1.0)
                   2607:       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 );
                   2608: #endif
                   2609: #endif
1.187     brouard  2610:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2611:   } 
1.191     brouard  2612: #ifdef DEBUGLINMIN
1.203     brouard  2613:   printf("\n");
1.191     brouard  2614:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2615:   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  2616:   for (j=1;j<=n;j++) { 
1.202     brouard  2617:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2618:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2619:     if(j % ncovmodel == 0){
1.191     brouard  2620:       printf("\n");
1.202     brouard  2621:       fprintf(ficlog,"\n");
                   2622:     }
1.191     brouard  2623:   }
1.203     brouard  2624: #else
1.191     brouard  2625: #endif
1.126     brouard  2626:   free_vector(xicom,1,n); 
                   2627:   free_vector(pcom,1,n); 
                   2628: } 
                   2629: 
                   2630: 
                   2631: /*************** powell ************************/
1.162     brouard  2632: /*
1.317     brouard  2633: Minimization of a function func of n variables. Input consists in an initial starting point
                   2634: p[1..n] ; an initial matrix xi[1..n][1..n]  whose columns contain the initial set of di-
                   2635: rections (usually the n unit vectors); and ftol, the fractional tolerance in the function value
                   2636: such that failure to decrease by more than this amount in one iteration signals doneness. On
1.162     brouard  2637: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2638: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2639:  */
1.224     brouard  2640: #ifdef LINMINORIGINAL
                   2641: #else
                   2642:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2643:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2644: #endif
1.126     brouard  2645: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2646:            double (*func)(double [])) 
                   2647: { 
1.224     brouard  2648: #ifdef LINMINORIGINAL
                   2649:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2650:              double (*func)(double [])); 
1.224     brouard  2651: #else 
1.241     brouard  2652:  void linmin(double p[], double xi[], int n, double *fret,
                   2653:             double (*func)(double []),int *flat); 
1.224     brouard  2654: #endif
1.239     brouard  2655:  int i,ibig,j,jk,k; 
1.126     brouard  2656:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2657:   double directest;
1.126     brouard  2658:   double fp,fptt;
                   2659:   double *xits;
                   2660:   int niterf, itmp;
1.349     brouard  2661:   int Bigter=0, nBigterf=1;
                   2662:   
1.126     brouard  2663:   pt=vector(1,n); 
                   2664:   ptt=vector(1,n); 
                   2665:   xit=vector(1,n); 
                   2666:   xits=vector(1,n); 
                   2667:   *fret=(*func)(p); 
                   2668:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.338     brouard  2669:   rcurr_time = time(NULL);
                   2670:   fp=(*fret); /* Initialisation */
1.126     brouard  2671:   for (*iter=1;;++(*iter)) { 
                   2672:     ibig=0; 
                   2673:     del=0.0; 
1.157     brouard  2674:     rlast_time=rcurr_time;
1.349     brouard  2675:     rlast_btime=rcurr_time;
1.157     brouard  2676:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2677:     rcurr_time = time(NULL);  
                   2678:     curr_time = *localtime(&rcurr_time);
1.337     brouard  2679:     /* 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); */
                   2680:     /* 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  2681:     Bigter=(*iter - *iter % ncovmodel)/ncovmodel +1; /* Big iteration, i.e on ncovmodel cycle */
                   2682:     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);
                   2683:     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);
                   2684:     fprintf(ficrespow,"%d %d %.12f %d",*iter,Bigter, *fret,curr_time.tm_sec-start_time.tm_sec);
1.324     brouard  2685:     fp=(*fret); /* From former iteration or initial value */
1.192     brouard  2686:     for (i=1;i<=n;i++) {
1.126     brouard  2687:       fprintf(ficrespow," %.12lf", p[i]);
                   2688:     }
1.239     brouard  2689:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2690:     printf("\n#model=  1      +     age ");
                   2691:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2692:     if(nagesqr==1){
1.241     brouard  2693:        printf("  + age*age  ");
                   2694:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2695:     }
                   2696:     for(j=1;j <=ncovmodel-2;j++){
                   2697:       if(Typevar[j]==0) {
                   2698:        printf("  +      V%d  ",Tvar[j]);
                   2699:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2700:       }else if(Typevar[j]==1) {
                   2701:        printf("  +    V%d*age ",Tvar[j]);
                   2702:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2703:       }else if(Typevar[j]==2) {
                   2704:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2705:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  2706:       }else if(Typevar[j]==3) {
                   2707:        printf("  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2708:        fprintf(ficlog,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.239     brouard  2709:       }
                   2710:     }
1.126     brouard  2711:     printf("\n");
1.239     brouard  2712: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2713: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2714:     fprintf(ficlog,"\n");
1.239     brouard  2715:     for(i=1,jk=1; i <=nlstate; i++){
                   2716:       for(k=1; k <=(nlstate+ndeath); k++){
                   2717:        if (k != i) {
                   2718:          printf("%d%d ",i,k);
                   2719:          fprintf(ficlog,"%d%d ",i,k);
                   2720:          for(j=1; j <=ncovmodel; j++){
                   2721:            printf("%12.7f ",p[jk]);
                   2722:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2723:            jk++; 
                   2724:          }
                   2725:          printf("\n");
                   2726:          fprintf(ficlog,"\n");
                   2727:        }
                   2728:       }
                   2729:     }
1.241     brouard  2730:     if(*iter <=3 && *iter >1){
1.157     brouard  2731:       tml = *localtime(&rcurr_time);
                   2732:       strcpy(strcurr,asctime(&tml));
                   2733:       rforecast_time=rcurr_time; 
1.126     brouard  2734:       itmp = strlen(strcurr);
                   2735:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2736:        strcurr[itmp-1]='\0';
1.162     brouard  2737:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2738:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.349     brouard  2739:       for(nBigterf=1;nBigterf<=31;nBigterf+=10){
                   2740:        niterf=nBigterf*ncovmodel;
                   2741:        /* rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time); */
1.241     brouard  2742:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2743:        forecast_time = *localtime(&rforecast_time);
                   2744:        strcpy(strfor,asctime(&forecast_time));
                   2745:        itmp = strlen(strfor);
                   2746:        if(strfor[itmp-1]=='\n')
                   2747:          strfor[itmp-1]='\0';
1.349     brouard  2748:        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);
                   2749:        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  2750:       }
                   2751:     }
1.187     brouard  2752:     for (i=1;i<=n;i++) { /* For each direction i */
                   2753:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2754:       fptt=(*fret); 
                   2755: #ifdef DEBUG
1.203     brouard  2756:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2757:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2758: #endif
1.203     brouard  2759:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2760:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2761: #ifdef LINMINORIGINAL
1.357     brouard  2762:       linmin(p,xit,n,fret,func); /* New point i minimizing in direction i has coordinates p[j].*/
                   2763:       /* xit[j] gives the n coordinates of direction i as input.*/
                   2764:       /* *fret gives the maximum value on direction xit */
1.224     brouard  2765: #else
                   2766:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2767:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2768: #endif
                   2769:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2770:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2771:                                /* because that direction will be replaced unless the gain del is small */
                   2772:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2773:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2774:                                /* with the new direction. */
                   2775:                                del=fabs(fptt-(*fret)); 
                   2776:                                ibig=i; 
1.126     brouard  2777:       } 
                   2778: #ifdef DEBUG
                   2779:       printf("%d %.12e",i,(*fret));
                   2780:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2781:       for (j=1;j<=n;j++) {
1.224     brouard  2782:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2783:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2784:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2785:       }
                   2786:       for(j=1;j<=n;j++) {
1.225     brouard  2787:                                printf(" p(%d)=%.12e",j,p[j]);
                   2788:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2789:       }
                   2790:       printf("\n");
                   2791:       fprintf(ficlog,"\n");
                   2792: #endif
1.187     brouard  2793:     } /* end loop on each direction i */
1.357     brouard  2794:     /* Convergence test will use last linmin estimation (fret) and compare to former iteration (fp) */ 
1.188     brouard  2795:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.319     brouard  2796:     for(j=1;j<=n;j++) {
                   2797:       if(flatdir[j] >0){
                   2798:         printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2799:         fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
1.302     brouard  2800:       }
1.319     brouard  2801:       /* printf("\n"); */
                   2802:       /* fprintf(ficlog,"\n"); */
                   2803:     }
1.243     brouard  2804:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2805:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2806:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2807:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2808:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2809:       /* decreased of more than 3.84  */
                   2810:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2811:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2812:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2813:                        
1.188     brouard  2814:       /* Starting the program with initial values given by a former maximization will simply change */
                   2815:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2816:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2817:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2818: #ifdef DEBUG
                   2819:       int k[2],l;
                   2820:       k[0]=1;
                   2821:       k[1]=-1;
                   2822:       printf("Max: %.12e",(*func)(p));
                   2823:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2824:       for (j=1;j<=n;j++) {
                   2825:        printf(" %.12e",p[j]);
                   2826:        fprintf(ficlog," %.12e",p[j]);
                   2827:       }
                   2828:       printf("\n");
                   2829:       fprintf(ficlog,"\n");
                   2830:       for(l=0;l<=1;l++) {
                   2831:        for (j=1;j<=n;j++) {
                   2832:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2833:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2834:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2835:        }
                   2836:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2837:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2838:       }
                   2839: #endif
                   2840: 
                   2841:       free_vector(xit,1,n); 
                   2842:       free_vector(xits,1,n); 
                   2843:       free_vector(ptt,1,n); 
                   2844:       free_vector(pt,1,n); 
                   2845:       return; 
1.192     brouard  2846:     } /* enough precision */ 
1.240     brouard  2847:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2848:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2849:       ptt[j]=2.0*p[j]-pt[j]; 
                   2850:       xit[j]=p[j]-pt[j]; 
                   2851:       pt[j]=p[j]; 
                   2852:     } 
1.181     brouard  2853:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2854: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2855:                if (*iter <=4) {
1.225     brouard  2856: #else
                   2857: #endif
1.224     brouard  2858: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2859: #else
1.161     brouard  2860:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2861: #endif
1.162     brouard  2862:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2863:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2864:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2865:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2866:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2867:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2868:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2869:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2870:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2871:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2872:       /* mu² and del² are equal when f3=f1 */
                   2873:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2874:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2875:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2876:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2877: #ifdef NRCORIGINAL
                   2878:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2879: #else
                   2880:       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  2881:       t= t- del*SQR(fp-fptt);
1.183     brouard  2882: #endif
1.202     brouard  2883:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2884: #ifdef DEBUG
1.181     brouard  2885:       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);
                   2886:       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  2887:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2888:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2889:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2890:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2891:       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);
                   2892:       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);
                   2893: #endif
1.183     brouard  2894: #ifdef POWELLORIGINAL
                   2895:       if (t < 0.0) { /* Then we use it for new direction */
                   2896: #else
1.182     brouard  2897:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2898:                                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  2899:         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  2900:         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  2901:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2902:       } 
1.181     brouard  2903:       if (directest < 0.0) { /* Then we use it for new direction */
                   2904: #endif
1.191     brouard  2905: #ifdef DEBUGLINMIN
1.234     brouard  2906:        printf("Before linmin in direction P%d-P0\n",n);
                   2907:        for (j=1;j<=n;j++) {
                   2908:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2909:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2910:          if(j % ncovmodel == 0){
                   2911:            printf("\n");
                   2912:            fprintf(ficlog,"\n");
                   2913:          }
                   2914:        }
1.224     brouard  2915: #endif
                   2916: #ifdef LINMINORIGINAL
1.234     brouard  2917:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2918: #else
1.234     brouard  2919:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2920:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2921: #endif
1.234     brouard  2922:        
1.191     brouard  2923: #ifdef DEBUGLINMIN
1.234     brouard  2924:        for (j=1;j<=n;j++) { 
                   2925:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2926:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2927:          if(j % ncovmodel == 0){
                   2928:            printf("\n");
                   2929:            fprintf(ficlog,"\n");
                   2930:          }
                   2931:        }
1.224     brouard  2932: #endif
1.357     brouard  2933: #ifdef POWELLORIGINCONJUGATE
1.234     brouard  2934:        for (j=1;j<=n;j++) { 
                   2935:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2936:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2937:        }
1.357     brouard  2938: #else
                   2939:        for (j=1;j<=n-1;j++) { 
                   2940:          xi[j][1]=xi[j][j+1]; /* Standard method of conjugate directions */
                   2941:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2942:        }
                   2943: #endif
1.224     brouard  2944: #ifdef LINMINORIGINAL
                   2945: #else
1.234     brouard  2946:        for (j=1, flatd=0;j<=n;j++) {
                   2947:          if(flatdir[j]>0)
                   2948:            flatd++;
                   2949:        }
                   2950:        if(flatd >0){
1.255     brouard  2951:          printf("%d flat directions: ",flatd);
                   2952:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  2953:          for (j=1;j<=n;j++) { 
                   2954:            if(flatdir[j]>0){
                   2955:              printf("%d ",j);
                   2956:              fprintf(ficlog,"%d ",j);
                   2957:            }
                   2958:          }
                   2959:          printf("\n");
                   2960:          fprintf(ficlog,"\n");
1.319     brouard  2961: #ifdef FLATSUP
                   2962:           free_vector(xit,1,n); 
                   2963:           free_vector(xits,1,n); 
                   2964:           free_vector(ptt,1,n); 
                   2965:           free_vector(pt,1,n); 
                   2966:           return;
                   2967: #endif
1.234     brouard  2968:        }
1.191     brouard  2969: #endif
1.234     brouard  2970:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2971:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.357     brouard  2972:   /* The minimization in direction $\xi_1$ gives $P_1$. From $P_1$ minimization in direction $\xi_2$ gives */
                   2973:   /* $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 */
                   2974:   /* direction $\xi_1^{(1)}=\xi_2$. Also second direction is replaced by new direction $\xi^{(1)}_2=P_2-P_0$. */
                   2975: 
                   2976:   /* At the second iteration, starting from $P_0^{(1)}$, minimization amongst $\xi^{(1)}_1$ gives point $P^{(1)}_1$. */
                   2977:   /* Minimization amongst $\xi^{(1)}_2=(P_2-P_0)$ gives point $P^{(1)}_2$.  As $P^{(2)}_1$ and */
                   2978:   /* $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$ */
                   2979:   /* and $P_2-P_0$ (parallel to $\xi$ and $\xi^c$) are conjugate.  } */
                   2980: 
1.234     brouard  2981:        
1.126     brouard  2982: #ifdef DEBUG
1.234     brouard  2983:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2984:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2985:        for(j=1;j<=n;j++){
                   2986:          printf(" %lf",xit[j]);
                   2987:          fprintf(ficlog," %lf",xit[j]);
                   2988:        }
                   2989:        printf("\n");
                   2990:        fprintf(ficlog,"\n");
1.126     brouard  2991: #endif
1.192     brouard  2992:       } /* end of t or directest negative */
1.224     brouard  2993: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2994: #else
1.234     brouard  2995:       } /* end if (fptt < fp)  */
1.192     brouard  2996: #endif
1.225     brouard  2997: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2998:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2999: #else
1.224     brouard  3000: #endif
1.234     brouard  3001:                } /* loop iteration */ 
1.126     brouard  3002: } 
1.234     brouard  3003:   
1.126     brouard  3004: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  3005:   
1.235     brouard  3006:   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  3007:   {
1.338     brouard  3008:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij . Nicely done
1.279     brouard  3009:      *   (and selected quantitative values in nres)
                   3010:      *  by left multiplying the unit
                   3011:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   3012:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   3013:      * Wx is row vector: population in state 1, population in state 2, population dead
                   3014:      * or prevalence in state 1, prevalence in state 2, 0
                   3015:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   3016:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   3017:      * Output is prlim.
                   3018:      * Initial matrix pimij 
                   3019:      */
1.206     brouard  3020:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   3021:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   3022:   /*  0,                   0                  , 1} */
                   3023:   /*
                   3024:    * and after some iteration: */
                   3025:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   3026:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   3027:   /*  0,                   0                  , 1} */
                   3028:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   3029:   /* {0.51571254859325999, 0.4842874514067399, */
                   3030:   /*  0.51326036147820708, 0.48673963852179264} */
                   3031:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  3032:     
1.332     brouard  3033:     int i, ii,j,k, k1;
1.209     brouard  3034:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  3035:   /* double **matprod2(); */ /* test */
1.218     brouard  3036:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  3037:   double **newm;
1.209     brouard  3038:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  3039:   int ncvloop=0;
1.288     brouard  3040:   int first=0;
1.169     brouard  3041:   
1.209     brouard  3042:   min=vector(1,nlstate);
                   3043:   max=vector(1,nlstate);
                   3044:   meandiff=vector(1,nlstate);
                   3045: 
1.218     brouard  3046:        /* Starting with matrix unity */
1.126     brouard  3047:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   3048:     for (j=1;j<=nlstate+ndeath;j++){
                   3049:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3050:     }
1.169     brouard  3051:   
                   3052:   cov[1]=1.;
                   3053:   
                   3054:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  3055:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  3056:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  3057:     ncvloop++;
1.126     brouard  3058:     newm=savm;
                   3059:     /* Covariates have to be included here again */
1.138     brouard  3060:     cov[2]=agefin;
1.319     brouard  3061:      if(nagesqr==1){
                   3062:       cov[3]= agefin*agefin;
                   3063:      }
1.332     brouard  3064:      /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   3065:      /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   3066:      for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  3067:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  3068:         cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   3069:        }else{
                   3070:         cov[2+nagesqr+k1]=precov[nres][k1];
                   3071:        }
                   3072:      }/* End of loop on model equation */
                   3073:      
                   3074: /* Start of old code (replaced by a loop on position in the model equation */
                   3075:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only of the model *\/ */
                   3076:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   3077:     /*   /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; *\/ */
                   3078:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TnsdVar[TvarsD[k]])]; */
                   3079:     /*   /\* model = 1 +age + V1*V3 + age*V1 + V2 + V1 + age*V2 + V3 + V3*age + V1*V2  */
                   3080:     /*    * k                  1        2      3    4      5      6     7        8 */
                   3081:     /*    *cov[]   1    2      3        4      5    6      7      8     9       10 */
                   3082:     /*    *TypeVar[k]          2        1      0    0      1      0     1        2 */
                   3083:     /*    *Dummy[k]            0        2      0    0      2      0     2        0 */
                   3084:     /*    *Tvar[k]             4        1      2    1      2      3     3        5 */
                   3085:     /*    *nsd=3                              (1)  (2)           (3) */
                   3086:     /*    *TvarsD[nsd]                      [1]=2    1             3 */
                   3087:     /*    *TnsdVar                          [2]=2 [1]=1         [3]=3 */
                   3088:     /*    *TvarsDind[nsd](=k)               [1]=3 [2]=4         [3]=6 */
                   3089:     /*    *Tage[]                  [1]=1                  [2]=2      [3]=3 */
                   3090:     /*    *Tvard[]       [1][1]=1                                           [2][1]=1 */
                   3091:     /*    *                   [1][2]=3                                           [2][2]=2 */
                   3092:     /*    *Tprod[](=k)     [1]=1                                              [2]=8 */
                   3093:     /*    *TvarsDp(=Tvar)   [1]=1            [2]=2             [3]=3          [4]=5 */
                   3094:     /*    *TvarD (=k)       [1]=1            [2]=3 [3]=4       [3]=6          [4]=6 */
                   3095:     /*    *TvarsDpType */
                   3096:     /*    *si model= 1 + age + V3 + V2*age + V2 + V3*age */
                   3097:     /*    * nsd=1              (1)           (2) */
                   3098:     /*    *TvarsD[nsd]          3             2 */
                   3099:     /*    *TnsdVar           (3)=1          (2)=2 */
                   3100:     /*    *TvarsDind[nsd](=k)  [1]=1        [2]=3 */
                   3101:     /*    *Tage[]                  [1]=2           [2]= 3    */
                   3102:     /*    *\/ */
                   3103:     /*   /\* cov[++k1]=nbcode[TvarsD[k]][codtabm(ij,k)]; *\/ */
                   3104:     /*   /\* 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)); *\/ */
                   3105:     /* } */
                   3106:     /* for (k=1; k<=nsq;k++) { /\* For single quantitative varying covariates only of the model *\/ */
                   3107:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3108:     /*   /\* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 *\/ */
                   3109:     /*   /\* cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   3110:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][resultmodel[nres][k1]] */
                   3111:     /*   /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   3112:     /*   /\* 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]); *\/ */
                   3113:     /* } */
                   3114:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   3115:     /*   if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   3116:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3117:     /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   3118:     /*   } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   3119:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   3120:     /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   3121:     /*   } */
                   3122:     /*   /\* 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]); *\/ */
                   3123:     /* } */
                   3124:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   3125:     /*   /\* 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]); *\/ */
                   3126:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3127:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3128:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3129:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3130:     /*         }else{ */
                   3131:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3132:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   3133:     /*         } */
                   3134:     /*   }else{ */
                   3135:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3136:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3137:     /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   3138:     /*         }else{ */
                   3139:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3140:     /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   3141:     /*         } */
                   3142:     /*   } */
                   3143:     /* } /\* End product without age *\/ */
                   3144: /* ENd of old code */
1.138     brouard  3145:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3146:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3147:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  3148:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3149:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.319     brouard  3150:     /* age and covariate values of ij are in 'cov' */
1.142     brouard  3151:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  3152:     
1.126     brouard  3153:     savm=oldm;
                   3154:     oldm=newm;
1.209     brouard  3155: 
                   3156:     for(j=1; j<=nlstate; j++){
                   3157:       max[j]=0.;
                   3158:       min[j]=1.;
                   3159:     }
                   3160:     for(i=1;i<=nlstate;i++){
                   3161:       sumnew=0;
                   3162:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   3163:       for(j=1; j<=nlstate; j++){ 
                   3164:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   3165:        max[j]=FMAX(max[j],prlim[i][j]);
                   3166:        min[j]=FMIN(min[j],prlim[i][j]);
                   3167:       }
                   3168:     }
                   3169: 
1.126     brouard  3170:     maxmax=0.;
1.209     brouard  3171:     for(j=1; j<=nlstate; j++){
                   3172:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   3173:       maxmax=FMAX(maxmax,meandiff[j]);
                   3174:       /* 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  3175:     } /* j loop */
1.203     brouard  3176:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  3177:     /* 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  3178:     if(maxmax < ftolpl){
1.209     brouard  3179:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   3180:       free_vector(min,1,nlstate);
                   3181:       free_vector(max,1,nlstate);
                   3182:       free_vector(meandiff,1,nlstate);
1.126     brouard  3183:       return prlim;
                   3184:     }
1.288     brouard  3185:   } /* agefin loop */
1.208     brouard  3186:     /* After some age loop it doesn't converge */
1.288     brouard  3187:   if(!first){
                   3188:     first=1;
                   3189:     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  3190:     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);
                   3191:   }else if (first >=1 && 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:     first++;
                   3194:   }else if (first ==10){
                   3195:     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);
                   3196:     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");
                   3197:     fprintf(ficlog,"Warning: the stable prevalence no convergence; too many cases, giving up noticing, even in log file\n");
                   3198:     first++;
1.288     brouard  3199:   }
                   3200: 
1.209     brouard  3201:   /* 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); */
                   3202:   free_vector(min,1,nlstate);
                   3203:   free_vector(max,1,nlstate);
                   3204:   free_vector(meandiff,1,nlstate);
1.208     brouard  3205:   
1.169     brouard  3206:   return prlim; /* should not reach here */
1.126     brouard  3207: }
                   3208: 
1.217     brouard  3209: 
                   3210:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   3211: 
1.218     brouard  3212:  /* 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) */
                   3213:  /* 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  3214:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  3215: {
1.264     brouard  3216:   /* 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  3217:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   3218:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   3219:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   3220:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   3221:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   3222:   /* Initial matrix pimij */
                   3223:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   3224:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   3225:   /*  0,                   0                  , 1} */
                   3226:   /*
                   3227:    * and after some iteration: */
                   3228:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   3229:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   3230:   /*  0,                   0                  , 1} */
                   3231:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   3232:   /* {0.51571254859325999, 0.4842874514067399, */
                   3233:   /*  0.51326036147820708, 0.48673963852179264} */
                   3234:   /* If we start from prlim again, prlim tends to a constant matrix */
                   3235: 
1.332     brouard  3236:   int i, ii,j,k, k1;
1.247     brouard  3237:   int first=0;
1.217     brouard  3238:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   3239:   /* double **matprod2(); */ /* test */
                   3240:   double **out, cov[NCOVMAX+1], **bmij();
                   3241:   double **newm;
1.218     brouard  3242:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   3243:   double        **oldm, **savm;  /* for use */
                   3244: 
1.217     brouard  3245:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   3246:   int ncvloop=0;
                   3247:   
                   3248:   min=vector(1,nlstate);
                   3249:   max=vector(1,nlstate);
                   3250:   meandiff=vector(1,nlstate);
                   3251: 
1.266     brouard  3252:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   3253:   oldm=oldms; savm=savms;
                   3254:   
                   3255:   /* Starting with matrix unity */
                   3256:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   3257:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  3258:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3259:     }
                   3260:   
                   3261:   cov[1]=1.;
                   3262:   
                   3263:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3264:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  3265:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  3266:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   3267:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  3268:     ncvloop++;
1.218     brouard  3269:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   3270:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  3271:     /* Covariates have to be included here again */
                   3272:     cov[2]=agefin;
1.319     brouard  3273:     if(nagesqr==1){
1.217     brouard  3274:       cov[3]= agefin*agefin;;
1.319     brouard  3275:     }
1.332     brouard  3276:     for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  3277:       if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  3278:        cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.242     brouard  3279:       }else{
1.332     brouard  3280:        cov[2+nagesqr+k1]=precov[nres][k1];
1.242     brouard  3281:       }
1.332     brouard  3282:     }/* End of loop on model equation */
                   3283: 
                   3284: /* Old code */ 
                   3285: 
                   3286:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   3287:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   3288:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; */
                   3289:     /*   /\* 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)); *\/ */
                   3290:     /* } */
                   3291:     /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   3292:     /* /\*   /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3293:     /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3294:     /* /\*   /\\* 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])]); *\\/ *\/ */
                   3295:     /* /\* } *\/ */
                   3296:     /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3297:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3298:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3299:     /*   /\* 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]); *\/ */
                   3300:     /* } */
                   3301:     /* /\* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; *\/ */
                   3302:     /* /\* for (k=1; k<=cptcovprod;k++) /\\* Useless *\\/ *\/ */
                   3303:     /* /\*   /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\\/ *\/ */
                   3304:     /* /\*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3305:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   3306:     /*   /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age *\\/ ERROR ???*\/ */
                   3307:     /*   if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3308:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3309:     /*   } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3310:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   3311:     /*   } */
                   3312:     /*   /\* 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]); *\/ */
                   3313:     /* } */
                   3314:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   3315:     /*   /\* 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]); *\/ */
                   3316:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3317:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3318:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3319:     /*         }else{ */
                   3320:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3321:     /*         } */
                   3322:     /*   }else{ */
                   3323:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3324:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3325:     /*         }else{ */
                   3326:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3327:     /*         } */
                   3328:     /*   } */
                   3329:     /* } */
1.217     brouard  3330:     
                   3331:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3332:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3333:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   3334:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3335:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  3336:                /* ij should be linked to the correct index of cov */
                   3337:                /* age and covariate values ij are in 'cov', but we need to pass
                   3338:                 * ij for the observed prevalence at age and status and covariate
                   3339:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   3340:                 */
                   3341:     /* 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 *\/ */
                   3342:     /* 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 *\/ */
                   3343:     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  3344:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  3345:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   3346:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   3347:     /*         printf("%d newm= ",i); */
                   3348:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3349:     /*           printf("%f ",newm[i][j]); */
                   3350:     /*         } */
                   3351:     /*         printf("oldm * "); */
                   3352:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3353:     /*           printf("%f ",oldm[i][j]); */
                   3354:     /*         } */
1.268     brouard  3355:     /*         printf(" bmmij "); */
1.266     brouard  3356:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3357:     /*           printf("%f ",pmmij[i][j]); */
                   3358:     /*         } */
                   3359:     /*         printf("\n"); */
                   3360:     /*   } */
                   3361:     /* } */
1.217     brouard  3362:     savm=oldm;
                   3363:     oldm=newm;
1.266     brouard  3364: 
1.217     brouard  3365:     for(j=1; j<=nlstate; j++){
                   3366:       max[j]=0.;
                   3367:       min[j]=1.;
                   3368:     }
                   3369:     for(j=1; j<=nlstate; j++){ 
                   3370:       for(i=1;i<=nlstate;i++){
1.234     brouard  3371:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   3372:        bprlim[i][j]= newm[i][j];
                   3373:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   3374:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  3375:       }
                   3376:     }
1.218     brouard  3377:                
1.217     brouard  3378:     maxmax=0.;
                   3379:     for(i=1; i<=nlstate; i++){
1.318     brouard  3380:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column, could be nan! */
1.217     brouard  3381:       maxmax=FMAX(maxmax,meandiff[i]);
                   3382:       /* 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  3383:     } /* i loop */
1.217     brouard  3384:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  3385:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3386:     if(maxmax < ftolpl){
1.220     brouard  3387:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3388:       free_vector(min,1,nlstate);
                   3389:       free_vector(max,1,nlstate);
                   3390:       free_vector(meandiff,1,nlstate);
                   3391:       return bprlim;
                   3392:     }
1.288     brouard  3393:   } /* agefin loop */
1.217     brouard  3394:     /* After some age loop it doesn't converge */
1.288     brouard  3395:   if(!first){
1.247     brouard  3396:     first=1;
                   3397:     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\
                   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:   }
                   3400:   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  3401: 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);
                   3402:   /* 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); */
                   3403:   free_vector(min,1,nlstate);
                   3404:   free_vector(max,1,nlstate);
                   3405:   free_vector(meandiff,1,nlstate);
                   3406:   
                   3407:   return bprlim; /* should not reach here */
                   3408: }
                   3409: 
1.126     brouard  3410: /*************** transition probabilities ***************/ 
                   3411: 
                   3412: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   3413: {
1.138     brouard  3414:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  3415:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  3416:      model to the ncovmodel covariates (including constant and age).
                   3417:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3418:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3419:      ncth covariate in the global vector x is given by the formula:
                   3420:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3421:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3422:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3423:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  3424:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  3425:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  3426:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  3427:   */
                   3428:   double s1, lnpijopii;
1.126     brouard  3429:   /*double t34;*/
1.164     brouard  3430:   int i,j, nc, ii, jj;
1.126     brouard  3431: 
1.223     brouard  3432:   for(i=1; i<= nlstate; i++){
                   3433:     for(j=1; j<i;j++){
                   3434:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3435:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3436:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3437:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3438:       }
                   3439:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3440:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3441:     }
                   3442:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3443:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3444:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3445:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3446:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3447:       }
                   3448:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3449:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3450:     }
                   3451:   }
1.218     brouard  3452:   
1.223     brouard  3453:   for(i=1; i<= nlstate; i++){
                   3454:     s1=0;
                   3455:     for(j=1; j<i; j++){
1.339     brouard  3456:       /* printf("debug1 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  3457:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3458:     }
                   3459:     for(j=i+1; j<=nlstate+ndeath; j++){
1.339     brouard  3460:       /* printf("debug2 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  3461:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3462:     }
                   3463:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3464:     ps[i][i]=1./(s1+1.);
                   3465:     /* Computing other pijs */
                   3466:     for(j=1; j<i; j++)
1.325     brouard  3467:       ps[i][j]= exp(ps[i][j])*ps[i][i];/* Bug valgrind */
1.223     brouard  3468:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3469:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3470:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3471:   } /* end i */
1.218     brouard  3472:   
1.223     brouard  3473:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3474:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3475:       ps[ii][jj]=0;
                   3476:       ps[ii][ii]=1;
                   3477:     }
                   3478:   }
1.294     brouard  3479: 
                   3480: 
1.223     brouard  3481:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3482:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3483:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3484:   /*   } */
                   3485:   /*   printf("\n "); */
                   3486:   /* } */
                   3487:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3488:   /*
                   3489:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  3490:                goto end;*/
1.266     brouard  3491:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  3492: }
                   3493: 
1.218     brouard  3494: /*************** backward transition probabilities ***************/ 
                   3495: 
                   3496:  /* 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 ) */
                   3497: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   3498:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   3499: {
1.302     brouard  3500:   /* 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  3501:    * 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  3502:    */
1.218     brouard  3503:   int i, ii, j,k;
1.222     brouard  3504:   
                   3505:   double **out, **pmij();
                   3506:   double sumnew=0.;
1.218     brouard  3507:   double agefin;
1.292     brouard  3508:   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  3509:   double **dnewm, **dsavm, **doldm;
                   3510:   double **bbmij;
                   3511:   
1.218     brouard  3512:   doldm=ddoldms; /* global pointers */
1.222     brouard  3513:   dnewm=ddnewms;
                   3514:   dsavm=ddsavms;
1.318     brouard  3515: 
                   3516:   /* Debug */
                   3517:   /* printf("Bmij ij=%d, cov[2}=%f\n", ij, cov[2]); */
1.222     brouard  3518:   agefin=cov[2];
1.268     brouard  3519:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  3520:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  3521:      the observed prevalence (with this covariate ij) at beginning of transition */
                   3522:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  3523: 
                   3524:   /* P_x */
1.325     brouard  3525:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm *//* Bug valgrind */
1.268     brouard  3526:   /* outputs pmmij which is a stochastic matrix in row */
                   3527: 
                   3528:   /* Diag(w_x) */
1.292     brouard  3529:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  3530:   sumnew=0.;
1.269     brouard  3531:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  3532:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  3533:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  3534:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   3535:   }
                   3536:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   3537:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3538:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  3539:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  3540:     }
                   3541:   }else{
                   3542:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3543:       for (j=1;j<=nlstate+ndeath;j++)
                   3544:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   3545:     }
                   3546:     /* if(sumnew <0.9){ */
                   3547:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   3548:     /* } */
                   3549:   }
                   3550:   k3=0.0;  /* We put the last diagonal to 0 */
                   3551:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   3552:       doldm[ii][ii]= k3;
                   3553:   }
                   3554:   /* End doldm, At the end doldm is diag[(w_i)] */
                   3555:   
1.292     brouard  3556:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   3557:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  3558: 
1.292     brouard  3559:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  3560:   /* 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  3561:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  3562:     sumnew=0.;
1.222     brouard  3563:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  3564:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  3565:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  3566:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  3567:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  3568:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  3569:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3570:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  3571:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3572:        /* }else */
1.268     brouard  3573:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   3574:     } /*End ii */
                   3575:   } /* 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 */
                   3576: 
1.292     brouard  3577:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  3578:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  3579:   /* end bmij */
1.266     brouard  3580:   return ps; /*pointer is unchanged */
1.218     brouard  3581: }
1.217     brouard  3582: /*************** transition probabilities ***************/ 
                   3583: 
1.218     brouard  3584: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  3585: {
                   3586:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3587:      computes the probability to be observed in state j being in state i by appying the
                   3588:      model to the ncovmodel covariates (including constant and age).
                   3589:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3590:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3591:      ncth covariate in the global vector x is given by the formula:
                   3592:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3593:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3594:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3595:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3596:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   3597:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3598:   */
                   3599:   double s1, lnpijopii;
                   3600:   /*double t34;*/
                   3601:   int i,j, nc, ii, jj;
                   3602: 
1.234     brouard  3603:   for(i=1; i<= nlstate; i++){
                   3604:     for(j=1; j<i;j++){
                   3605:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3606:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3607:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3608:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3609:       }
                   3610:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3611:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3612:     }
                   3613:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3614:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3615:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3616:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3617:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3618:       }
                   3619:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3620:     }
                   3621:   }
                   3622:   
                   3623:   for(i=1; i<= nlstate; i++){
                   3624:     s1=0;
                   3625:     for(j=1; j<i; j++){
                   3626:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3627:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3628:     }
                   3629:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3630:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3631:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3632:     }
                   3633:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3634:     ps[i][i]=1./(s1+1.);
                   3635:     /* Computing other pijs */
                   3636:     for(j=1; j<i; j++)
                   3637:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3638:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3639:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3640:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3641:   } /* end i */
                   3642:   
                   3643:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3644:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3645:       ps[ii][jj]=0;
                   3646:       ps[ii][ii]=1;
                   3647:     }
                   3648:   }
1.296     brouard  3649:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  3650:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3651:     s1=0.;
                   3652:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   3653:       s1+=ps[ii][jj];
                   3654:     }
                   3655:     for(ii=1; ii<= nlstate; ii++){
                   3656:       ps[ii][jj]=ps[ii][jj]/s1;
                   3657:     }
                   3658:   }
                   3659:   /* Transposition */
                   3660:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3661:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   3662:       s1=ps[ii][jj];
                   3663:       ps[ii][jj]=ps[jj][ii];
                   3664:       ps[jj][ii]=s1;
                   3665:     }
                   3666:   }
                   3667:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3668:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3669:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3670:   /*   } */
                   3671:   /*   printf("\n "); */
                   3672:   /* } */
                   3673:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3674:   /*
                   3675:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3676:     goto end;*/
                   3677:   return ps;
1.217     brouard  3678: }
                   3679: 
                   3680: 
1.126     brouard  3681: /**************** Product of 2 matrices ******************/
                   3682: 
1.145     brouard  3683: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  3684: {
                   3685:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3686:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3687:   /* in, b, out are matrice of pointers which should have been initialized 
                   3688:      before: only the contents of out is modified. The function returns
                   3689:      a pointer to pointers identical to out */
1.145     brouard  3690:   int i, j, k;
1.126     brouard  3691:   for(i=nrl; i<= nrh; i++)
1.145     brouard  3692:     for(k=ncolol; k<=ncoloh; k++){
                   3693:       out[i][k]=0.;
                   3694:       for(j=ncl; j<=nch; j++)
                   3695:        out[i][k] +=in[i][j]*b[j][k];
                   3696:     }
1.126     brouard  3697:   return out;
                   3698: }
                   3699: 
                   3700: 
                   3701: /************* Higher Matrix Product ***************/
                   3702: 
1.235     brouard  3703: 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  3704: {
1.336     brouard  3705:   /* Already optimized with precov.
                   3706:      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  3707:      'nhstepm*hstepm*stepm' months (i.e. until
                   3708:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3709:      nhstepm*hstepm matrices. 
                   3710:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3711:      (typically every 2 years instead of every month which is too big 
                   3712:      for the memory).
                   3713:      Model is determined by parameters x and covariates have to be 
                   3714:      included manually here. 
                   3715: 
                   3716:      */
                   3717: 
1.330     brouard  3718:   int i, j, d, h, k, k1;
1.131     brouard  3719:   double **out, cov[NCOVMAX+1];
1.126     brouard  3720:   double **newm;
1.187     brouard  3721:   double agexact;
1.214     brouard  3722:   double agebegin, ageend;
1.126     brouard  3723: 
                   3724:   /* Hstepm could be zero and should return the unit matrix */
                   3725:   for (i=1;i<=nlstate+ndeath;i++)
                   3726:     for (j=1;j<=nlstate+ndeath;j++){
                   3727:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3728:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3729:     }
                   3730:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3731:   for(h=1; h <=nhstepm; h++){
                   3732:     for(d=1; d <=hstepm; d++){
                   3733:       newm=savm;
                   3734:       /* Covariates have to be included here again */
                   3735:       cov[1]=1.;
1.214     brouard  3736:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3737:       cov[2]=agexact;
1.319     brouard  3738:       if(nagesqr==1){
1.227     brouard  3739:        cov[3]= agexact*agexact;
1.319     brouard  3740:       }
1.330     brouard  3741:       /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   3742:       /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   3743:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  3744:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  3745:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   3746:        }else{
                   3747:          cov[2+nagesqr+k1]=precov[nres][k1];
                   3748:        }
                   3749:       }/* End of loop on model equation */
                   3750:        /* Old code */ 
                   3751: /*     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /\* Single dummy  *\/ */
                   3752: /* /\*    V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) *\/ */
                   3753: /* /\*       for (k=1; k<=nsd;k++) { /\\* For single dummy covariates only *\\/ *\/ */
                   3754: /* /\* /\\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\\/ *\/ */
                   3755: /*     /\* codtabm(ij,k)  (1 & (ij-1) >> (k-1))+1 *\/ */
                   3756: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3757: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3758: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
                   3759: /* /\*    nsd         1   2                              3 *\/ /\* Counting single dummies covar fixed or tv *\/ */
                   3760: /* /\*TvarsD[nsd]     4   3                              1 *\/ /\* ID of single dummy cova fixed or timevary*\/ */
                   3761: /* /\*TvarsDind[k]    2   3                              9 *\/ /\* position K of single dummy cova *\/ */
                   3762: /*       /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];or [codtabm(ij,TnsdVar[TvarsD[k]] *\/ */
                   3763: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]]; */
                   3764: /*       /\* 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]])); *\/ */
                   3765: /*       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); */
                   3766: /*       printf("hpxij new Dummy precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3767: /*     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /\* Single quantitative variables  *\/ */
                   3768: /*       /\* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline *\/ */
                   3769: /*       cov[2+nagesqr+k1]=Tqresult[nres][resultmodel[nres][k1]];  */
                   3770: /*       /\* for (k=1; k<=nsq;k++) { /\\* For single varying covariates only *\\/ *\/ */
                   3771: /*       /\*   /\\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\\/ *\/ */
                   3772: /*       /\*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   3773: /*       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]]); */
                   3774: /*       printf("hpxij new Quanti precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3775: /*     }else if( Dummy[k1]==2 ){ /\* For dummy with age product *\/ */
                   3776: /*       /\* Tvar[k1] Variable in the age product age*V1 is 1 *\/ */
                   3777: /*       /\* [Tinvresult[nres][V1] is its value in the resultline nres *\/ */
                   3778: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvar[k1]]*cov[2]; */
                   3779: /*       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]); */
                   3780: /*       printf("hpxij new Dummy with age product precov[nres=%d][k1=%d]=%.4f * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3781: 
                   3782: /*       /\* cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];    *\/ */
                   3783: /*       /\* for (k=1; k<=cptcovage;k++){ /\\* For product with age V1+V1*age +V4 +age*V3 *\\/ *\/ */
                   3784: /*       /\* 1+2 Tage[1]=2 TVar[2]=1 Dummy[2]=2, Tage[2]=4 TVar[4]=3 Dummy[4]=3 quant*\/ */
                   3785: /*       /\* *\/ */
1.330     brouard  3786: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3787: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3788: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
1.332     brouard  3789: /* /\*cptcovage=2                   1               2      *\/ */
                   3790: /* /\*Tage[k]=                      5               8      *\/  */
                   3791: /*     }else if( Dummy[k1]==3 ){ /\* For quant with age product *\/ */
                   3792: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];        */
                   3793: /*       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]]); */
                   3794: /*       printf("hpxij new Quanti with age product precov[nres=%d][k1=%d] * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3795: /*       /\* if(Dummy[Tage[k]]== 2){ /\\* dummy with age *\\/ *\/ */
                   3796: /*       /\* /\\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\\* dummy with age *\\\/ *\\/ *\/ */
                   3797: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\\/ *\/ */
                   3798: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\\/ *\/ */
                   3799: /*       /\*   cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\/ */
                   3800: /*       /\*   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); *\/ */
                   3801: /*       /\* } else if(Dummy[Tage[k]]== 3){ /\\* quantitative with age *\\/ *\/ */
                   3802: /*       /\*   cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; *\/ */
                   3803: /*       /\* } *\/ */
                   3804: /*       /\* 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]); *\/ */
                   3805: /*     }else if(Typevar[k1]==2 ){ /\* For product (not with age) *\/ */
                   3806: /* /\*       for (k=1; k<=cptcovprod;k++){ /\\*  For product without age *\\/ *\/ */
                   3807: /* /\* /\\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\\/ *\/ */
                   3808: /* /\* /\\*    k        1  2   3   4     5    6    7     8    9 *\\/ *\/ */
                   3809: /* /\* /\\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\\/ *\/ */
                   3810: /* /\* /\\*cptcovprod=1            1               2            *\\/ *\/ */
                   3811: /* /\* /\\*Tprod[]=                4               7            *\\/ *\/ */
                   3812: /* /\* /\\*Tvard[][1]             4               1             *\\/ *\/ */
                   3813: /* /\* /\\*Tvard[][2]               3               2           *\\/ *\/ */
1.330     brouard  3814:          
1.332     brouard  3815: /*       /\* 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])]); *\/ */
                   3816: /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3817: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];     */
                   3818: /*       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]]); */
                   3819: /*       printf("hpxij new Product no age product precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3820: 
                   3821: /*       /\* if(Dummy[Tvardk[k1][1]]==0){ *\/ */
                   3822: /*       /\*   if(Dummy[Tvardk[k1][2]]==0){ /\\* Product of dummies *\\/ *\/ */
                   3823: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3824: /*           /\* cov[2+nagesqr+k1]=Tinvresult[nres][Tvardk[k1][1]] * Tinvresult[nres][Tvardk[k1][2]];   *\/ */
                   3825: /*           /\* 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]])]; *\/ */
                   3826: /*         /\* }else{ /\\* Product of dummy by quantitative *\\/ *\/ */
                   3827: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,TnsdVar[Tvard[k][1]])] * Tqresult[nres][k]; *\/ */
                   3828: /*           /\* cov[2+nagesqr+k1]=Tresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]; *\/ */
                   3829: /*       /\*   } *\/ */
                   3830: /*       /\* }else{ /\\* Product of quantitative by...*\\/ *\/ */
                   3831: /*       /\*   if(Dummy[Tvard[k][2]]==0){  /\\* quant by dummy *\\/ *\/ */
                   3832: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][Tvard[k][1]]; *\\/ *\/ */
                   3833: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3834: /*       /\*   }else{ /\\* Product of two quant *\\/ *\/ */
                   3835: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\\/ *\/ */
                   3836: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3837: /*       /\*   } *\/ */
                   3838: /*       /\* }/\\*end of products quantitative *\\/ *\/ */
                   3839: /*     }/\*end of products *\/ */
                   3840:       /* } /\* End of loop on model equation *\/ */
1.235     brouard  3841:       /* for (k=1; k<=cptcovn;k++)  */
                   3842:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3843:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3844:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3845:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3846:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3847:       
                   3848:       
1.126     brouard  3849:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3850:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.319     brouard  3851:       /* right multiplication of oldm by the current matrix */
1.126     brouard  3852:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3853:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3854:       /* if((int)age == 70){ */
                   3855:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3856:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3857:       /*         printf("%d pmmij ",i); */
                   3858:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3859:       /*           printf("%f ",pmmij[i][j]); */
                   3860:       /*         } */
                   3861:       /*         printf(" oldm "); */
                   3862:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3863:       /*           printf("%f ",oldm[i][j]); */
                   3864:       /*         } */
                   3865:       /*         printf("\n"); */
                   3866:       /*       } */
                   3867:       /* } */
1.126     brouard  3868:       savm=oldm;
                   3869:       oldm=newm;
                   3870:     }
                   3871:     for(i=1; i<=nlstate+ndeath; i++)
                   3872:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  3873:        po[i][j][h]=newm[i][j];
                   3874:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3875:       }
1.128     brouard  3876:     /*printf("h=%d ",h);*/
1.126     brouard  3877:   } /* end h */
1.267     brouard  3878:   /*     printf("\n H=%d \n",h); */
1.126     brouard  3879:   return po;
                   3880: }
                   3881: 
1.217     brouard  3882: /************* Higher Back Matrix Product ***************/
1.218     brouard  3883: /* 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  3884: 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  3885: {
1.332     brouard  3886:   /* For dummy covariates given in each resultline (for historical, computes the corresponding combination ij),
                   3887:      computes the transition matrix starting at age 'age' over
1.217     brouard  3888:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3889:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3890:      nhstepm*hstepm matrices.
                   3891:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3892:      (typically every 2 years instead of every month which is too big
1.217     brouard  3893:      for the memory).
1.218     brouard  3894:      Model is determined by parameters x and covariates have to be
1.266     brouard  3895:      included manually here. Then we use a call to bmij(x and cov)
                   3896:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  3897:   */
1.217     brouard  3898: 
1.332     brouard  3899:   int i, j, d, h, k, k1;
1.266     brouard  3900:   double **out, cov[NCOVMAX+1], **bmij();
                   3901:   double **newm, ***newmm;
1.217     brouard  3902:   double agexact;
                   3903:   double agebegin, ageend;
1.222     brouard  3904:   double **oldm, **savm;
1.217     brouard  3905: 
1.266     brouard  3906:   newmm=po; /* To be saved */
                   3907:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  3908:   /* Hstepm could be zero and should return the unit matrix */
                   3909:   for (i=1;i<=nlstate+ndeath;i++)
                   3910:     for (j=1;j<=nlstate+ndeath;j++){
                   3911:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3912:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3913:     }
                   3914:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3915:   for(h=1; h <=nhstepm; h++){
                   3916:     for(d=1; d <=hstepm; d++){
                   3917:       newm=savm;
                   3918:       /* Covariates have to be included here again */
                   3919:       cov[1]=1.;
1.271     brouard  3920:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  3921:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
1.318     brouard  3922:         /* Debug */
                   3923:       /* printf("hBxij age=%lf, agexact=%lf\n", age, agexact); */
1.217     brouard  3924:       cov[2]=agexact;
1.332     brouard  3925:       if(nagesqr==1){
1.222     brouard  3926:        cov[3]= agexact*agexact;
1.332     brouard  3927:       }
                   3928:       /** New code */
                   3929:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  3930:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  3931:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.325     brouard  3932:        }else{
1.332     brouard  3933:          cov[2+nagesqr+k1]=precov[nres][k1];
1.325     brouard  3934:        }
1.332     brouard  3935:       }/* End of loop on model equation */
                   3936:       /** End of new code */
                   3937:   /** This was old code */
                   3938:       /* for (k=1; k<=nsd;k++){ /\* For single dummy covariates only *\//\* cptcovn error *\/ */
                   3939:       /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3940:       /* /\* /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3941:       /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])];/\* Bug valgrind *\/ */
                   3942:       /*   /\* 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)); *\/ */
                   3943:       /* } */
                   3944:       /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3945:       /*       /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3946:       /*       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3947:       /*       /\* 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]); *\/ */
                   3948:       /* } */
                   3949:       /* for (k=1; k<=cptcovage;k++){ /\* Should start at cptcovn+1 *\//\* For product with age *\/ */
                   3950:       /*       /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age error!!!*\\/ *\/ */
                   3951:       /*       if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3952:       /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3953:       /*       } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3954:       /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];  */
                   3955:       /*       } */
                   3956:       /*       /\* 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]); *\/ */
                   3957:       /* } */
                   3958:       /* for (k=1; k<=cptcovprod;k++){ /\* Useless because included in cptcovn *\/ */
                   3959:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3960:       /*       if(Dummy[Tvard[k][1]]==0){ */
                   3961:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3962:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][1])]; */
                   3963:       /*         }else{ */
                   3964:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3965:       /*         } */
                   3966:       /*       }else{ */
                   3967:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3968:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3969:       /*         }else{ */
                   3970:       /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3971:       /*         } */
                   3972:       /*       } */
                   3973:       /* }                      */
                   3974:       /* /\*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*\/ */
                   3975:       /* /\*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*\/ */
                   3976: /** End of old code */
                   3977:       
1.218     brouard  3978:       /* Careful transposed matrix */
1.266     brouard  3979:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  3980:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3981:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3982:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.325     brouard  3983:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);/* Bug valgrind */
1.217     brouard  3984:       /* if((int)age == 70){ */
                   3985:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3986:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3987:       /*         printf("%d pmmij ",i); */
                   3988:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3989:       /*           printf("%f ",pmmij[i][j]); */
                   3990:       /*         } */
                   3991:       /*         printf(" oldm "); */
                   3992:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3993:       /*           printf("%f ",oldm[i][j]); */
                   3994:       /*         } */
                   3995:       /*         printf("\n"); */
                   3996:       /*       } */
                   3997:       /* } */
                   3998:       savm=oldm;
                   3999:       oldm=newm;
                   4000:     }
                   4001:     for(i=1; i<=nlstate+ndeath; i++)
                   4002:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  4003:        po[i][j][h]=newm[i][j];
1.268     brouard  4004:        /* if(h==nhstepm) */
                   4005:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  4006:       }
1.268     brouard  4007:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  4008:   } /* end h */
1.268     brouard  4009:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  4010:   return po;
                   4011: }
                   4012: 
                   4013: 
1.162     brouard  4014: #ifdef NLOPT
                   4015:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   4016:   double fret;
                   4017:   double *xt;
                   4018:   int j;
                   4019:   myfunc_data *d2 = (myfunc_data *) pd;
                   4020: /* xt = (p1-1); */
                   4021:   xt=vector(1,n); 
                   4022:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   4023: 
                   4024:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   4025:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   4026:   printf("Function = %.12lf ",fret);
                   4027:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   4028:   printf("\n");
                   4029:  free_vector(xt,1,n);
                   4030:   return fret;
                   4031: }
                   4032: #endif
1.126     brouard  4033: 
                   4034: /*************** log-likelihood *************/
                   4035: double func( double *x)
                   4036: {
1.336     brouard  4037:   int i, ii, j, k, mi, d, kk, kf=0;
1.226     brouard  4038:   int ioffset=0;
1.339     brouard  4039:   int ipos=0,iposold=0,ncovv=0;
                   4040: 
1.340     brouard  4041:   double cotvarv, cotvarvold;
1.226     brouard  4042:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   4043:   double **out;
                   4044:   double lli; /* Individual log likelihood */
                   4045:   int s1, s2;
1.228     brouard  4046:   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  4047: 
1.226     brouard  4048:   double bbh, survp;
                   4049:   double agexact;
1.336     brouard  4050:   double agebegin, ageend;
1.226     brouard  4051:   /*extern weight */
                   4052:   /* We are differentiating ll according to initial status */
                   4053:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   4054:   /*for(i=1;i<imx;i++) 
                   4055:     printf(" %d\n",s[4][i]);
                   4056:   */
1.162     brouard  4057: 
1.226     brouard  4058:   ++countcallfunc;
1.162     brouard  4059: 
1.226     brouard  4060:   cov[1]=1.;
1.126     brouard  4061: 
1.226     brouard  4062:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  4063:   ioffset=0;
1.226     brouard  4064:   if(mle==1){
                   4065:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4066:       /* Computes the values of the ncovmodel covariates of the model
                   4067:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   4068:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   4069:         to be observed in j being in i according to the model.
                   4070:       */
1.243     brouard  4071:       ioffset=2+nagesqr ;
1.233     brouard  4072:    /* Fixed */
1.345     brouard  4073:       for (kf=1; kf<=ncovf;kf++){ /* For each fixed covariate dummy or quant or prod */
1.319     brouard  4074:        /* # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi */
                   4075:         /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   4076:        /*  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  4077:         /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.336     brouard  4078:        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  4079:        /* V1*V2 (7)  TvarFind[2]=7, TvarFind[3]=9 */
1.234     brouard  4080:       }
1.226     brouard  4081:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.319     brouard  4082:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
1.226     brouard  4083:         has been calculated etc */
                   4084:       /* For an individual i, wav[i] gives the number of effective waves */
                   4085:       /* We compute the contribution to Likelihood of each effective transition
                   4086:         mw[mi][i] is real wave of the mi th effectve wave */
                   4087:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   4088:         s2=s[mw[mi+1][i]][i];
1.341     brouard  4089:         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  4090:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   4091:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   4092:       */
1.336     brouard  4093:       for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
                   4094:       /* Wave varying (but not age varying) */
1.339     brouard  4095:        /* 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*\/ */
                   4096:        /*   /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; but where is the crossproduct? *\/ */
                   4097:        /*   cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   4098:        /* } */
1.340     brouard  4099:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age )*/
                   4100:          itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   4101:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
1.345     brouard  4102:          if(FixedV[itv]!=0){ /* Not a fixed covariate */
1.341     brouard  4103:            cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* cotvar[wav][ncovcol+nqv+iv][i] */
1.340     brouard  4104:          }else{ /* fixed covariate */
1.345     brouard  4105:            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  4106:          }
1.339     brouard  4107:          if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  4108:            cotvarvold=cotvarv;
                   4109:          }else{ /* A second product */
                   4110:            cotvarv=cotvarv*cotvarvold;
1.339     brouard  4111:          }
                   4112:          iposold=ipos;
1.340     brouard  4113:          cov[ioffset+ipos]=cotvarv;
1.234     brouard  4114:        }
1.339     brouard  4115:        /* for products of time varying to be done */
1.234     brouard  4116:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4117:          for (j=1;j<=nlstate+ndeath;j++){
                   4118:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4119:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4120:          }
1.336     brouard  4121: 
                   4122:        agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4123:        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  4124:        for(d=0; d<dh[mi][i]; d++){
                   4125:          newm=savm;
                   4126:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4127:          cov[2]=agexact;
                   4128:          if(nagesqr==1)
                   4129:            cov[3]= agexact*agexact;  /* Should be changed here */
1.349     brouard  4130:          /* for (kk=1; kk<=cptcovage;kk++) { */
                   4131:          /*   if(!FixedV[Tvar[Tage[kk]]]) */
                   4132:          /*     cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /\* Tage[kk] gives the data-covariate associated with age *\/ */
                   4133:          /*   else */
                   4134:          /*     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) *\/  */
                   4135:          /* } */
                   4136:          for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   4137:            itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   4138:            ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4139:            if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   4140:              cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   4141:            }else{ /* fixed covariate */
                   4142:              cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   4143:            }
                   4144:            if(ipos!=iposold){ /* Not a product or first of a product */
                   4145:              cotvarvold=cotvarv;
                   4146:            }else{ /* A second product */
                   4147:              cotvarv=cotvarv*cotvarvold;
                   4148:            }
                   4149:            iposold=ipos;
                   4150:            cov[ioffset+ipos]=cotvarv*agexact;
                   4151:            /* For products */
1.234     brouard  4152:          }
1.349     brouard  4153:          
1.234     brouard  4154:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4155:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4156:          savm=oldm;
                   4157:          oldm=newm;
                   4158:        } /* end mult */
                   4159:        
                   4160:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   4161:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   4162:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   4163:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   4164:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   4165:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   4166:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   4167:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  4168:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   4169:                                 * -stepm/2 to stepm/2 .
                   4170:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   4171:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   4172:                                 */
1.234     brouard  4173:        s1=s[mw[mi][i]][i];
                   4174:        s2=s[mw[mi+1][i]][i];
                   4175:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4176:        /* bias bh is positive if real duration
                   4177:         * is higher than the multiple of stepm and negative otherwise.
                   4178:         */
                   4179:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   4180:        if( s2 > nlstate){ 
                   4181:          /* i.e. if s2 is a death state and if the date of death is known 
                   4182:             then the contribution to the likelihood is the probability to 
                   4183:             die between last step unit time and current  step unit time, 
                   4184:             which is also equal to probability to die before dh 
                   4185:             minus probability to die before dh-stepm . 
                   4186:             In version up to 0.92 likelihood was computed
                   4187:             as if date of death was unknown. Death was treated as any other
                   4188:             health state: the date of the interview describes the actual state
                   4189:             and not the date of a change in health state. The former idea was
                   4190:             to consider that at each interview the state was recorded
                   4191:             (healthy, disable or death) and IMaCh was corrected; but when we
                   4192:             introduced the exact date of death then we should have modified
                   4193:             the contribution of an exact death to the likelihood. This new
                   4194:             contribution is smaller and very dependent of the step unit
                   4195:             stepm. It is no more the probability to die between last interview
                   4196:             and month of death but the probability to survive from last
                   4197:             interview up to one month before death multiplied by the
                   4198:             probability to die within a month. Thanks to Chris
                   4199:             Jackson for correcting this bug.  Former versions increased
                   4200:             mortality artificially. The bad side is that we add another loop
                   4201:             which slows down the processing. The difference can be up to 10%
                   4202:             lower mortality.
                   4203:          */
                   4204:          /* If, at the beginning of the maximization mostly, the
                   4205:             cumulative probability or probability to be dead is
                   4206:             constant (ie = 1) over time d, the difference is equal to
                   4207:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   4208:             s1 at precedent wave, to be dead a month before current
                   4209:             wave is equal to probability, being at state s1 at
                   4210:             precedent wave, to be dead at mont of the current
                   4211:             wave. Then the observed probability (that this person died)
                   4212:             is null according to current estimated parameter. In fact,
                   4213:             it should be very low but not zero otherwise the log go to
                   4214:             infinity.
                   4215:          */
1.183     brouard  4216: /* #ifdef INFINITYORIGINAL */
                   4217: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4218: /* #else */
                   4219: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   4220: /*         lli=log(mytinydouble); */
                   4221: /*       else */
                   4222: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4223: /* #endif */
1.226     brouard  4224:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4225:          
1.226     brouard  4226:        } else if  ( s2==-1 ) { /* alive */
                   4227:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4228:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4229:          /*survp += out[s1][j]; */
                   4230:          lli= log(survp);
                   4231:        }
1.336     brouard  4232:        /* else if  (s2==-4) {  */
                   4233:        /*   for (j=3,survp=0. ; j<=nlstate; j++)   */
                   4234:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4235:        /*   lli= log(survp);  */
                   4236:        /* }  */
                   4237:        /* else if  (s2==-5) {  */
                   4238:        /*   for (j=1,survp=0. ; j<=2; j++)   */
                   4239:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4240:        /*   lli= log(survp);  */
                   4241:        /* }  */
1.226     brouard  4242:        else{
                   4243:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4244:          /*  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 */
                   4245:        } 
                   4246:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   4247:        /*if(lli ==000.0)*/
1.340     brouard  4248:        /* 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  4249:        ipmx +=1;
                   4250:        sw += weight[i];
                   4251:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4252:        /* if (lli < log(mytinydouble)){ */
                   4253:        /*   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); */
                   4254:        /*   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]); */
                   4255:        /* } */
                   4256:       } /* end of wave */
                   4257:     } /* end of individual */
                   4258:   }  else if(mle==2){
                   4259:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.319     brouard  4260:       ioffset=2+nagesqr ;
                   4261:       for (k=1; k<=ncovf;k++)
                   4262:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];
1.226     brouard  4263:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  4264:        for(k=1; k <= ncovv ; k++){
1.341     brouard  4265:          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  4266:        }
1.226     brouard  4267:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4268:          for (j=1;j<=nlstate+ndeath;j++){
                   4269:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4270:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4271:          }
                   4272:        for(d=0; d<=dh[mi][i]; d++){
                   4273:          newm=savm;
                   4274:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4275:          cov[2]=agexact;
                   4276:          if(nagesqr==1)
                   4277:            cov[3]= agexact*agexact;
                   4278:          for (kk=1; kk<=cptcovage;kk++) {
                   4279:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4280:          }
                   4281:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4282:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4283:          savm=oldm;
                   4284:          oldm=newm;
                   4285:        } /* end mult */
                   4286:       
                   4287:        s1=s[mw[mi][i]][i];
                   4288:        s2=s[mw[mi+1][i]][i];
                   4289:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4290:        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 */
                   4291:        ipmx +=1;
                   4292:        sw += weight[i];
                   4293:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4294:       } /* end of wave */
                   4295:     } /* end of individual */
                   4296:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   4297:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4298:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4299:       for(mi=1; mi<= wav[i]-1; mi++){
                   4300:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4301:          for (j=1;j<=nlstate+ndeath;j++){
                   4302:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4303:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4304:          }
                   4305:        for(d=0; d<dh[mi][i]; d++){
                   4306:          newm=savm;
                   4307:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4308:          cov[2]=agexact;
                   4309:          if(nagesqr==1)
                   4310:            cov[3]= agexact*agexact;
                   4311:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  4312:            if(!FixedV[Tvar[Tage[kk]]])
                   4313:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4314:            else
1.341     brouard  4315:              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  4316:          }
                   4317:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4318:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4319:          savm=oldm;
                   4320:          oldm=newm;
                   4321:        } /* end mult */
                   4322:       
                   4323:        s1=s[mw[mi][i]][i];
                   4324:        s2=s[mw[mi+1][i]][i];
                   4325:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4326:        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 */
                   4327:        ipmx +=1;
                   4328:        sw += weight[i];
                   4329:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4330:       } /* end of wave */
                   4331:     } /* end of individual */
                   4332:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   4333:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4334:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4335:       for(mi=1; mi<= wav[i]-1; mi++){
                   4336:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4337:          for (j=1;j<=nlstate+ndeath;j++){
                   4338:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4339:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4340:          }
                   4341:        for(d=0; d<dh[mi][i]; d++){
                   4342:          newm=savm;
                   4343:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4344:          cov[2]=agexact;
                   4345:          if(nagesqr==1)
                   4346:            cov[3]= agexact*agexact;
                   4347:          for (kk=1; kk<=cptcovage;kk++) {
                   4348:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4349:          }
1.126     brouard  4350:        
1.226     brouard  4351:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4352:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4353:          savm=oldm;
                   4354:          oldm=newm;
                   4355:        } /* end mult */
                   4356:       
                   4357:        s1=s[mw[mi][i]][i];
                   4358:        s2=s[mw[mi+1][i]][i];
                   4359:        if( s2 > nlstate){ 
                   4360:          lli=log(out[s1][s2] - savm[s1][s2]);
                   4361:        } else if  ( s2==-1 ) { /* alive */
                   4362:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4363:            survp += out[s1][j];
                   4364:          lli= log(survp);
                   4365:        }else{
                   4366:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4367:        }
                   4368:        ipmx +=1;
                   4369:        sw += weight[i];
                   4370:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.343     brouard  4371:        /* 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  4372:       } /* end of wave */
                   4373:     } /* end of individual */
                   4374:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   4375:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4376:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4377:       for(mi=1; mi<= wav[i]-1; mi++){
                   4378:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4379:          for (j=1;j<=nlstate+ndeath;j++){
                   4380:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4381:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4382:          }
                   4383:        for(d=0; d<dh[mi][i]; d++){
                   4384:          newm=savm;
                   4385:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4386:          cov[2]=agexact;
                   4387:          if(nagesqr==1)
                   4388:            cov[3]= agexact*agexact;
                   4389:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  4390:            if(!FixedV[Tvar[Tage[kk]]])
                   4391:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4392:            else
1.341     brouard  4393:              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  4394:          }
1.126     brouard  4395:        
1.226     brouard  4396:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4397:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4398:          savm=oldm;
                   4399:          oldm=newm;
                   4400:        } /* end mult */
                   4401:       
                   4402:        s1=s[mw[mi][i]][i];
                   4403:        s2=s[mw[mi+1][i]][i];
                   4404:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4405:        ipmx +=1;
                   4406:        sw += weight[i];
                   4407:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4408:        /*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]);*/
                   4409:       } /* end of wave */
                   4410:     } /* end of individual */
                   4411:   } /* End of if */
                   4412:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   4413:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   4414:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4415:   return -l;
1.126     brouard  4416: }
                   4417: 
                   4418: /*************** log-likelihood *************/
                   4419: double funcone( double *x)
                   4420: {
1.228     brouard  4421:   /* Same as func but slower because of a lot of printf and if */
1.349     brouard  4422:   int i, ii, j, k, mi, d, kk, kv=0, kf=0;
1.228     brouard  4423:   int ioffset=0;
1.339     brouard  4424:   int ipos=0,iposold=0,ncovv=0;
                   4425: 
1.340     brouard  4426:   double cotvarv, cotvarvold;
1.131     brouard  4427:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  4428:   double **out;
                   4429:   double lli; /* Individual log likelihood */
                   4430:   double llt;
                   4431:   int s1, s2;
1.228     brouard  4432:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   4433: 
1.126     brouard  4434:   double bbh, survp;
1.187     brouard  4435:   double agexact;
1.214     brouard  4436:   double agebegin, ageend;
1.126     brouard  4437:   /*extern weight */
                   4438:   /* We are differentiating ll according to initial status */
                   4439:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   4440:   /*for(i=1;i<imx;i++) 
                   4441:     printf(" %d\n",s[4][i]);
                   4442:   */
                   4443:   cov[1]=1.;
                   4444: 
                   4445:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  4446:   ioffset=0;
                   4447:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.336     brouard  4448:     /* Computes the values of the ncovmodel covariates of the model
                   4449:        depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   4450:        Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   4451:        to be observed in j being in i according to the model.
                   4452:     */
1.243     brouard  4453:     /* ioffset=2+nagesqr+cptcovage; */
                   4454:     ioffset=2+nagesqr;
1.232     brouard  4455:     /* Fixed */
1.224     brouard  4456:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  4457:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
1.349     brouard  4458:     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  4459:       /* printf("Debug3 TvarFind[%d]=%d",kf, TvarFind[kf]); */
                   4460:       /* printf(" Tvar[TvarFind[kf]]=%d", Tvar[TvarFind[kf]]); */
                   4461:       /* printf(" i=%d covar[Tvar[TvarFind[kf]]][i]=%f\n",i,covar[Tvar[TvarFind[kf]]][i]); */
1.335     brouard  4462:       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  4463: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   4464: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   4465: /*    cov[2+6]=covar[2][i]; V2  */
                   4466: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   4467: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   4468: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   4469: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   4470: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   4471: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  4472:     }
1.336     brouard  4473:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   4474:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
                   4475:         has been calculated etc */
                   4476:       /* For an individual i, wav[i] gives the number of effective waves */
                   4477:       /* We compute the contribution to Likelihood of each effective transition
                   4478:         mw[mi][i] is real wave of the mi th effectve wave */
                   4479:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   4480:         s2=s[mw[mi+1][i]][i];
1.341     brouard  4481:         And the iv th varying covariate in the DATA is the cotvar[mw[mi+1][i]][ncovcol+nqv+iv][i]
1.336     brouard  4482:       */
                   4483:     /* This part may be useless now because everythin should be in covar */
1.232     brouard  4484:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   4485:     /*   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?)*\/ */
                   4486:     /* } */
1.231     brouard  4487:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   4488:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   4489:     /* } */
1.225     brouard  4490:     
1.233     brouard  4491: 
                   4492:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.339     brouard  4493:       /* 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 */
                   4494:       /* for(k=1; k <= ncovv ; k++){ /\* Varying  covariates (single and product but no age )*\/ */
                   4495:       /*       /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; *\/ */
                   4496:       /*       cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   4497:       /* } */
                   4498:       
                   4499:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   4500:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   4501:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   4502:       /*  TvarVV[1]=V3 (first time varying in the model equation, TvarVV[2]=V1 (in V1*V3) TvarVV[3]=3(V3)  */
                   4503:       /* We need the position of the time varying or product in the model */
                   4504:       /* 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 */            
                   4505:       /* TvarVV gives the variable name */
1.340     brouard  4506:       /* Other example V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   4507:       *      k=         1   2     3     4         5        6        7       8        9
                   4508:       *  varying            1     2                                 3       4        5
                   4509:       *  ncovv              1     2                                3 4     5 6      7 8
1.343     brouard  4510:       * TvarVV[ncovv]      V3     5                                1 3     3 5      1 5
1.340     brouard  4511:       * TvarVVind           2     3                                7 7     8 8      9 9
                   4512:       * TvarFind[k]     1   0     0     0         0        0        0       0        0
                   4513:       */
1.345     brouard  4514:       /* Other model ncovcol=5 nqv=0 ntv=3 nqtv=0 nlstate=3
1.349     brouard  4515:        * 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  4516:        * FixedV[ncovcol+qv+ntv+nqtv]       V5
1.349     brouard  4517:        * 3           V1  V2     V3    V4   V5 V6     V7  V8 V3*V2 V7*V2  V6*V3 V7*V3 V6*V4 V7*V4
                   4518:        *             0   0      0      0    0  1      1   1  0, 0, 1,1,   1, 0, 1, 0, 1, 0, 1, 0}
                   4519:        * 3           0   0      0      0    0  1      1   1  0,     1      1    1      1    1}
                   4520:        * model=          V2  +  V3  +  V4  +  V6  +  V7  +  V6*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   4521:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   4522:         *                +age*V6*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   4523:        * model2=          V2  +  V3  +  V4  +  V6  +  V7  +  V3*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   4524:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   4525:         *                +age*V3*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   4526:        * model3=          V2  +  V3  +  V4  +  V6  +  V7  + age*V3*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   4527:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   4528:         *                +V3*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   4529:        * kmodel           1     2      3      4      5        6         7         8         9        10        11    
                   4530:        *                  12       13      14      15       16
                   4531:        *                    17        18         19        20         21
                   4532:        * Tvar[kmodel]     2     3      4      6      7        9        10        11        12        13        14
                   4533:        *                   2       3        4       6        7
                   4534:        *                     9         11          12        13         14            
                   4535:        * cptcovage=5+5 total of covariates with age 
                   4536:        * Tage[cptcovage] age*V2=12      13      14      15       16
                   4537:        *1                   17            18         19        20         21 gives the position in model of covariates associated with age
                   4538:        *3 Tage[cptcovage] age*V3*V2=6  
                   4539:        *3                age*V2=12         13      14      15       16
                   4540:        *3                age*V6*V3=18      19    20   21
                   4541:        * Tvar[Tage[cptcovage]]    Tvar[12]=2      3      4       6         Tvar[16]=7(age*V7)
                   4542:        *     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
                   4543:        * 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
                   4544:        * 3 Tvar[Tage[cptcovage]]    Tvar[6]=9      Tvar[12]=2      3     4       6         Tvar[16]=7(age*V7)
                   4545:        * 3     Tvar[18]age*V6*V3=11  age*V7*V3=12         age*V6*V4=13        Tvar[21]age*V7*V4=14
                   4546:        * 3 Tage[cptcovage] age*V3*V2=6   age*V2=12 age*V3 13    14      15       16
                   4547:        *                    age*V6*V3=18         19        20         21 gives the position in model of covariates associated with age
                   4548:        * 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
                   4549:        * Tvar=                {2, 3, 4, 6, 7,
                   4550:        *                       9, 10, 11, 12, 13, 14,
                   4551:        *              Tvar[12]=2, 3, 4, 6, 7,
                   4552:        *              Tvar[17]=9, 11, 12, 13, 14}
                   4553:        * Typevar[1]@21 = {0, 0, 0, 0, 0,
                   4554:        *                  2, 2, 2, 2, 2, 2,
                   4555:        * 3                3, 2, 2, 2, 2, 2,
                   4556:        *                  1, 1, 1, 1, 1, 
                   4557:        *                  3, 3, 3, 3, 3}
                   4558:        * 3                 2, 3, 3, 3, 3}
                   4559:        * 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
                   4560:        * p Tprod[1]@21 {6, 7, 8, 9, 10, 11, 0 <repeats 15 times>}
                   4561:        * 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}
                   4562:        * 3 Tprod[1]@21 {17, 7, 8, 9, 10, 11, 0 <repeats 15 times>}
                   4563:        * cptcovprod=11 (6+5)
                   4564:        * FixedV[Tvar[Tage[cptcovage]]]]  FixedV[2]=0      FixedV[3]=0      0      1          (age*V7)Tvar[16]=1 FixedV[absolute] not [kmodel]
                   4565:        *   FixedV[Tvar[17]=FixedV[age*V6*V2]=FixedV[9]=1        1         1          1         1  
                   4566:        * 3 FixedV[Tvar[17]=FixedV[age*V3*V2]=FixedV[9]=0        [11]=1         1          1         1  
                   4567:        * FixedV[]          V1=0     V2=0   V3=0  v4=0    V5=0  V6=1    V7=1 v8=1  OK then model dependent
                   4568:        *                   9=1  [V7*V2]=[10]=1 11=1  12=1  13=1  14=1
                   4569:        * 3                 9=0  [V7*V2]=[10]=1 11=1  12=1  13=1  14=1
                   4570:        * cptcovdageprod=5  for gnuplot printing
                   4571:        * cptcovprodvage=6 
                   4572:        * ncova=15           1        2       3       4       5
                   4573:        *                      6 7        8 9      10 11        12 13     14 15
                   4574:        * TvarA              2        3       4       6       7
                   4575:        *                      6 2        6 7       7 3          6 4       7 4
                   4576:        * TvaAind             12 12      13 13     14 14      15 15       16 16        
1.345     brouard  4577:        * ncovf            1     2      3
1.349     brouard  4578:        *                                    V6       V7      V6*V2     V7*V2     V6*V3     V7*V3     V6*V4     V7*V4
                   4579:        * ncovvt=14                            1      2        3 4       5 6       7 8       9 10     11 12     13 14     
                   4580:        * TvarVV[1]@14 = itv               {V6=6,     7, V6*V2=6, 2,     7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
                   4581:        * TvarVVind[1]@14=                    {4,     5,       6, 6,     7, 7,     8, 8,      9, 9,   10, 10,   11, 11}
                   4582:        * 3 ncovvt=12                        V6       V7      V7*V2     V6*V3     V7*V3     V6*V4     V7*V4
                   4583:        * 3 TvarVV[1]@12 = itv                {6,     7, V7*V2=7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
                   4584:        * 3                                    1      2        3  4      5  6      7  8      9 10     11 12
                   4585:        * TvarVVind[1]@12=         {V6 is in k=4,     5,  7,(4isV2)=7,   8, 8,      9, 9,   10,10,    11,11}TvarVVind[12]=k=11
                   4586:        * TvarV              6, 7, 9, 10, 11, 12, 13, 14
                   4587:        * 3 cptcovprodvage=6
                   4588:        * 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
                   4589:        * 3 TvarAVVA[1]@15= itva 3 2    2      3    4        6       7        6 3         7 3         6 4         7 4 
                   4590:        * 3 ncovta             1 2      3      4    5        6       7        8 9       10 11       12 13        14 15
1.354     brouard  4591:        *?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  4592:        * TvarAVVAind[1]@15= V3 is in k=6 6 12  13   14      15      16       18 18       19,19,     20,20        21,21}TvarVVAind[]
                   4593:        * 3 ncovvta=10     +age*V6 + age*V7 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   4594:        * 3 we want to compute =cotvar[mw[mi][i]][TvarVVA[ncovva]][i] at position TvarVVAind[ncovva]
                   4595:        * 3 TvarVVA[1]@10= itva   6       7        6 3         7 3         6 4         7 4 
                   4596:        * 3 ncovva                1       2        3 4         5 6         7 8         9 10
                   4597:        * TvarVVAind[1]@10= V6 is in k=4  5        8,8         9, 9,      10,10        11 11}TvarVVAind[]
                   4598:        * TvarVVAind[1]@10=       15       16     18,18        19,19,      20,20        21 21}TvarVVAind[]
                   4599:        * TvarVA              V3*V2=6 6 , 1, 2, 11, 12, 13, 14
1.345     brouard  4600:        * TvarFind[1]@14= {1,    2,     3,     0 <repeats 12 times>}
1.349     brouard  4601:        * Tvar[1]@21=     {2,    3,     4,    6,      7,      9,      10,        11,       12,      13,       14,
                   4602:        *                   2, 3, 4, 6, 7,
                   4603:        *                     6, 8, 9, 10, 11}
1.345     brouard  4604:        * TvarFind[itv]                        0      0       0
                   4605:        * FixedV[itv]                          1      1       1  0      1 0       1 0       1 0       0
1.354     brouard  4606:        *? FixedV[itv]                          1      1       1  0      1 0       1 0       1 0      1 0     1 0
1.345     brouard  4607:        * Tvar[TvarFind[ncovf]]=[1]=2 [2]=3 [4]=4
                   4608:        * Tvar[TvarFind[itv]]                [0]=?      ?ncovv 1 à ncovvt]
                   4609:        *   Not a fixed cotvar[mw][itv][i]     6       7      6  2      7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
1.349     brouard  4610:        *   fixed covar[itv]                  [6]     [7]    [6][2] 
1.345     brouard  4611:        */
                   4612: 
1.349     brouard  4613:       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 */
                   4614:        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  4615:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
1.345     brouard  4616:        /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   4617:        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  4618:          /* printf("DEBUG ncovv=%d, Varying TvarVV[ncovv]=%d\n",ncovv, TvarVV[ncovv]); */
1.345     brouard  4619:          cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
1.354     brouard  4620:          /* printf("DEBUG Varying cov[ioffset+ipos=%d]=%g \n",ioffset+ipos,cotvarv); */
1.340     brouard  4621:        }else{ /* fixed covariate */
1.345     brouard  4622:          /* 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  4623:          /* printf("DEBUG ncovv=%d, Fixed TvarVV[ncovv]=%d\n",ncovv, TvarVV[ncovv]); */
1.349     brouard  4624:          cotvarv=covar[itv][i];  /* Good: In V6*V3, 3 is fixed at position of the data */
1.354     brouard  4625:          /* printf("DEBUG Fixed cov[ioffset+ipos=%d]=%g \n",ioffset+ipos,cotvarv); */
1.340     brouard  4626:        }
1.339     brouard  4627:        if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  4628:          cotvarvold=cotvarv;
                   4629:        }else{ /* A second product */
                   4630:          cotvarv=cotvarv*cotvarvold;
1.339     brouard  4631:        }
                   4632:        iposold=ipos;
1.340     brouard  4633:        cov[ioffset+ipos]=cotvarv;
1.354     brouard  4634:        /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
1.339     brouard  4635:        /* For products */
                   4636:       }
                   4637:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates single *\/ */
                   4638:       /*       iv=TvarVDind[itv]; /\* iv, position in the model equation of time varying covariate itv *\/ */
                   4639:       /*       /\*         "V1+V3+age*V1+age*V3+V1*V3" with V3 time varying *\/ */
                   4640:       /*       /\*           1  2   3      4      5                         *\/ */
                   4641:       /*       /\*itv           1                                           *\/ */
                   4642:       /*       /\* TvarVInd[1]= 2                                           *\/ */
                   4643:       /*       /\* iv= Tvar[Tmodelind[itv]]-ncovcol-nqv;  /\\* Counting the # varying covariate from 1 to ntveff *\\/ *\/ */
                   4644:       /*       /\* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; *\/ */
                   4645:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; *\/ */
                   4646:       /*       /\* k=ioffset-2-nagesqr-cptcovage+itv; /\\* position in simple model *\\/ *\/ */
                   4647:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; *\/ */
                   4648:       /*       cov[ioffset+iv]=cotvar[mw[mi][i]][itv][i]; */
                   4649:       /*       /\* 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]); *\/ */
                   4650:       /* } */
1.232     brouard  4651:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  4652:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4653:       /*       /\* 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]); *\/ */
                   4654:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  4655:       /* } */
1.126     brouard  4656:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  4657:        for (j=1;j<=nlstate+ndeath;j++){
                   4658:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4659:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4660:        }
1.214     brouard  4661:       
                   4662:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4663:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   4664:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  4665:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  4666:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4667:          and mw[mi+1][i]. dh depends on stepm.*/
                   4668:        newm=savm;
1.247     brouard  4669:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  4670:        cov[2]=agexact;
                   4671:        if(nagesqr==1)
                   4672:          cov[3]= agexact*agexact;
1.349     brouard  4673:        for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   4674:          itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   4675:          ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4676:          /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   4677:          if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   4678:            /* printf("DEBUG  ncovva=%d, Varying TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   4679:            cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   4680:          }else{ /* fixed covariate */
                   4681:            /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
                   4682:            /* printf("DEBUG ncovva=%d, Fixed TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   4683:            cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   4684:          }
                   4685:          if(ipos!=iposold){ /* Not a product or first of a product */
                   4686:            cotvarvold=cotvarv;
                   4687:          }else{ /* A second product */
                   4688:            /* printf("DEBUG * \n"); */
                   4689:            cotvarv=cotvarv*cotvarvold;
                   4690:          }
                   4691:          iposold=ipos;
                   4692:          /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
                   4693:          cov[ioffset+ipos]=cotvarv*agexact;
                   4694:          /* For products */
1.242     brouard  4695:        }
1.349     brouard  4696: 
1.242     brouard  4697:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   4698:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4699:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4700:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4701:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   4702:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   4703:        savm=oldm;
                   4704:        oldm=newm;
1.126     brouard  4705:       } /* end mult */
1.336     brouard  4706:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   4707:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   4708:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   4709:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   4710:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   4711:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   4712:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   4713:         * probability in order to take into account the bias as a fraction of the way
                   4714:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   4715:                                 * -stepm/2 to stepm/2 .
                   4716:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   4717:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   4718:                                 */
1.126     brouard  4719:       s1=s[mw[mi][i]][i];
                   4720:       s2=s[mw[mi+1][i]][i];
1.217     brouard  4721:       /* if(s2==-1){ */
1.268     brouard  4722:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  4723:       /*       /\* exit(1); *\/ */
                   4724:       /* } */
1.126     brouard  4725:       bbh=(double)bh[mi][i]/(double)stepm; 
                   4726:       /* bias is positive if real duration
                   4727:        * is higher than the multiple of stepm and negative otherwise.
                   4728:        */
                   4729:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  4730:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4731:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  4732:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   4733:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4734:        lli= log(survp);
1.126     brouard  4735:       }else if (mle==1){
1.242     brouard  4736:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  4737:       } else if(mle==2){
1.242     brouard  4738:        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  4739:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  4740:        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  4741:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  4742:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  4743:       } else{  /* mle=0 back to 1 */
1.242     brouard  4744:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4745:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  4746:       } /* End of if */
                   4747:       ipmx +=1;
                   4748:       sw += weight[i];
                   4749:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.342     brouard  4750:       /* Printing covariates values for each contribution for checking */
1.343     brouard  4751:       /* 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  4752:       if(globpr){
1.246     brouard  4753:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  4754:  %11.6f %11.6f %11.6f ", \
1.242     brouard  4755:                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  4756:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.343     brouard  4757:        /*      printf("%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\ */
                   4758:        /* %11.6f %11.6f %11.6f ", \ */
                   4759:        /*              num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw, */
                   4760:        /*              2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
1.242     brouard  4761:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   4762:          llt +=ll[k]*gipmx/gsw;
                   4763:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
1.335     brouard  4764:          /* printf(" %10.6f",-ll[k]*gipmx/gsw); */
1.242     brouard  4765:        }
1.343     brouard  4766:        fprintf(ficresilk," %10.6f ", -llt);
1.335     brouard  4767:        /* printf(" %10.6f\n", -llt); */
1.342     brouard  4768:        /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
1.343     brouard  4769:        /* fprintf(ficresilk,"%09ld ", num[i]); */ /* not necessary */
                   4770:        for (kf=1; kf<=ncovf;kf++){ /* Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
                   4771:          fprintf(ficresilk," %g",covar[Tvar[TvarFind[kf]]][i]);
                   4772:        }
                   4773:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age) including individual from products */
                   4774:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4775:          if(ipos!=iposold){ /* Not a product or first of a product */
                   4776:            fprintf(ficresilk," %g",cov[ioffset+ipos]);
                   4777:            /* printf(" %g",cov[ioffset+ipos]); */
                   4778:          }else{
                   4779:            fprintf(ficresilk,"*");
                   4780:            /* printf("*"); */
1.342     brouard  4781:          }
1.343     brouard  4782:          iposold=ipos;
                   4783:        }
1.349     brouard  4784:        /* for (kk=1; kk<=cptcovage;kk++) { */
                   4785:        /*   if(!FixedV[Tvar[Tage[kk]]]){ */
                   4786:        /*     fprintf(ficresilk," %g*age",covar[Tvar[Tage[kk]]][i]); */
                   4787:        /*     /\* printf(" %g*age",covar[Tvar[Tage[kk]]][i]); *\/ */
                   4788:        /*   }else{ */
                   4789:        /*     fprintf(ficresilk," %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
                   4790:        /*     /\* printf(" %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\\/  *\/ */
                   4791:        /*   } */
                   4792:        /* } */
                   4793:        for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   4794:          itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   4795:          ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4796:          /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   4797:          if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   4798:            /* printf("DEBUG  ncovva=%d, Varying TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   4799:            cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   4800:          }else{ /* fixed covariate */
                   4801:            /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
                   4802:            /* printf("DEBUG ncovva=%d, Fixed TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   4803:            cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   4804:          }
                   4805:          if(ipos!=iposold){ /* Not a product or first of a product */
                   4806:            cotvarvold=cotvarv;
                   4807:          }else{ /* A second product */
                   4808:            /* printf("DEBUG * \n"); */
                   4809:            cotvarv=cotvarv*cotvarvold;
1.342     brouard  4810:          }
1.349     brouard  4811:          cotvarv=cotvarv*agexact;
                   4812:          fprintf(ficresilk," %g*age",cotvarv);
                   4813:          iposold=ipos;
                   4814:          /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
                   4815:          cov[ioffset+ipos]=cotvarv;
                   4816:          /* For products */
1.343     brouard  4817:        }
                   4818:        /* printf("\n"); */
1.342     brouard  4819:        /* } /\*  End debugILK *\/ */
                   4820:        fprintf(ficresilk,"\n");
                   4821:       } /* End if globpr */
1.335     brouard  4822:     } /* end of wave */
                   4823:   } /* end of individual */
                   4824:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
1.232     brouard  4825: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
1.335     brouard  4826:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4827:   if(globpr==0){ /* First time we count the contributions and weights */
                   4828:     gipmx=ipmx;
                   4829:     gsw=sw;
                   4830:   }
1.343     brouard  4831:   return -l;
1.126     brouard  4832: }
                   4833: 
                   4834: 
                   4835: /*************** function likelione ***********/
1.292     brouard  4836: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  4837: {
                   4838:   /* This routine should help understanding what is done with 
                   4839:      the selection of individuals/waves and
                   4840:      to check the exact contribution to the likelihood.
                   4841:      Plotting could be done.
1.342     brouard  4842:   */
                   4843:   void pstamp(FILE *ficres);
1.343     brouard  4844:   int k, kf, kk, kvar, ncovv, iposold, ipos;
1.126     brouard  4845: 
                   4846:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  4847:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  4848:     strcat(fileresilk,fileresu);
1.126     brouard  4849:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   4850:       printf("Problem with resultfile: %s\n", fileresilk);
                   4851:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   4852:     }
1.342     brouard  4853:     pstamp(ficresilk);fprintf(ficresilk,"# model=1+age+%s\n",model);
1.214     brouard  4854:     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");
                   4855:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  4856:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   4857:     for(k=1; k<=nlstate; k++) 
                   4858:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
1.342     brouard  4859:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total) ");
                   4860: 
                   4861:     /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
                   4862:       for(kf=1;kf <= ncovf; kf++){
                   4863:        fprintf(ficresilk,"V%d",Tvar[TvarFind[kf]]);
                   4864:        /* printf("V%d",Tvar[TvarFind[kf]]); */
                   4865:       }
                   4866:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){
1.343     brouard  4867:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
1.342     brouard  4868:        if(ipos!=iposold){ /* Not a product or first of a product */
                   4869:          /* printf(" %d",ipos); */
                   4870:          fprintf(ficresilk," V%d",TvarVV[ncovv]);
                   4871:        }else{
                   4872:          /* printf("*"); */
                   4873:          fprintf(ficresilk,"*");
1.343     brouard  4874:        }
1.342     brouard  4875:        iposold=ipos;
                   4876:       }
                   4877:       for (kk=1; kk<=cptcovage;kk++) {
                   4878:        if(!FixedV[Tvar[Tage[kk]]]){
                   4879:          /* printf(" %d*age(Fixed)",Tvar[Tage[kk]]); */
                   4880:          fprintf(ficresilk," %d*age(Fixed)",Tvar[Tage[kk]]);
                   4881:        }else{
                   4882:          fprintf(ficresilk," %d*age(Varying)",Tvar[Tage[kk]]);/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
                   4883:          /* printf(" %d*age(Varying)",Tvar[Tage[kk]]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
                   4884:        }
                   4885:       }
                   4886:     /* } /\* End if debugILK *\/ */
                   4887:     /* printf("\n"); */
                   4888:     fprintf(ficresilk,"\n");
                   4889:   } /* End glogpri */
1.126     brouard  4890: 
1.292     brouard  4891:   *fretone=(*func)(p);
1.126     brouard  4892:   if(*globpri !=0){
                   4893:     fclose(ficresilk);
1.205     brouard  4894:     if (mle ==0)
                   4895:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   4896:     else if(mle >=1)
                   4897:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   4898:     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  4899:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  4900:       
1.207     brouard  4901:     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  4902: <img src=\"%s-ori.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4903:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.343     brouard  4904: <img src=\"%s-dest.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
                   4905:     
                   4906:     for (k=1; k<= nlstate ; k++) {
                   4907:       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 \
                   4908: <img src=\"%s-p%dj.png\">\n",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   4909:       for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
1.350     brouard  4910:         kvar=Tvar[TvarFind[kf]];  /* variable */
                   4911:         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]]);
                   4912:         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);
                   4913:         fprintf(fichtm,"<img src=\"%s-p%dj-%d.png\">",subdirf2(optionfilefiname,"ILK_"),k,Tvar[TvarFind[kf]]);
1.343     brouard  4914:       }
                   4915:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Loop on the time varying extended covariates (with extension of Vn*Vm */
                   4916:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   4917:        kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   4918:        /* 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]); */
                   4919:        if(ipos!=iposold){ /* Not a product or first of a product */
                   4920:          /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   4921:          /* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); */
                   4922:          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)  */
                   4923:            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> \
                   4924: <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);
                   4925:          } /* End only for dummies time varying (single?) */
                   4926:        }else{ /* Useless product */
                   4927:          /* printf("*"); */
                   4928:          /* fprintf(ficresilk,"*"); */ 
                   4929:        }
                   4930:        iposold=ipos;
                   4931:       } /* For each time varying covariate */
                   4932:     } /* End loop on states */
                   4933: 
                   4934: /*     if(debugILK){ */
                   4935: /*       for(kf=1; kf <= ncovf; kf++){ /\* For each simple dummy covariate of the model *\/ */
                   4936: /*     /\* kvar=Tvar[TvarFind[kf]]; *\/ /\* variable *\/ */
                   4937: /*     for (k=1; k<= nlstate ; k++) { */
                   4938: /*       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> \ */
                   4939: /* <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]]); */
                   4940: /*     } */
                   4941: /*       } */
                   4942: /*       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /\* Loop on the time varying extended covariates (with extension of Vn*Vm *\/ */
                   4943: /*     ipos=TvarVVind[ncovv]; /\* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate *\/ */
                   4944: /*     kvar=TvarVV[ncovv]; /\*  TvarVV={3, 1, 3} gives the name of each varying covariate *\/ */
                   4945: /*     /\* 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]); *\/ */
                   4946: /*     if(ipos!=iposold){ /\* Not a product or first of a product *\/ */
                   4947: /*       /\* fprintf(ficresilk," V%d",TvarVV[ncovv]); *\/ */
                   4948: /*       /\* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); *\/ */
                   4949: /*       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)  *\/ */
                   4950: /*         for (k=1; k<= nlstate ; k++) { */
                   4951: /*           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> \ */
                   4952: /* <img src=\"%s-p%dj-%d.png\">",k,k,kvar,kvar,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,kvar); */
                   4953: /*         } /\* End state *\/ */
                   4954: /*       } /\* End only for dummies time varying (single?) *\/ */
                   4955: /*     }else{ /\* Useless product *\/ */
                   4956: /*       /\* printf("*"); *\/ */
                   4957: /*       /\* fprintf(ficresilk,"*"); *\/  */
                   4958: /*     } */
                   4959: /*     iposold=ipos; */
                   4960: /*       } /\* For each time varying covariate *\/ */
                   4961: /*     }/\* End debugILK *\/ */
1.207     brouard  4962:     fflush(fichtm);
1.343     brouard  4963:   }/* End globpri */
1.126     brouard  4964:   return;
                   4965: }
                   4966: 
                   4967: 
                   4968: /*********** Maximum Likelihood Estimation ***************/
                   4969: 
                   4970: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   4971: {
1.319     brouard  4972:   int i,j,k, jk, jkk=0, iter=0;
1.126     brouard  4973:   double **xi;
                   4974:   double fret;
                   4975:   double fretone; /* Only one call to likelihood */
                   4976:   /*  char filerespow[FILENAMELENGTH];*/
1.354     brouard  4977:   
                   4978:   double * p1; /* Shifted parameters from 0 instead of 1 */
1.162     brouard  4979: #ifdef NLOPT
                   4980:   int creturn;
                   4981:   nlopt_opt opt;
                   4982:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   4983:   double *lb;
                   4984:   double minf; /* the minimum objective value, upon return */
1.354     brouard  4985: 
1.162     brouard  4986:   myfunc_data dinst, *d = &dinst;
                   4987: #endif
                   4988: 
                   4989: 
1.126     brouard  4990:   xi=matrix(1,npar,1,npar);
1.357     brouard  4991:   for (i=1;i<=npar;i++)  /* Starting with canonical directions j=1,n xi[i=1,n][j] */
1.126     brouard  4992:     for (j=1;j<=npar;j++)
                   4993:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   4994:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  4995:   strcpy(filerespow,"POW_"); 
1.126     brouard  4996:   strcat(filerespow,fileres);
                   4997:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   4998:     printf("Problem with resultfile: %s\n", filerespow);
                   4999:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   5000:   }
                   5001:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   5002:   for (i=1;i<=nlstate;i++)
                   5003:     for(j=1;j<=nlstate+ndeath;j++)
                   5004:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   5005:   fprintf(ficrespow,"\n");
1.162     brouard  5006: #ifdef POWELL
1.319     brouard  5007: #ifdef LINMINORIGINAL
                   5008: #else /* LINMINORIGINAL */
                   5009:   
                   5010:   flatdir=ivector(1,npar); 
                   5011:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   5012: #endif /*LINMINORIGINAL */
                   5013: 
                   5014: #ifdef FLATSUP
                   5015:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   5016:   /* reorganizing p by suppressing flat directions */
                   5017:   for(i=1, jk=1; i <=nlstate; i++){
                   5018:     for(k=1; k <=(nlstate+ndeath); k++){
                   5019:       if (k != i) {
                   5020:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   5021:         if(flatdir[jk]==1){
                   5022:           printf(" To be skipped %d%d flatdir[%d]=%d ",i,k,jk, flatdir[jk]);
                   5023:         }
                   5024:         for(j=1; j <=ncovmodel; j++){
                   5025:           printf("%12.7f ",p[jk]);
                   5026:           jk++; 
                   5027:         }
                   5028:         printf("\n");
                   5029:       }
                   5030:     }
                   5031:   }
                   5032: /* skipping */
                   5033:   /* for(i=1, jk=1, jkk=1;(flatdir[jk]==0)&& (i <=nlstate); i++){ */
                   5034:   for(i=1, jk=1, jkk=1;i <=nlstate; i++){
                   5035:     for(k=1; k <=(nlstate+ndeath); k++){
                   5036:       if (k != i) {
                   5037:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   5038:         if(flatdir[jk]==1){
                   5039:           printf(" To be skipped %d%d flatdir[%d]=%d jk=%d p[%d] ",i,k,jk, flatdir[jk],jk, jk);
                   5040:           for(j=1; j <=ncovmodel;  jk++,j++){
                   5041:             printf(" p[%d]=%12.7f",jk, p[jk]);
                   5042:             /*q[jjk]=p[jk];*/
                   5043:           }
                   5044:         }else{
                   5045:           printf(" To be kept %d%d flatdir[%d]=%d jk=%d q[%d]=p[%d] ",i,k,jk, flatdir[jk],jk, jkk, jk);
                   5046:           for(j=1; j <=ncovmodel;  jk++,jkk++,j++){
                   5047:             printf(" p[%d]=%12.7f=q[%d]",jk, p[jk],jkk);
                   5048:             /*q[jjk]=p[jk];*/
                   5049:           }
                   5050:         }
                   5051:         printf("\n");
                   5052:       }
                   5053:       fflush(stdout);
                   5054:     }
                   5055:   }
                   5056:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   5057: #else  /* FLATSUP */
1.126     brouard  5058:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.319     brouard  5059: #endif  /* FLATSUP */
                   5060: 
                   5061: #ifdef LINMINORIGINAL
                   5062: #else
                   5063:       free_ivector(flatdir,1,npar); 
                   5064: #endif  /* LINMINORIGINAL*/
                   5065: #endif /* POWELL */
1.126     brouard  5066: 
1.162     brouard  5067: #ifdef NLOPT
                   5068: #ifdef NEWUOA
                   5069:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   5070: #else
                   5071:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   5072: #endif
                   5073:   lb=vector(0,npar-1);
                   5074:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   5075:   nlopt_set_lower_bounds(opt, lb);
                   5076:   nlopt_set_initial_step1(opt, 0.1);
                   5077:   
                   5078:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   5079:   d->function = func;
                   5080:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   5081:   nlopt_set_min_objective(opt, myfunc, d);
                   5082:   nlopt_set_xtol_rel(opt, ftol);
                   5083:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   5084:     printf("nlopt failed! %d\n",creturn); 
                   5085:   }
                   5086:   else {
                   5087:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   5088:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   5089:     iter=1; /* not equal */
                   5090:   }
                   5091:   nlopt_destroy(opt);
                   5092: #endif
1.319     brouard  5093: #ifdef FLATSUP
                   5094:   /* npared = npar -flatd/ncovmodel; */
                   5095:   /* xired= matrix(1,npared,1,npared); */
                   5096:   /* paramred= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */
                   5097:   /* powell(pred,xired,npared,ftol,&iter,&fret,flatdir,func); */
                   5098:   /* free_matrix(xire,1,npared,1,npared); */
                   5099: #else  /* FLATSUP */
                   5100: #endif /* FLATSUP */
1.126     brouard  5101:   free_matrix(xi,1,npar,1,npar);
                   5102:   fclose(ficrespow);
1.203     brouard  5103:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   5104:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  5105:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  5106: 
                   5107: }
                   5108: 
                   5109: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  5110: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  5111: {
                   5112:   double  **a,**y,*x,pd;
1.203     brouard  5113:   /* double **hess; */
1.164     brouard  5114:   int i, j;
1.126     brouard  5115:   int *indx;
                   5116: 
                   5117:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  5118:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  5119:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   5120:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   5121:   double gompertz(double p[]);
1.203     brouard  5122:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  5123: 
                   5124:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   5125:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   5126:   for (i=1;i<=npar;i++){
1.203     brouard  5127:     printf("%d-",i);fflush(stdout);
                   5128:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  5129:    
                   5130:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   5131:     
                   5132:     /*  printf(" %f ",p[i]);
                   5133:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   5134:   }
                   5135:   
                   5136:   for (i=1;i<=npar;i++) {
                   5137:     for (j=1;j<=npar;j++)  {
                   5138:       if (j>i) { 
1.203     brouard  5139:        printf(".%d-%d",i,j);fflush(stdout);
                   5140:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   5141:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  5142:        
                   5143:        hess[j][i]=hess[i][j];    
                   5144:        /*printf(" %lf ",hess[i][j]);*/
                   5145:       }
                   5146:     }
                   5147:   }
                   5148:   printf("\n");
                   5149:   fprintf(ficlog,"\n");
                   5150: 
                   5151:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   5152:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   5153:   
                   5154:   a=matrix(1,npar,1,npar);
                   5155:   y=matrix(1,npar,1,npar);
                   5156:   x=vector(1,npar);
                   5157:   indx=ivector(1,npar);
                   5158:   for (i=1;i<=npar;i++)
                   5159:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   5160:   ludcmp(a,npar,indx,&pd);
                   5161: 
                   5162:   for (j=1;j<=npar;j++) {
                   5163:     for (i=1;i<=npar;i++) x[i]=0;
                   5164:     x[j]=1;
                   5165:     lubksb(a,npar,indx,x);
                   5166:     for (i=1;i<=npar;i++){ 
                   5167:       matcov[i][j]=x[i];
                   5168:     }
                   5169:   }
                   5170: 
                   5171:   printf("\n#Hessian matrix#\n");
                   5172:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   5173:   for (i=1;i<=npar;i++) { 
                   5174:     for (j=1;j<=npar;j++) { 
1.203     brouard  5175:       printf("%.6e ",hess[i][j]);
                   5176:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  5177:     }
                   5178:     printf("\n");
                   5179:     fprintf(ficlog,"\n");
                   5180:   }
                   5181: 
1.203     brouard  5182:   /* printf("\n#Covariance matrix#\n"); */
                   5183:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   5184:   /* for (i=1;i<=npar;i++) {  */
                   5185:   /*   for (j=1;j<=npar;j++) {  */
                   5186:   /*     printf("%.6e ",matcov[i][j]); */
                   5187:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   5188:   /*   } */
                   5189:   /*   printf("\n"); */
                   5190:   /*   fprintf(ficlog,"\n"); */
                   5191:   /* } */
                   5192: 
1.126     brouard  5193:   /* Recompute Inverse */
1.203     brouard  5194:   /* for (i=1;i<=npar;i++) */
                   5195:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   5196:   /* ludcmp(a,npar,indx,&pd); */
                   5197: 
                   5198:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   5199: 
                   5200:   /* for (j=1;j<=npar;j++) { */
                   5201:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   5202:   /*   x[j]=1; */
                   5203:   /*   lubksb(a,npar,indx,x); */
                   5204:   /*   for (i=1;i<=npar;i++){  */
                   5205:   /*     y[i][j]=x[i]; */
                   5206:   /*     printf("%.3e ",y[i][j]); */
                   5207:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   5208:   /*   } */
                   5209:   /*   printf("\n"); */
                   5210:   /*   fprintf(ficlog,"\n"); */
                   5211:   /* } */
                   5212: 
                   5213:   /* Verifying the inverse matrix */
                   5214: #ifdef DEBUGHESS
                   5215:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  5216: 
1.203     brouard  5217:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   5218:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  5219: 
                   5220:   for (j=1;j<=npar;j++) {
                   5221:     for (i=1;i<=npar;i++){ 
1.203     brouard  5222:       printf("%.2f ",y[i][j]);
                   5223:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  5224:     }
                   5225:     printf("\n");
                   5226:     fprintf(ficlog,"\n");
                   5227:   }
1.203     brouard  5228: #endif
1.126     brouard  5229: 
                   5230:   free_matrix(a,1,npar,1,npar);
                   5231:   free_matrix(y,1,npar,1,npar);
                   5232:   free_vector(x,1,npar);
                   5233:   free_ivector(indx,1,npar);
1.203     brouard  5234:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  5235: 
                   5236: 
                   5237: }
                   5238: 
                   5239: /*************** hessian matrix ****************/
                   5240: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  5241: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  5242:   int i;
                   5243:   int l=1, lmax=20;
1.203     brouard  5244:   double k1,k2, res, fx;
1.132     brouard  5245:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  5246:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   5247:   int k=0,kmax=10;
                   5248:   double l1;
                   5249: 
                   5250:   fx=func(x);
                   5251:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  5252:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  5253:     l1=pow(10,l);
                   5254:     delts=delt;
                   5255:     for(k=1 ; k <kmax; k=k+1){
                   5256:       delt = delta*(l1*k);
                   5257:       p2[theta]=x[theta] +delt;
1.145     brouard  5258:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  5259:       p2[theta]=x[theta]-delt;
                   5260:       k2=func(p2)-fx;
                   5261:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  5262:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  5263:       
1.203     brouard  5264: #ifdef DEBUGHESSII
1.126     brouard  5265:       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);
                   5266:       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);
                   5267: #endif
                   5268:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   5269:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   5270:        k=kmax;
                   5271:       }
                   5272:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  5273:        k=kmax; l=lmax*10;
1.126     brouard  5274:       }
                   5275:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   5276:        delts=delt;
                   5277:       }
1.203     brouard  5278:     } /* End loop k */
1.126     brouard  5279:   }
                   5280:   delti[theta]=delts;
                   5281:   return res; 
                   5282:   
                   5283: }
                   5284: 
1.203     brouard  5285: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  5286: {
                   5287:   int i;
1.164     brouard  5288:   int l=1, lmax=20;
1.126     brouard  5289:   double k1,k2,k3,k4,res,fx;
1.132     brouard  5290:   double p2[MAXPARM+1];
1.203     brouard  5291:   int k, kmax=1;
                   5292:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  5293: 
                   5294:   int firstime=0;
1.203     brouard  5295:   
1.126     brouard  5296:   fx=func(x);
1.203     brouard  5297:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  5298:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  5299:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   5300:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  5301:     k1=func(p2)-fx;
                   5302:   
1.203     brouard  5303:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   5304:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  5305:     k2=func(p2)-fx;
                   5306:   
1.203     brouard  5307:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   5308:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  5309:     k3=func(p2)-fx;
                   5310:   
1.203     brouard  5311:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   5312:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  5313:     k4=func(p2)-fx;
1.203     brouard  5314:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   5315:     if(k1*k2*k3*k4 <0.){
1.208     brouard  5316:       firstime=1;
1.203     brouard  5317:       kmax=kmax+10;
1.208     brouard  5318:     }
                   5319:     if(kmax >=10 || firstime ==1){
1.354     brouard  5320:       /* What are the thetai and thetaj? thetai/ncovmodel thetai=(thetai-thetai%ncovmodel)/ncovmodel +thetai%ncovmodel=(line,pos)  */
1.246     brouard  5321:       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);
                   5322:       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  5323:       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);
                   5324:       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);
                   5325:     }
                   5326: #ifdef DEBUGHESSIJ
                   5327:     v1=hess[thetai][thetai];
                   5328:     v2=hess[thetaj][thetaj];
                   5329:     cv12=res;
                   5330:     /* Computing eigen value of Hessian matrix */
                   5331:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5332:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5333:     if ((lc2 <0) || (lc1 <0) ){
                   5334:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   5335:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   5336:       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);
                   5337:       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);
                   5338:     }
1.126     brouard  5339: #endif
                   5340:   }
                   5341:   return res;
                   5342: }
                   5343: 
1.203     brouard  5344:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   5345: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   5346: /* { */
                   5347: /*   int i; */
                   5348: /*   int l=1, lmax=20; */
                   5349: /*   double k1,k2,k3,k4,res,fx; */
                   5350: /*   double p2[MAXPARM+1]; */
                   5351: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   5352: /*   int k=0,kmax=10; */
                   5353: /*   double l1; */
                   5354:   
                   5355: /*   fx=func(x); */
                   5356: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   5357: /*     l1=pow(10,l); */
                   5358: /*     delts=delt; */
                   5359: /*     for(k=1 ; k <kmax; k=k+1){ */
                   5360: /*       delt = delti*(l1*k); */
                   5361: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   5362: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   5363: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   5364: /*       k1=func(p2)-fx; */
                   5365:       
                   5366: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   5367: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   5368: /*       k2=func(p2)-fx; */
                   5369:       
                   5370: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   5371: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   5372: /*       k3=func(p2)-fx; */
                   5373:       
                   5374: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   5375: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   5376: /*       k4=func(p2)-fx; */
                   5377: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   5378: /* #ifdef DEBUGHESSIJ */
                   5379: /*       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); */
                   5380: /*       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); */
                   5381: /* #endif */
                   5382: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   5383: /*     k=kmax; */
                   5384: /*       } */
                   5385: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   5386: /*     k=kmax; l=lmax*10; */
                   5387: /*       } */
                   5388: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   5389: /*     delts=delt; */
                   5390: /*       } */
                   5391: /*     } /\* End loop k *\/ */
                   5392: /*   } */
                   5393: /*   delti[theta]=delts; */
                   5394: /*   return res;  */
                   5395: /* } */
                   5396: 
                   5397: 
1.126     brouard  5398: /************** Inverse of matrix **************/
                   5399: void ludcmp(double **a, int n, int *indx, double *d) 
                   5400: { 
                   5401:   int i,imax,j,k; 
                   5402:   double big,dum,sum,temp; 
                   5403:   double *vv; 
                   5404:  
                   5405:   vv=vector(1,n); 
                   5406:   *d=1.0; 
                   5407:   for (i=1;i<=n;i++) { 
                   5408:     big=0.0; 
                   5409:     for (j=1;j<=n;j++) 
                   5410:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  5411:     if (big == 0.0){
                   5412:       printf(" Singular Hessian matrix at row %d:\n",i);
                   5413:       for (j=1;j<=n;j++) {
                   5414:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   5415:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   5416:       }
                   5417:       fflush(ficlog);
                   5418:       fclose(ficlog);
                   5419:       nrerror("Singular matrix in routine ludcmp"); 
                   5420:     }
1.126     brouard  5421:     vv[i]=1.0/big; 
                   5422:   } 
                   5423:   for (j=1;j<=n;j++) { 
                   5424:     for (i=1;i<j;i++) { 
                   5425:       sum=a[i][j]; 
                   5426:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   5427:       a[i][j]=sum; 
                   5428:     } 
                   5429:     big=0.0; 
                   5430:     for (i=j;i<=n;i++) { 
                   5431:       sum=a[i][j]; 
                   5432:       for (k=1;k<j;k++) 
                   5433:        sum -= a[i][k]*a[k][j]; 
                   5434:       a[i][j]=sum; 
                   5435:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   5436:        big=dum; 
                   5437:        imax=i; 
                   5438:       } 
                   5439:     } 
                   5440:     if (j != imax) { 
                   5441:       for (k=1;k<=n;k++) { 
                   5442:        dum=a[imax][k]; 
                   5443:        a[imax][k]=a[j][k]; 
                   5444:        a[j][k]=dum; 
                   5445:       } 
                   5446:       *d = -(*d); 
                   5447:       vv[imax]=vv[j]; 
                   5448:     } 
                   5449:     indx[j]=imax; 
                   5450:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   5451:     if (j != n) { 
                   5452:       dum=1.0/(a[j][j]); 
                   5453:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   5454:     } 
                   5455:   } 
                   5456:   free_vector(vv,1,n);  /* Doesn't work */
                   5457: ;
                   5458: } 
                   5459: 
                   5460: void lubksb(double **a, int n, int *indx, double b[]) 
                   5461: { 
                   5462:   int i,ii=0,ip,j; 
                   5463:   double sum; 
                   5464:  
                   5465:   for (i=1;i<=n;i++) { 
                   5466:     ip=indx[i]; 
                   5467:     sum=b[ip]; 
                   5468:     b[ip]=b[i]; 
                   5469:     if (ii) 
                   5470:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   5471:     else if (sum) ii=i; 
                   5472:     b[i]=sum; 
                   5473:   } 
                   5474:   for (i=n;i>=1;i--) { 
                   5475:     sum=b[i]; 
                   5476:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   5477:     b[i]=sum/a[i][i]; 
                   5478:   } 
                   5479: } 
                   5480: 
                   5481: void pstamp(FILE *fichier)
                   5482: {
1.196     brouard  5483:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  5484: }
                   5485: 
1.297     brouard  5486: void date2dmy(double date,double *day, double *month, double *year){
                   5487:   double yp=0., yp1=0., yp2=0.;
                   5488:   
                   5489:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   5490:                        fractional in yp1 */
                   5491:   *year=yp;
                   5492:   yp2=modf((yp1*12),&yp);
                   5493:   *month=yp;
                   5494:   yp1=modf((yp2*30.5),&yp);
                   5495:   *day=yp;
                   5496:   if(*day==0) *day=1;
                   5497:   if(*month==0) *month=1;
                   5498: }
                   5499: 
1.253     brouard  5500: 
                   5501: 
1.126     brouard  5502: /************ Frequencies ********************/
1.251     brouard  5503: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  5504:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   5505:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  5506: {  /* Some frequencies as well as proposing some starting values */
1.332     brouard  5507:   /* Frequencies of any combination of dummy covariate used in the model equation */ 
1.265     brouard  5508:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  5509:   int iind=0, iage=0;
                   5510:   int mi; /* Effective wave */
                   5511:   int first;
                   5512:   double ***freq; /* Frequencies */
1.268     brouard  5513:   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 */
                   5514:   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  5515:   double *meanq, *stdq, *idq;
1.226     brouard  5516:   double **meanqt;
                   5517:   double *pp, **prop, *posprop, *pospropt;
                   5518:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   5519:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   5520:   double agebegin, ageend;
                   5521:     
                   5522:   pp=vector(1,nlstate);
1.251     brouard  5523:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  5524:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   5525:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   5526:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   5527:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  5528:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  5529:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  5530:   meanqt=matrix(1,lastpass,1,nqtveff);
                   5531:   strcpy(fileresp,"P_");
                   5532:   strcat(fileresp,fileresu);
                   5533:   /*strcat(fileresphtm,fileresu);*/
                   5534:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   5535:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   5536:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   5537:     exit(0);
                   5538:   }
1.240     brouard  5539:   
1.226     brouard  5540:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   5541:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   5542:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5543:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5544:     fflush(ficlog);
                   5545:     exit(70); 
                   5546:   }
                   5547:   else{
                   5548:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  5549: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  5550: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5551:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5552:   }
1.319     brouard  5553:   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  5554:   
1.226     brouard  5555:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   5556:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   5557:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5558:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5559:     fflush(ficlog);
                   5560:     exit(70); 
1.240     brouard  5561:   } else{
1.226     brouard  5562:     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  5563: ,<hr size=\"2\" color=\"#EC5E5E\"> \n                                  \
1.214     brouard  5564: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5565:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5566:   }
1.319     brouard  5567:   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  5568:   
1.253     brouard  5569:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   5570:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  5571:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  5572:   j1=0;
1.126     brouard  5573:   
1.227     brouard  5574:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
1.335     brouard  5575:   j=cptcoveff;  /* Only simple dummy covariates used in the model */
1.330     brouard  5576:   /* j=cptcovn;  /\* Only dummy covariates of the model *\/ */
1.226     brouard  5577:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  5578:   
                   5579:   
1.226     brouard  5580:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   5581:      reference=low_education V1=0,V2=0
                   5582:      med_educ                V1=1 V2=0, 
                   5583:      high_educ               V1=0 V2=1
1.330     brouard  5584:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcovn 
1.226     brouard  5585:   */
1.249     brouard  5586:   dateintsum=0;
                   5587:   k2cpt=0;
                   5588: 
1.253     brouard  5589:   if(cptcoveff == 0 )
1.265     brouard  5590:     nl=1;  /* Constant and age model only */
1.253     brouard  5591:   else
                   5592:     nl=2;
1.265     brouard  5593: 
                   5594:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   5595:   /* Loop on nj=1 or 2 if dummy covariates j!=0
1.335     brouard  5596:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
1.265     brouard  5597:    *     freq[s1][s2][iage] =0.
                   5598:    *     Loop on iind
                   5599:    *       ++freq[s1][s2][iage] weighted
                   5600:    *     end iind
                   5601:    *     if covariate and j!0
                   5602:    *       headers Variable on one line
                   5603:    *     endif cov j!=0
                   5604:    *     header of frequency table by age
                   5605:    *     Loop on age
                   5606:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   5607:    *       pos+=freq[s1][s2][iage] weighted
                   5608:    *       Loop on s1 initial state
                   5609:    *         fprintf(ficresp
                   5610:    *       end s1
                   5611:    *     end age
                   5612:    *     if j!=0 computes starting values
                   5613:    *     end compute starting values
                   5614:    *   end j1
                   5615:    * end nl 
                   5616:    */
1.253     brouard  5617:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   5618:     if(nj==1)
                   5619:       j=0;  /* First pass for the constant */
1.265     brouard  5620:     else{
1.335     brouard  5621:       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  5622:     }
1.251     brouard  5623:     first=1;
1.332     brouard  5624:     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  5625:       posproptt=0.;
1.330     brouard  5626:       /*printf("cptcovn=%d Tvaraff=%d", cptcovn,Tvaraff[1]);
1.251     brouard  5627:        scanf("%d", i);*/
                   5628:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  5629:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  5630:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  5631:            freq[i][s2][m]=0;
1.251     brouard  5632:       
                   5633:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  5634:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  5635:          prop[i][m]=0;
                   5636:        posprop[i]=0;
                   5637:        pospropt[i]=0;
                   5638:       }
1.283     brouard  5639:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  5640:         idq[z1]=0.;
                   5641:         meanq[z1]=0.;
                   5642:         stdq[z1]=0.;
1.283     brouard  5643:       }
                   5644:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  5645:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  5646:       /*         meanqt[m][z1]=0.; */
                   5647:       /*       } */
                   5648:       /* }       */
1.251     brouard  5649:       /* dateintsum=0; */
                   5650:       /* k2cpt=0; */
                   5651:       
1.265     brouard  5652:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  5653:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   5654:        bool=1;
                   5655:        if(j !=0){
                   5656:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.335     brouard  5657:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   5658:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
1.251     brouard  5659:                /* if(Tvaraff[z1] ==-20){ */
                   5660:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   5661:                /* }else  if(Tvaraff[z1] ==-10){ */
                   5662:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
1.330     brouard  5663:                /* }else  */ /* TODO TODO codtabm(j1,z1) or codtabm(j1,Tvaraff[z1]]z1)*/
1.335     brouard  5664:                /* 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); */
                   5665:                if(Tvaraff[z1]<1 || Tvaraff[z1]>=NCOVMAX)
1.338     brouard  5666:                  printf("Error Tvaraff[z1]=%d<1 or >=%d, cptcoveff=%d model=1+age+%s\n",Tvaraff[z1],NCOVMAX, cptcoveff, model);
1.332     brouard  5667:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]){ /* for combination j1 of covariates */
1.265     brouard  5668:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  5669:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
1.332     brouard  5670:                  /* 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", */
                   5671:                  /*   bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),*/
                   5672:                   /*   j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
1.251     brouard  5673:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   5674:                } /* Onlyf fixed */
                   5675:              } /* end z1 */
1.335     brouard  5676:            } /* cptcoveff > 0 */
1.251     brouard  5677:          } /* end any */
                   5678:        }/* end j==0 */
1.265     brouard  5679:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  5680:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  5681:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  5682:            m=mw[mi][iind];
                   5683:            if(j!=0){
                   5684:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
1.335     brouard  5685:                for (z1=1; z1<=cptcoveff; z1++) {
1.251     brouard  5686:                  if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  5687:                    /* iv= Tvar[Tmodelind[z1]]-ncovcol-nqv; /\* Good *\/ */
                   5688:                    iv= Tvar[Tmodelind[z1]]; /* Good *//* because cotvar starts now at first at ncovcol+nqv+ntv */ 
1.332     brouard  5689:                    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  5690:                                                                                      value is -1, we don't select. It differs from the 
                   5691:                                                                                      constant and age model which counts them. */
                   5692:                      bool=0; /* not selected */
                   5693:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
1.334     brouard  5694:                    /* i1=Tvaraff[z1]; */
                   5695:                    /* i2=TnsdVar[i1]; */
                   5696:                    /* i3=nbcode[i1][i2]; */
                   5697:                    /* i4=covar[i1][iind]; */
                   5698:                    /* if(i4 != i3){ */
                   5699:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) { /* Bug valgrind */
1.251     brouard  5700:                      bool=0;
                   5701:                    }
                   5702:                  }
                   5703:                }
                   5704:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   5705:            } /* end j==0 */
                   5706:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  5707:            if(bool==1){ /*Selected */
1.251     brouard  5708:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   5709:                 and mw[mi+1][iind]. dh depends on stepm. */
                   5710:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   5711:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   5712:              if(m >=firstpass && m <=lastpass){
                   5713:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   5714:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   5715:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   5716:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   5717:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   5718:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   5719:                if (m<lastpass) {
                   5720:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   5721:                  /*   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]); */
                   5722:                  if(s[m][iind]==-1)
                   5723:                    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.));
                   5724:                  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  5725:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
                   5726:                    if(!isnan(covar[ncovcol+z1][iind])){
1.332     brouard  5727:                      idq[z1]=idq[z1]+weight[iind];
                   5728:                      meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   5729:                      /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
                   5730:                      stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
1.311     brouard  5731:                    }
1.284     brouard  5732:                  }
1.251     brouard  5733:                  /* if((int)agev[m][iind] == 55) */
                   5734:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   5735:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   5736:                  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  5737:                }
1.251     brouard  5738:              } /* end if between passes */  
                   5739:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   5740:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   5741:                k2cpt++;
                   5742:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  5743:              }
1.251     brouard  5744:            }else{
                   5745:              bool=1;
                   5746:            }/* end bool 2 */
                   5747:          } /* end m */
1.284     brouard  5748:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   5749:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   5750:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   5751:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   5752:          /* } */
1.251     brouard  5753:        } /* end bool */
                   5754:       } /* end iind = 1 to imx */
1.319     brouard  5755:       /* prop[s][age] is fed for any initial and valid live state as well as
1.251     brouard  5756:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   5757:       
                   5758:       
                   5759:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.335     brouard  5760:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
1.265     brouard  5761:         pstamp(ficresp);
1.335     brouard  5762:       if  (cptcoveff>0 && j!=0){
1.265     brouard  5763:         pstamp(ficresp);
1.251     brouard  5764:        printf( "\n#********** Variable "); 
                   5765:        fprintf(ficresp, "\n#********** Variable "); 
                   5766:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   5767:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   5768:        fprintf(ficlog, "\n#********** Variable "); 
1.340     brouard  5769:        for (z1=1; z1<=cptcoveff; z1++){
1.251     brouard  5770:          if(!FixedV[Tvaraff[z1]]){
1.330     brouard  5771:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5772:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5773:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5774:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5775:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.250     brouard  5776:          }else{
1.330     brouard  5777:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5778:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5779:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5780:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5781:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.251     brouard  5782:          }
                   5783:        }
                   5784:        printf( "**********\n#");
                   5785:        fprintf(ficresp, "**********\n#");
                   5786:        fprintf(ficresphtm, "**********</h3>\n");
                   5787:        fprintf(ficresphtmfr, "**********</h3>\n");
                   5788:        fprintf(ficlog, "**********\n");
                   5789:       }
1.284     brouard  5790:       /*
                   5791:        Printing means of quantitative variables if any
                   5792:       */
                   5793:       for (z1=1; z1<= nqfveff; z1++) {
1.311     brouard  5794:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.312     brouard  5795:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
1.284     brouard  5796:        if(weightopt==1){
                   5797:          printf(" Weighted mean and standard deviation of");
                   5798:          fprintf(ficlog," Weighted mean and standard deviation of");
                   5799:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   5800:        }
1.311     brouard  5801:        /* mu = \frac{w x}{\sum w}
                   5802:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
                   5803:        */
                   5804:        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]));
                   5805:        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]));
                   5806:        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  5807:       }
                   5808:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   5809:       /*       for(m=1;m<=lastpass;m++){ */
                   5810:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   5811:       /*   } */
                   5812:       /* } */
1.283     brouard  5813: 
1.251     brouard  5814:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.335     brouard  5815:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
1.265     brouard  5816:         fprintf(ficresp, " Age");
1.335     brouard  5817:       if(nj==2) for (z1=1; z1<=cptcoveff; z1++) {
                   5818:          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]]);
                   5819:          fprintf(ficresp, " V%d=%d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5820:        }
1.251     brouard  5821:       for(i=1; i<=nlstate;i++) {
1.335     brouard  5822:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  5823:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   5824:       }
1.335     brouard  5825:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  5826:       fprintf(ficresphtm, "\n");
                   5827:       
                   5828:       /* Header of frequency table by age */
                   5829:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   5830:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  5831:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  5832:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5833:          if(s2!=0 && m!=0)
                   5834:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  5835:        }
1.226     brouard  5836:       }
1.251     brouard  5837:       fprintf(ficresphtmfr, "\n");
                   5838:     
                   5839:       /* For each age */
                   5840:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   5841:        fprintf(ficresphtm,"<tr>");
                   5842:        if(iage==iagemax+1){
                   5843:          fprintf(ficlog,"1");
                   5844:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   5845:        }else if(iage==iagemax+2){
                   5846:          fprintf(ficlog,"0");
                   5847:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   5848:        }else if(iage==iagemax+3){
                   5849:          fprintf(ficlog,"Total");
                   5850:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   5851:        }else{
1.240     brouard  5852:          if(first==1){
1.251     brouard  5853:            first=0;
                   5854:            printf("See log file for details...\n");
                   5855:          }
                   5856:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   5857:          fprintf(ficlog,"Age %d", iage);
                   5858:        }
1.265     brouard  5859:        for(s1=1; s1 <=nlstate ; s1++){
                   5860:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   5861:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  5862:        }
1.265     brouard  5863:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5864:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  5865:            pos += freq[s1][m][iage];
                   5866:          if(pp[s1]>=1.e-10){
1.251     brouard  5867:            if(first==1){
1.265     brouard  5868:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5869:            }
1.265     brouard  5870:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5871:          }else{
                   5872:            if(first==1)
1.265     brouard  5873:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   5874:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  5875:          }
                   5876:        }
                   5877:       
1.265     brouard  5878:        for(s1=1; s1 <=nlstate ; s1++){ 
                   5879:          /* posprop[s1]=0; */
                   5880:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   5881:            pp[s1] += freq[s1][m][iage];
                   5882:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   5883:       
                   5884:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   5885:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   5886:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5887:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5888:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5889:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5890:        }
                   5891:        
                   5892:        /* Writing ficresp */
1.335     brouard  5893:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5894:           if( iage <= iagemax){
                   5895:            fprintf(ficresp," %d",iage);
                   5896:           }
                   5897:         }else if( nj==2){
                   5898:           if( iage <= iagemax){
                   5899:            fprintf(ficresp," %d",iage);
1.335     brouard  5900:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.265     brouard  5901:           }
1.240     brouard  5902:        }
1.265     brouard  5903:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  5904:          if(pos>=1.e-5){
1.251     brouard  5905:            if(first==1)
1.265     brouard  5906:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   5907:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  5908:          }else{
                   5909:            if(first==1)
1.265     brouard  5910:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   5911:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  5912:          }
                   5913:          if( iage <= iagemax){
                   5914:            if(pos>=1.e-5){
1.335     brouard  5915:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5916:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5917:               }else if( nj==2){
                   5918:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5919:               }
                   5920:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5921:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   5922:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   5923:            } else{
1.335     brouard  5924:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
1.265     brouard  5925:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  5926:            }
1.240     brouard  5927:          }
1.265     brouard  5928:          pospropt[s1] +=posprop[s1];
                   5929:        } /* end loop s1 */
1.251     brouard  5930:        /* pospropt=0.; */
1.265     brouard  5931:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  5932:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5933:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  5934:              if(first==1){
1.265     brouard  5935:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5936:              }
1.265     brouard  5937:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   5938:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5939:            }
1.265     brouard  5940:            if(s1!=0 && m!=0)
                   5941:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  5942:          }
1.265     brouard  5943:        } /* end loop s1 */
1.251     brouard  5944:        posproptt=0.; 
1.265     brouard  5945:        for(s1=1; s1 <=nlstate; s1++){
                   5946:          posproptt += pospropt[s1];
1.251     brouard  5947:        }
                   5948:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  5949:        fprintf(ficresphtm,"</tr>\n");
1.335     brouard  5950:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
1.265     brouard  5951:          if(iage <= iagemax)
                   5952:            fprintf(ficresp,"\n");
1.240     brouard  5953:        }
1.251     brouard  5954:        if(first==1)
                   5955:          printf("Others in log...\n");
                   5956:        fprintf(ficlog,"\n");
                   5957:       } /* end loop age iage */
1.265     brouard  5958:       
1.251     brouard  5959:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  5960:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5961:        if(posproptt < 1.e-5){
1.265     brouard  5962:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  5963:        }else{
1.265     brouard  5964:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  5965:        }
1.226     brouard  5966:       }
1.251     brouard  5967:       fprintf(ficresphtm,"</tr>\n");
                   5968:       fprintf(ficresphtm,"</table>\n");
                   5969:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  5970:       if(posproptt < 1.e-5){
1.251     brouard  5971:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   5972:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  5973:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   5974:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  5975:        invalidvarcomb[j1]=1;
1.226     brouard  5976:       }else{
1.338     brouard  5977:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced (or no resultline).</p>",j1);
1.251     brouard  5978:        invalidvarcomb[j1]=0;
1.226     brouard  5979:       }
1.251     brouard  5980:       fprintf(ficresphtmfr,"</table>\n");
                   5981:       fprintf(ficlog,"\n");
                   5982:       if(j!=0){
                   5983:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  5984:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5985:          for(k=1; k <=(nlstate+ndeath); k++){
                   5986:            if (k != i) {
1.265     brouard  5987:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  5988:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  5989:                  if(j1==1){ /* All dummy covariates to zero */
                   5990:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   5991:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  5992:                    printf("%d%d ",i,k);
                   5993:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5994:                    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]));
                   5995:                    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]));
                   5996:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  5997:                  }
1.253     brouard  5998:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   5999:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   6000:                    x[iage]= (double)iage;
                   6001:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  6002:                    /* 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  6003:                  }
1.268     brouard  6004:                  /* Some are not finite, but linreg will ignore these ages */
                   6005:                  no=0;
1.253     brouard  6006:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  6007:                  pstart[s1]=b;
                   6008:                  pstart[s1-1]=a;
1.252     brouard  6009:                }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 */ 
                   6010:                  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]);
                   6011:                  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  6012:                  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  6013:                  printf("%d%d ",i,k);
                   6014:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  6015:                  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  6016:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   6017:                  ;
                   6018:                }
                   6019:                /* printf("%12.7f )", param[i][jj][k]); */
                   6020:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  6021:                s1++; 
1.251     brouard  6022:              } /* end jj */
                   6023:            } /* end k!= i */
                   6024:          } /* end k */
1.265     brouard  6025:        } /* end i, s1 */
1.251     brouard  6026:       } /* end j !=0 */
                   6027:     } /* end selected combination of covariate j1 */
                   6028:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   6029:       printf("#Freqsummary: Starting values for the constants:\n");
                   6030:       fprintf(ficlog,"\n");
1.265     brouard  6031:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  6032:        for(k=1; k <=(nlstate+ndeath); k++){
                   6033:          if (k != i) {
                   6034:            printf("%d%d ",i,k);
                   6035:            fprintf(ficlog,"%d%d ",i,k);
                   6036:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  6037:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  6038:              if(jj==1){ /* Age has to be done */
1.265     brouard  6039:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   6040:                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]));
                   6041:                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  6042:              }
                   6043:              /* printf("%12.7f )", param[i][jj][k]); */
                   6044:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  6045:              s1++; 
1.250     brouard  6046:            }
1.251     brouard  6047:            printf("\n");
                   6048:            fprintf(ficlog,"\n");
1.250     brouard  6049:          }
                   6050:        }
1.284     brouard  6051:       } /* end of state i */
1.251     brouard  6052:       printf("#Freqsummary\n");
                   6053:       fprintf(ficlog,"\n");
1.265     brouard  6054:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   6055:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   6056:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   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]);
                   6059:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   6060:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   6061:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  6062:          /* } */
                   6063:        }
1.265     brouard  6064:       } /* end loop s1 */
1.251     brouard  6065:       
                   6066:       printf("\n");
                   6067:       fprintf(ficlog,"\n");
                   6068:     } /* end j=0 */
1.249     brouard  6069:   } /* end j */
1.252     brouard  6070: 
1.253     brouard  6071:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  6072:     for(i=1, jk=1; i <=nlstate; i++){
                   6073:       for(j=1; j <=nlstate+ndeath; j++){
                   6074:        if(j!=i){
                   6075:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   6076:          printf("%1d%1d",i,j);
                   6077:          fprintf(ficparo,"%1d%1d",i,j);
                   6078:          for(k=1; k<=ncovmodel;k++){
                   6079:            /*    printf(" %lf",param[i][j][k]); */
                   6080:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   6081:            p[jk]=pstart[jk];
                   6082:            printf(" %f ",pstart[jk]);
                   6083:            fprintf(ficparo," %f ",pstart[jk]);
                   6084:            jk++;
                   6085:          }
                   6086:          printf("\n");
                   6087:          fprintf(ficparo,"\n");
                   6088:        }
                   6089:       }
                   6090:     }
                   6091:   } /* end mle=-2 */
1.226     brouard  6092:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  6093:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  6094:   
1.226     brouard  6095:   fclose(ficresp);
                   6096:   fclose(ficresphtm);
                   6097:   fclose(ficresphtmfr);
1.283     brouard  6098:   free_vector(idq,1,nqfveff);
1.226     brouard  6099:   free_vector(meanq,1,nqfveff);
1.284     brouard  6100:   free_vector(stdq,1,nqfveff);
1.226     brouard  6101:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  6102:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   6103:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  6104:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  6105:   free_vector(pospropt,1,nlstate);
                   6106:   free_vector(posprop,1,nlstate);
1.251     brouard  6107:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  6108:   free_vector(pp,1,nlstate);
                   6109:   /* End of freqsummary */
                   6110: }
1.126     brouard  6111: 
1.268     brouard  6112: /* Simple linear regression */
                   6113: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   6114: 
                   6115:   /* y=a+bx regression */
                   6116:   double   sumx = 0.0;                        /* sum of x                      */
                   6117:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   6118:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   6119:   double   sumy = 0.0;                        /* sum of y                      */
                   6120:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   6121:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   6122:   double yhat;
                   6123:   
                   6124:   double denom=0;
                   6125:   int i;
                   6126:   int ne=*no;
                   6127:   
                   6128:   for ( i=ifi, ne=0;i<=ila;i++) {
                   6129:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   6130:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   6131:       continue;
                   6132:     }
                   6133:     ne=ne+1;
                   6134:     sumx  += x[i];       
                   6135:     sumx2 += x[i]*x[i];  
                   6136:     sumxy += x[i] * y[i];
                   6137:     sumy  += y[i];      
                   6138:     sumy2 += y[i]*y[i]; 
                   6139:     denom = (ne * sumx2 - sumx*sumx);
                   6140:     /* 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); */
                   6141:   } 
                   6142:   
                   6143:   denom = (ne * sumx2 - sumx*sumx);
                   6144:   if (denom == 0) {
                   6145:     // vertical, slope m is infinity
                   6146:     *b = INFINITY;
                   6147:     *a = 0;
                   6148:     if (r) *r = 0;
                   6149:     return 1;
                   6150:   }
                   6151:   
                   6152:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   6153:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   6154:   if (r!=NULL) {
                   6155:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   6156:       sqrt((sumx2 - sumx*sumx/ne) *
                   6157:           (sumy2 - sumy*sumy/ne));
                   6158:   }
                   6159:   *no=ne;
                   6160:   for ( i=ifi, ne=0;i<=ila;i++) {
                   6161:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   6162:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   6163:       continue;
                   6164:     }
                   6165:     ne=ne+1;
                   6166:     yhat = y[i] - *a -*b* x[i];
                   6167:     sume2  += yhat * yhat ;       
                   6168:     
                   6169:     denom = (ne * sumx2 - sumx*sumx);
                   6170:     /* 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); */
                   6171:   } 
                   6172:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   6173:   *sa= *sb * sqrt(sumx2/ne);
                   6174:   
                   6175:   return 0; 
                   6176: }
                   6177: 
1.126     brouard  6178: /************ Prevalence ********************/
1.227     brouard  6179: 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)
                   6180: {  
                   6181:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   6182:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   6183:      We still use firstpass and lastpass as another selection.
                   6184:   */
1.126     brouard  6185:  
1.227     brouard  6186:   int i, m, jk, j1, bool, z1,j, iv;
                   6187:   int mi; /* Effective wave */
                   6188:   int iage;
                   6189:   double agebegin, ageend;
                   6190: 
                   6191:   double **prop;
                   6192:   double posprop; 
                   6193:   double  y2; /* in fractional years */
                   6194:   int iagemin, iagemax;
                   6195:   int first; /** to stop verbosity which is redirected to log file */
                   6196: 
                   6197:   iagemin= (int) agemin;
                   6198:   iagemax= (int) agemax;
                   6199:   /*pp=vector(1,nlstate);*/
1.251     brouard  6200:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  6201:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   6202:   j1=0;
1.222     brouard  6203:   
1.227     brouard  6204:   /*j=cptcoveff;*/
                   6205:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  6206:   
1.288     brouard  6207:   first=0;
1.335     brouard  6208:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of simple dummy covariates */
1.227     brouard  6209:     for (i=1; i<=nlstate; i++)  
1.251     brouard  6210:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  6211:        prop[i][iage]=0.0;
                   6212:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   6213:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   6214:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   6215:     
                   6216:     for (i=1; i<=imx; i++) { /* Each individual */
                   6217:       bool=1;
                   6218:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   6219:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   6220:        m=mw[mi][i];
                   6221:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   6222:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   6223:        for (z1=1; z1<=cptcoveff; z1++){
                   6224:          if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  6225:            iv= Tvar[Tmodelind[z1]];/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
1.332     brouard  6226:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality */
1.227     brouard  6227:              bool=0;
                   6228:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
1.332     brouard  6229:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) {
1.227     brouard  6230:              bool=0;
                   6231:            }
                   6232:        }
                   6233:        if(bool==1){ /* Otherwise we skip that wave/person */
                   6234:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   6235:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   6236:          if(m >=firstpass && m <=lastpass){
                   6237:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   6238:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   6239:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   6240:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  6241:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  6242:                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); 
                   6243:                exit(1);
                   6244:              }
                   6245:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   6246:                /*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]]);*/
                   6247:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   6248:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   6249:              } /* end valid statuses */ 
                   6250:            } /* end selection of dates */
                   6251:          } /* end selection of waves */
                   6252:        } /* end bool */
                   6253:       } /* end wave */
                   6254:     } /* end individual */
                   6255:     for(i=iagemin; i <= iagemax+3; i++){  
                   6256:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   6257:        posprop += prop[jk][i]; 
                   6258:       } 
                   6259:       
                   6260:       for(jk=1; jk <=nlstate ; jk++){      
                   6261:        if( i <=  iagemax){ 
                   6262:          if(posprop>=1.e-5){ 
                   6263:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   6264:          } else{
1.288     brouard  6265:            if(!first){
                   6266:              first=1;
1.266     brouard  6267:              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]);
                   6268:            }else{
1.288     brouard  6269:              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  6270:            }
                   6271:          }
                   6272:        } 
                   6273:       }/* end jk */ 
                   6274:     }/* end i */ 
1.222     brouard  6275:      /*} *//* end i1 */
1.227     brouard  6276:   } /* end j1 */
1.222     brouard  6277:   
1.227     brouard  6278:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   6279:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  6280:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  6281: }  /* End of prevalence */
1.126     brouard  6282: 
                   6283: /************* Waves Concatenation ***************/
                   6284: 
                   6285: 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)
                   6286: {
1.298     brouard  6287:   /* 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  6288:      Death is a valid wave (if date is known).
                   6289:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   6290:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  6291:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  6292:   */
1.126     brouard  6293: 
1.224     brouard  6294:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  6295:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   6296:      double sum=0., jmean=0.;*/
1.224     brouard  6297:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  6298:   int j, k=0,jk, ju, jl;
                   6299:   double sum=0.;
                   6300:   first=0;
1.214     brouard  6301:   firstwo=0;
1.217     brouard  6302:   firsthree=0;
1.218     brouard  6303:   firstfour=0;
1.164     brouard  6304:   jmin=100000;
1.126     brouard  6305:   jmax=-1;
                   6306:   jmean=0.;
1.224     brouard  6307: 
                   6308: /* Treating live states */
1.214     brouard  6309:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  6310:     mi=0;  /* First valid wave */
1.227     brouard  6311:     mli=0; /* Last valid wave */
1.309     brouard  6312:     m=firstpass;  /* Loop on waves */
                   6313:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
1.227     brouard  6314:       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 */
                   6315:        mli=m-1;/* mw[++mi][i]=m-1; */
                   6316:       }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  6317:        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  6318:        mli=m;
1.224     brouard  6319:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   6320:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  6321:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  6322:       }
1.309     brouard  6323:       else{ /* m = lastpass, eventual special issue with warning */
1.224     brouard  6324: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  6325:        break;
1.224     brouard  6326: #else
1.317     brouard  6327:        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  6328:          if(firsthree == 0){
1.302     brouard  6329:            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  6330:            firsthree=1;
1.317     brouard  6331:          }else if(firsthree >=1 && firsthree < 10){
                   6332:            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);
                   6333:            firsthree++;
                   6334:          }else if(firsthree == 10){
                   6335:            printf("Information, too many Information flags: no more reported to log either\n");
                   6336:            fprintf(ficlog,"Information, too many Information flags: no more reported to log either\n");
                   6337:            firsthree++;
                   6338:          }else{
                   6339:            firsthree++;
1.227     brouard  6340:          }
1.309     brouard  6341:          mw[++mi][i]=m; /* Valid transition with unknown status */
1.227     brouard  6342:          mli=m;
                   6343:        }
                   6344:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   6345:          nbwarn++;
1.309     brouard  6346:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
1.227     brouard  6347:            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);
                   6348:            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);
                   6349:          }
                   6350:          break;
                   6351:        }
                   6352:        break;
1.224     brouard  6353: #endif
1.227     brouard  6354:       }/* End m >= lastpass */
1.126     brouard  6355:     }/* end while */
1.224     brouard  6356: 
1.227     brouard  6357:     /* 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  6358:     /* After last pass */
1.224     brouard  6359: /* Treating death states */
1.214     brouard  6360:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  6361:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   6362:       /* } */
1.126     brouard  6363:       mi++;    /* Death is another wave */
                   6364:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  6365:       /* Only death is a correct wave */
1.126     brouard  6366:       mw[mi][i]=m;
1.257     brouard  6367:     } /* else not in a death state */
1.224     brouard  6368: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  6369:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  6370:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.309     brouard  6371:        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  6372:          nbwarn++;
                   6373:          if(firstfiv==0){
1.309     brouard  6374:            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  6375:            firstfiv=1;
                   6376:          }else{
1.309     brouard  6377:            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  6378:          }
1.309     brouard  6379:            s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
                   6380:        }else{ /* Month of Death occured afer last wave month, potential bias */
1.227     brouard  6381:          nberr++;
                   6382:          if(firstwo==0){
1.309     brouard  6383:            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  6384:            firstwo=1;
                   6385:          }
1.309     brouard  6386:          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  6387:        }
1.257     brouard  6388:       }else{ /* if date of interview is unknown */
1.227     brouard  6389:        /* death is known but not confirmed by death status at any wave */
                   6390:        if(firstfour==0){
1.309     brouard  6391:          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  6392:          firstfour=1;
                   6393:        }
1.309     brouard  6394:        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  6395:       }
1.224     brouard  6396:     } /* end if date of death is known */
                   6397: #endif
1.309     brouard  6398:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
                   6399:     /* wav[i]=mw[mi][i];   */
1.126     brouard  6400:     if(mi==0){
                   6401:       nbwarn++;
                   6402:       if(first==0){
1.227     brouard  6403:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   6404:        first=1;
1.126     brouard  6405:       }
                   6406:       if(first==1){
1.227     brouard  6407:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  6408:       }
                   6409:     } /* end mi==0 */
                   6410:   } /* End individuals */
1.214     brouard  6411:   /* wav and mw are no more changed */
1.223     brouard  6412:        
1.317     brouard  6413:   printf("Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   6414:   fprintf(ficlog,"Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   6415: 
                   6416: 
1.126     brouard  6417:   for(i=1; i<=imx; i++){
                   6418:     for(mi=1; mi<wav[i];mi++){
                   6419:       if (stepm <=0)
1.227     brouard  6420:        dh[mi][i]=1;
1.126     brouard  6421:       else{
1.260     brouard  6422:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  6423:          if (agedc[i] < 2*AGESUP) {
                   6424:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   6425:            if(j==0) j=1;  /* Survives at least one month after exam */
                   6426:            else if(j<0){
                   6427:              nberr++;
                   6428:              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]);
                   6429:              j=1; /* Temporary Dangerous patch */
                   6430:              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);
                   6431:              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]);
                   6432:              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);
                   6433:            }
                   6434:            k=k+1;
                   6435:            if (j >= jmax){
                   6436:              jmax=j;
                   6437:              ijmax=i;
                   6438:            }
                   6439:            if (j <= jmin){
                   6440:              jmin=j;
                   6441:              ijmin=i;
                   6442:            }
                   6443:            sum=sum+j;
                   6444:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   6445:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   6446:          }
                   6447:        }
                   6448:        else{
                   6449:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  6450: /*       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  6451:                                        
1.227     brouard  6452:          k=k+1;
                   6453:          if (j >= jmax) {
                   6454:            jmax=j;
                   6455:            ijmax=i;
                   6456:          }
                   6457:          else if (j <= jmin){
                   6458:            jmin=j;
                   6459:            ijmin=i;
                   6460:          }
                   6461:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   6462:          /*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]);*/
                   6463:          if(j<0){
                   6464:            nberr++;
                   6465:            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]);
                   6466:            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]);
                   6467:          }
                   6468:          sum=sum+j;
                   6469:        }
                   6470:        jk= j/stepm;
                   6471:        jl= j -jk*stepm;
                   6472:        ju= j -(jk+1)*stepm;
                   6473:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   6474:          if(jl==0){
                   6475:            dh[mi][i]=jk;
                   6476:            bh[mi][i]=0;
                   6477:          }else{ /* We want a negative bias in order to only have interpolation ie
                   6478:                  * to avoid the price of an extra matrix product in likelihood */
                   6479:            dh[mi][i]=jk+1;
                   6480:            bh[mi][i]=ju;
                   6481:          }
                   6482:        }else{
                   6483:          if(jl <= -ju){
                   6484:            dh[mi][i]=jk;
                   6485:            bh[mi][i]=jl;       /* bias is positive if real duration
                   6486:                                 * is higher than the multiple of stepm and negative otherwise.
                   6487:                                 */
                   6488:          }
                   6489:          else{
                   6490:            dh[mi][i]=jk+1;
                   6491:            bh[mi][i]=ju;
                   6492:          }
                   6493:          if(dh[mi][i]==0){
                   6494:            dh[mi][i]=1; /* At least one step */
                   6495:            bh[mi][i]=ju; /* At least one step */
                   6496:            /*  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);*/
                   6497:          }
                   6498:        } /* end if mle */
1.126     brouard  6499:       }
                   6500:     } /* end wave */
                   6501:   }
                   6502:   jmean=sum/k;
                   6503:   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  6504:   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  6505: }
1.126     brouard  6506: 
                   6507: /*********** Tricode ****************************/
1.220     brouard  6508:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  6509:  {
                   6510:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   6511:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   6512:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   6513:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   6514:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   6515:     */
1.130     brouard  6516: 
1.242     brouard  6517:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   6518:    int modmaxcovj=0; /* Modality max of covariates j */
                   6519:    int cptcode=0; /* Modality max of covariates j */
                   6520:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  6521: 
                   6522: 
1.242     brouard  6523:    /* cptcoveff=0;  */
                   6524:    /* *cptcov=0; */
1.126     brouard  6525:  
1.242     brouard  6526:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  6527:    for (k=1; k <= maxncov; k++)
                   6528:      for(j=1; j<=2; j++)
                   6529:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  6530: 
1.242     brouard  6531:    /* Loop on covariates without age and products and no quantitative variable */
1.335     brouard  6532:    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  6533:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
1.343     brouard  6534:      /* printf("Testing k=%d, cptcovt=%d\n",k, cptcovt); */
1.349     brouard  6535:      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  6536:        switch(Fixed[k]) {
                   6537:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.311     brouard  6538:         modmaxcovj=0;
                   6539:         modmincovj=0;
1.242     brouard  6540:         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  6541:           /* 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  6542:           ij=(int)(covar[Tvar[k]][i]);
                   6543:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   6544:            * If product of Vn*Vm, still boolean *:
                   6545:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   6546:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   6547:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   6548:              modality of the nth covariate of individual i. */
                   6549:           if (ij > modmaxcovj)
                   6550:             modmaxcovj=ij; 
                   6551:           else if (ij < modmincovj) 
                   6552:             modmincovj=ij; 
1.287     brouard  6553:           if (ij <0 || ij >1 ){
1.311     brouard  6554:             printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6555:             fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6556:             fflush(ficlog);
                   6557:             exit(1);
1.287     brouard  6558:           }
                   6559:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  6560:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   6561:             exit(1);
                   6562:           }else
                   6563:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   6564:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   6565:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   6566:           /* getting the maximum value of the modality of the covariate
                   6567:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   6568:              female ies 1, then modmaxcovj=1.
                   6569:           */
                   6570:         } /* end for loop on individuals i */
                   6571:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6572:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6573:         cptcode=modmaxcovj;
                   6574:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   6575:         /*for (i=0; i<=cptcode; i++) {*/
                   6576:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   6577:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6578:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6579:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   6580:             if( j != -1){
                   6581:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   6582:                                  covariate for which somebody answered excluding 
                   6583:                                  undefined. Usually 2: 0 and 1. */
                   6584:             }
                   6585:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   6586:                                     covariate for which somebody answered including 
                   6587:                                     undefined. Usually 3: -1, 0 and 1. */
                   6588:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   6589:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   6590:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  6591:                        
1.242     brouard  6592:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   6593:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   6594:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   6595:         /* modmincovj=3; modmaxcovj = 7; */
                   6596:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   6597:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   6598:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   6599:         /* nbcode[Tvar[j]][ij]=k; */
                   6600:         /* nbcode[Tvar[j]][1]=0; */
                   6601:         /* nbcode[Tvar[j]][2]=1; */
                   6602:         /* nbcode[Tvar[j]][3]=2; */
                   6603:         /* To be continued (not working yet). */
                   6604:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  6605: 
                   6606:         /* 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*/
                   6607:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   6608:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   6609:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   6610:         /*, could be restored in the future */
                   6611:         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  6612:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   6613:             break;
                   6614:           }
                   6615:           ij++;
1.287     brouard  6616:           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  6617:           cptcode = ij; /* New max modality for covar j */
                   6618:         } /* end of loop on modality i=-1 to 1 or more */
                   6619:         break;
                   6620:        case 1: /* Testing on varying covariate, could be simple and
                   6621:                * should look at waves or product of fixed *
                   6622:                * varying. No time to test -1, assuming 0 and 1 only */
                   6623:         ij=0;
                   6624:         for(i=0; i<=1;i++){
                   6625:           nbcode[Tvar[k]][++ij]=i;
                   6626:         }
                   6627:         break;
                   6628:        default:
                   6629:         break;
                   6630:        } /* end switch */
                   6631:      } /* end dummy test */
1.349     brouard  6632:      if(Dummy[k]==1 && Typevar[k] !=1 && Typevar[k] !=3 && Fixed ==0){ /* Fixed Quantitative covariate and not age product */ 
1.311     brouard  6633:        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  6634:         if(Tvar[k]<=0 || Tvar[k]>=NCOVMAX){
                   6635:           printf("Error k=%d \n",k);
                   6636:           exit(1);
                   6637:         }
1.311     brouard  6638:         if(isnan(covar[Tvar[k]][i])){
                   6639:           printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6640:           fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6641:           fflush(ficlog);
                   6642:           exit(1);
                   6643:          }
                   6644:        }
1.335     brouard  6645:      } /* end Quanti */
1.287     brouard  6646:    } /* 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  6647:   
                   6648:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   6649:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   6650:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   6651:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   6652:      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 */ 
                   6653:      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 */
                   6654:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   6655:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   6656:   
                   6657:    ij=0;
                   6658:    /* 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  6659:    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 */
                   6660:      /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
1.242     brouard  6661:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   6662:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
1.335     brouard  6663:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy simple and non empty in the model */
                   6664:        /* Typevar[k] =0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for product */
                   6665:        /* 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  6666:        /* If product not in single variable we don't print results */
                   6667:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
1.335     brouard  6668:        ++ij;/*    V5 + V4 + V3 + V4*V3 + V5*age + V2 +  V1*V2 + V1*age + V1, *//* V5 quanti, V2 quanti, V4, V3, V1 dummies */
                   6669:        /* k=       1    2   3     4       5       6      7       8        9  */
                   6670:        /* Tvar[k]= 5    4    3    6       5       2      7       1        1  */
                   6671:        /* ij            1    2                                            3  */  
                   6672:        /* Tvaraff[ij]=  4    3                                            1  */
                   6673:        /* Tmodelind[ij]=2    3                                            9  */
                   6674:        /* TmodelInvind[ij]=2 1                                            1  */
1.242     brouard  6675:        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*/
                   6676:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   6677:        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 */
                   6678:        if(Fixed[k]!=0)
                   6679:         anyvaryingduminmodel=1;
                   6680:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   6681:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6682:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   6683:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   6684:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   6685:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6686:      } 
                   6687:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   6688:    /* ij--; */
                   6689:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
1.335     brouard  6690:    *cptcov=ij; /* cptcov= Number of total real effective simple dummies (fixed or time  arying) effective (used as cptcoveff in other functions)
1.242     brouard  6691:                * because they can be excluded from the model and real
                   6692:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   6693:    for(j=ij+1; j<= cptcovt; j++){
                   6694:      Tvaraff[j]=0;
                   6695:      Tmodelind[j]=0;
                   6696:    }
                   6697:    for(j=ntveff+1; j<= cptcovt; j++){
                   6698:      TmodelInvind[j]=0;
                   6699:    }
                   6700:    /* To be sorted */
                   6701:    ;
                   6702:  }
1.126     brouard  6703: 
1.145     brouard  6704: 
1.126     brouard  6705: /*********** Health Expectancies ****************/
                   6706: 
1.235     brouard  6707:  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  6708: 
                   6709: {
                   6710:   /* Health expectancies, no variances */
1.329     brouard  6711:   /* cij is the combination in the list of combination of dummy covariates */
                   6712:   /* strstart is a string of time at start of computing */
1.164     brouard  6713:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  6714:   int nhstepma, nstepma; /* Decreasing with age */
                   6715:   double age, agelim, hf;
                   6716:   double ***p3mat;
                   6717:   double eip;
                   6718: 
1.238     brouard  6719:   /* pstamp(ficreseij); */
1.126     brouard  6720:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   6721:   fprintf(ficreseij,"# Age");
                   6722:   for(i=1; i<=nlstate;i++){
                   6723:     for(j=1; j<=nlstate;j++){
                   6724:       fprintf(ficreseij," e%1d%1d ",i,j);
                   6725:     }
                   6726:     fprintf(ficreseij," e%1d. ",i);
                   6727:   }
                   6728:   fprintf(ficreseij,"\n");
                   6729: 
                   6730:   
                   6731:   if(estepm < stepm){
                   6732:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6733:   }
                   6734:   else  hstepm=estepm;   
                   6735:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6736:    * This is mainly to measure the difference between two models: for example
                   6737:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6738:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6739:    * progression in between and thus overestimating or underestimating according
                   6740:    * to the curvature of the survival function. If, for the same date, we 
                   6741:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6742:    * to compare the new estimate of Life expectancy with the same linear 
                   6743:    * hypothesis. A more precise result, taking into account a more precise
                   6744:    * curvature will be obtained if estepm is as small as stepm. */
                   6745: 
                   6746:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6747:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6748:      nhstepm is the number of hstepm from age to agelim 
                   6749:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  6750:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  6751:      and note for a fixed period like estepm months */
                   6752:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6753:      survival function given by stepm (the optimization length). Unfortunately it
                   6754:      means that if the survival funtion is printed only each two years of age and if
                   6755:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6756:      results. So we changed our mind and took the option of the best precision.
                   6757:   */
                   6758:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6759: 
                   6760:   agelim=AGESUP;
                   6761:   /* If stepm=6 months */
                   6762:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   6763:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   6764:     
                   6765: /* nhstepm age range expressed in number of stepm */
                   6766:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6767:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6768:   /* if (stepm >= YEARM) hstepm=1;*/
                   6769:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6770:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6771: 
                   6772:   for (age=bage; age<=fage; age ++){ 
                   6773:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6774:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6775:     /* if (stepm >= YEARM) hstepm=1;*/
                   6776:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   6777: 
                   6778:     /* If stepm=6 months */
                   6779:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6780:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
1.330     brouard  6781:     /* 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  6782:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  6783:     
                   6784:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6785:     
                   6786:     printf("%d|",(int)age);fflush(stdout);
                   6787:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6788:     
                   6789:     /* Computing expectancies */
                   6790:     for(i=1; i<=nlstate;i++)
                   6791:       for(j=1; j<=nlstate;j++)
                   6792:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6793:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   6794:          
                   6795:          /* 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]);*/
                   6796: 
                   6797:        }
                   6798: 
                   6799:     fprintf(ficreseij,"%3.0f",age );
                   6800:     for(i=1; i<=nlstate;i++){
                   6801:       eip=0;
                   6802:       for(j=1; j<=nlstate;j++){
                   6803:        eip +=eij[i][j][(int)age];
                   6804:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   6805:       }
                   6806:       fprintf(ficreseij,"%9.4f", eip );
                   6807:     }
                   6808:     fprintf(ficreseij,"\n");
                   6809:     
                   6810:   }
                   6811:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6812:   printf("\n");
                   6813:   fprintf(ficlog,"\n");
                   6814:   
                   6815: }
                   6816: 
1.235     brouard  6817:  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  6818: 
                   6819: {
                   6820:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  6821:      to initial status i, ei. .
1.126     brouard  6822:   */
1.336     brouard  6823:   /* Very time consuming function, but already optimized with precov */
1.126     brouard  6824:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   6825:   int nhstepma, nstepma; /* Decreasing with age */
                   6826:   double age, agelim, hf;
                   6827:   double ***p3matp, ***p3matm, ***varhe;
                   6828:   double **dnewm,**doldm;
                   6829:   double *xp, *xm;
                   6830:   double **gp, **gm;
                   6831:   double ***gradg, ***trgradg;
                   6832:   int theta;
                   6833: 
                   6834:   double eip, vip;
                   6835: 
                   6836:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   6837:   xp=vector(1,npar);
                   6838:   xm=vector(1,npar);
                   6839:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   6840:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   6841:   
                   6842:   pstamp(ficresstdeij);
                   6843:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   6844:   fprintf(ficresstdeij,"# Age");
                   6845:   for(i=1; i<=nlstate;i++){
                   6846:     for(j=1; j<=nlstate;j++)
                   6847:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   6848:     fprintf(ficresstdeij," e%1d. ",i);
                   6849:   }
                   6850:   fprintf(ficresstdeij,"\n");
                   6851: 
                   6852:   pstamp(ficrescveij);
                   6853:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   6854:   fprintf(ficrescveij,"# Age");
                   6855:   for(i=1; i<=nlstate;i++)
                   6856:     for(j=1; j<=nlstate;j++){
                   6857:       cptj= (j-1)*nlstate+i;
                   6858:       for(i2=1; i2<=nlstate;i2++)
                   6859:        for(j2=1; j2<=nlstate;j2++){
                   6860:          cptj2= (j2-1)*nlstate+i2;
                   6861:          if(cptj2 <= cptj)
                   6862:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   6863:        }
                   6864:     }
                   6865:   fprintf(ficrescveij,"\n");
                   6866:   
                   6867:   if(estepm < stepm){
                   6868:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6869:   }
                   6870:   else  hstepm=estepm;   
                   6871:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6872:    * This is mainly to measure the difference between two models: for example
                   6873:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6874:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6875:    * progression in between and thus overestimating or underestimating according
                   6876:    * to the curvature of the survival function. If, for the same date, we 
                   6877:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6878:    * to compare the new estimate of Life expectancy with the same linear 
                   6879:    * hypothesis. A more precise result, taking into account a more precise
                   6880:    * curvature will be obtained if estepm is as small as stepm. */
                   6881: 
                   6882:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6883:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6884:      nhstepm is the number of hstepm from age to agelim 
                   6885:      nstepm is the number of stepm from age to agelin. 
                   6886:      Look at hpijx to understand the reason of that which relies in memory size
                   6887:      and note for a fixed period like estepm months */
                   6888:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6889:      survival function given by stepm (the optimization length). Unfortunately it
                   6890:      means that if the survival funtion is printed only each two years of age and if
                   6891:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6892:      results. So we changed our mind and took the option of the best precision.
                   6893:   */
                   6894:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6895: 
                   6896:   /* If stepm=6 months */
                   6897:   /* nhstepm age range expressed in number of stepm */
                   6898:   agelim=AGESUP;
                   6899:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   6900:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6901:   /* if (stepm >= YEARM) hstepm=1;*/
                   6902:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6903:   
                   6904:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6905:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6906:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   6907:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   6908:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   6909:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   6910: 
                   6911:   for (age=bage; age<=fage; age ++){ 
                   6912:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6913:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6914:     /* if (stepm >= YEARM) hstepm=1;*/
                   6915:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  6916:                
1.126     brouard  6917:     /* If stepm=6 months */
                   6918:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6919:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   6920:     
                   6921:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  6922:                
1.126     brouard  6923:     /* Computing  Variances of health expectancies */
                   6924:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   6925:        decrease memory allocation */
                   6926:     for(theta=1; theta <=npar; theta++){
                   6927:       for(i=1; i<=npar; i++){ 
1.222     brouard  6928:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6929:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  6930:       }
1.235     brouard  6931:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   6932:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  6933:                        
1.126     brouard  6934:       for(j=1; j<= nlstate; j++){
1.222     brouard  6935:        for(i=1; i<=nlstate; i++){
                   6936:          for(h=0; h<=nhstepm-1; h++){
                   6937:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   6938:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   6939:          }
                   6940:        }
1.126     brouard  6941:       }
1.218     brouard  6942:                        
1.126     brouard  6943:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  6944:        for(h=0; h<=nhstepm-1; h++){
                   6945:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   6946:        }
1.126     brouard  6947:     }/* End theta */
                   6948:     
                   6949:     
                   6950:     for(h=0; h<=nhstepm-1; h++)
                   6951:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  6952:        for(theta=1; theta <=npar; theta++)
                   6953:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  6954:     
1.218     brouard  6955:                
1.222     brouard  6956:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  6957:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  6958:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  6959:                
1.222     brouard  6960:     printf("%d|",(int)age);fflush(stdout);
                   6961:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6962:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  6963:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  6964:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   6965:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   6966:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   6967:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   6968:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  6969:       }
                   6970:     }
1.320     brouard  6971:     /* if((int)age ==50){ */
                   6972:     /*   printf(" age=%d cij=%d nres=%d varhe[%d][%d]=%f ",(int)age, cij, nres, 1,2,varhe[1][2]); */
                   6973:     /* } */
1.126     brouard  6974:     /* Computing expectancies */
1.235     brouard  6975:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  6976:     for(i=1; i<=nlstate;i++)
                   6977:       for(j=1; j<=nlstate;j++)
1.222     brouard  6978:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6979:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  6980:                                        
1.222     brouard  6981:          /* 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  6982:                                        
1.222     brouard  6983:        }
1.269     brouard  6984: 
                   6985:     /* Standard deviation of expectancies ij */                
1.126     brouard  6986:     fprintf(ficresstdeij,"%3.0f",age );
                   6987:     for(i=1; i<=nlstate;i++){
                   6988:       eip=0.;
                   6989:       vip=0.;
                   6990:       for(j=1; j<=nlstate;j++){
1.222     brouard  6991:        eip += eij[i][j][(int)age];
                   6992:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   6993:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   6994:        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  6995:       }
                   6996:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   6997:     }
                   6998:     fprintf(ficresstdeij,"\n");
1.218     brouard  6999:                
1.269     brouard  7000:     /* Variance of expectancies ij */          
1.126     brouard  7001:     fprintf(ficrescveij,"%3.0f",age );
                   7002:     for(i=1; i<=nlstate;i++)
                   7003:       for(j=1; j<=nlstate;j++){
1.222     brouard  7004:        cptj= (j-1)*nlstate+i;
                   7005:        for(i2=1; i2<=nlstate;i2++)
                   7006:          for(j2=1; j2<=nlstate;j2++){
                   7007:            cptj2= (j2-1)*nlstate+i2;
                   7008:            if(cptj2 <= cptj)
                   7009:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   7010:          }
1.126     brouard  7011:       }
                   7012:     fprintf(ficrescveij,"\n");
1.218     brouard  7013:                
1.126     brouard  7014:   }
                   7015:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   7016:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   7017:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   7018:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   7019:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7020:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7021:   printf("\n");
                   7022:   fprintf(ficlog,"\n");
1.218     brouard  7023:        
1.126     brouard  7024:   free_vector(xm,1,npar);
                   7025:   free_vector(xp,1,npar);
                   7026:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   7027:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   7028:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   7029: }
1.218     brouard  7030:  
1.126     brouard  7031: /************ Variance ******************/
1.235     brouard  7032:  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  7033:  {
1.279     brouard  7034:    /** Variance of health expectancies 
                   7035:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   7036:     * double **newm;
                   7037:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   7038:     */
1.218     brouard  7039:   
                   7040:    /* int movingaverage(); */
                   7041:    double **dnewm,**doldm;
                   7042:    double **dnewmp,**doldmp;
                   7043:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  7044:    int first=0;
1.218     brouard  7045:    int k;
                   7046:    double *xp;
1.279     brouard  7047:    double **gp, **gm;  /**< for var eij */
                   7048:    double ***gradg, ***trgradg; /**< for var eij */
                   7049:    double **gradgp, **trgradgp; /**< for var p point j */
                   7050:    double *gpp, *gmp; /**< for var p point j */
                   7051:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
1.218     brouard  7052:    double ***p3mat;
                   7053:    double age,agelim, hf;
                   7054:    /* double ***mobaverage; */
                   7055:    int theta;
                   7056:    char digit[4];
                   7057:    char digitp[25];
                   7058: 
                   7059:    char fileresprobmorprev[FILENAMELENGTH];
                   7060: 
                   7061:    if(popbased==1){
                   7062:      if(mobilav!=0)
                   7063:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   7064:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   7065:    }
                   7066:    else 
                   7067:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  7068: 
1.218     brouard  7069:    /* if (mobilav!=0) { */
                   7070:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7071:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   7072:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   7073:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   7074:    /*   } */
                   7075:    /* } */
                   7076: 
                   7077:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   7078:    sprintf(digit,"%-d",ij);
                   7079:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   7080:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   7081:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   7082:    strcat(fileresprobmorprev,fileresu);
                   7083:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   7084:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   7085:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   7086:    }
                   7087:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   7088:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   7089:    pstamp(ficresprobmorprev);
                   7090:    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  7091:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
1.337     brouard  7092: 
                   7093:    /* We use TinvDoQresult[nres][resultmodel[nres][j] we sort according to the equation model and the resultline: it is a choice */
                   7094:    /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ /\* To be done*\/ */
                   7095:    /*   fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   7096:    /* } */
                   7097:    for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */ /* To be done*/
1.344     brouard  7098:      /* fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); */
1.337     brouard  7099:      fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  7100:    }
1.337     brouard  7101:    /* for(j=1;j<=cptcoveff;j++)  */
                   7102:    /*   fprintf(ficresprobmorprev," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,TnsdVar[Tvaraff[j]])]); */
1.238     brouard  7103:    fprintf(ficresprobmorprev,"\n");
                   7104: 
1.218     brouard  7105:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   7106:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   7107:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   7108:      for(i=1; i<=nlstate;i++)
                   7109:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   7110:    }  
                   7111:    fprintf(ficresprobmorprev,"\n");
                   7112:   
                   7113:    fprintf(ficgp,"\n# Routine varevsij");
                   7114:    fprintf(ficgp,"\nunset title \n");
                   7115:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   7116:    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");
                   7117:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  7118: 
1.218     brouard  7119:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7120:    pstamp(ficresvij);
                   7121:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   7122:    if(popbased==1)
                   7123:      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);
                   7124:    else
                   7125:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   7126:    fprintf(ficresvij,"# Age");
                   7127:    for(i=1; i<=nlstate;i++)
                   7128:      for(j=1; j<=nlstate;j++)
                   7129:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   7130:    fprintf(ficresvij,"\n");
                   7131: 
                   7132:    xp=vector(1,npar);
                   7133:    dnewm=matrix(1,nlstate,1,npar);
                   7134:    doldm=matrix(1,nlstate,1,nlstate);
                   7135:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   7136:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7137: 
                   7138:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   7139:    gpp=vector(nlstate+1,nlstate+ndeath);
                   7140:    gmp=vector(nlstate+1,nlstate+ndeath);
                   7141:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  7142:   
1.218     brouard  7143:    if(estepm < stepm){
                   7144:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   7145:    }
                   7146:    else  hstepm=estepm;   
                   7147:    /* For example we decided to compute the life expectancy with the smallest unit */
                   7148:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   7149:       nhstepm is the number of hstepm from age to agelim 
                   7150:       nstepm is the number of stepm from age to agelim. 
                   7151:       Look at function hpijx to understand why because of memory size limitations, 
                   7152:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   7153:       survival function given by stepm (the optimization length). Unfortunately it
                   7154:       means that if the survival funtion is printed every two years of age and if
                   7155:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   7156:       results. So we changed our mind and took the option of the best precision.
                   7157:    */
                   7158:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   7159:    agelim = AGESUP;
                   7160:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   7161:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7162:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   7163:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7164:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   7165:      gp=matrix(0,nhstepm,1,nlstate);
                   7166:      gm=matrix(0,nhstepm,1,nlstate);
                   7167:                
                   7168:                
                   7169:      for(theta=1; theta <=npar; theta++){
                   7170:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   7171:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7172:        }
1.279     brouard  7173:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   7174:        * returns into prlim .
1.288     brouard  7175:        */
1.242     brouard  7176:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  7177: 
                   7178:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  7179:        if (popbased==1) {
                   7180:         if(mobilav ==0){
                   7181:           for(i=1; i<=nlstate;i++)
                   7182:             prlim[i][i]=probs[(int)age][i][ij];
                   7183:         }else{ /* mobilav */ 
                   7184:           for(i=1; i<=nlstate;i++)
                   7185:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   7186:         }
                   7187:        }
1.295     brouard  7188:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  7189:        */                      
                   7190:        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  7191:        /**< 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  7192:        * at horizon h in state j including mortality.
                   7193:        */
1.218     brouard  7194:        for(j=1; j<= nlstate; j++){
                   7195:         for(h=0; h<=nhstepm; h++){
                   7196:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   7197:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   7198:         }
                   7199:        }
1.279     brouard  7200:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  7201:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  7202:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  7203:        */
                   7204:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   7205:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   7206:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  7207:        }
                   7208:        
                   7209:        /* Again with minus shift */
1.218     brouard  7210:                        
                   7211:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   7212:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  7213: 
1.242     brouard  7214:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  7215:                        
                   7216:        if (popbased==1) {
                   7217:         if(mobilav ==0){
                   7218:           for(i=1; i<=nlstate;i++)
                   7219:             prlim[i][i]=probs[(int)age][i][ij];
                   7220:         }else{ /* mobilav */ 
                   7221:           for(i=1; i<=nlstate;i++)
                   7222:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   7223:         }
                   7224:        }
                   7225:                        
1.235     brouard  7226:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  7227:                        
                   7228:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   7229:         for(h=0; h<=nhstepm; h++){
                   7230:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   7231:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   7232:         }
                   7233:        }
                   7234:        /* This for computing probability of death (h=1 means
                   7235:          computed over hstepm matrices product = hstepm*stepm months) 
                   7236:          as a weighted average of prlim.
                   7237:        */
                   7238:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   7239:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   7240:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   7241:        }    
1.279     brouard  7242:        /* end shifting computations */
                   7243: 
                   7244:        /**< Computing gradient matrix at horizon h 
                   7245:        */
1.218     brouard  7246:        for(j=1; j<= nlstate; j++) /* vareij */
                   7247:         for(h=0; h<=nhstepm; h++){
                   7248:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   7249:         }
1.279     brouard  7250:        /**< Gradient of overall mortality p.3 (or p.j) 
                   7251:        */
                   7252:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
1.218     brouard  7253:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   7254:        }
                   7255:                        
                   7256:      } /* End theta */
1.279     brouard  7257:      
                   7258:      /* We got the gradient matrix for each theta and state j */               
1.218     brouard  7259:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   7260:                
                   7261:      for(h=0; h<=nhstepm; h++) /* veij */
                   7262:        for(j=1; j<=nlstate;j++)
                   7263:         for(theta=1; theta <=npar; theta++)
                   7264:           trgradg[h][j][theta]=gradg[h][theta][j];
                   7265:                
                   7266:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   7267:        for(theta=1; theta <=npar; theta++)
                   7268:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  7269:      /**< as well as its transposed matrix 
                   7270:       */               
1.218     brouard  7271:                
                   7272:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   7273:      for(i=1;i<=nlstate;i++)
                   7274:        for(j=1;j<=nlstate;j++)
                   7275:         vareij[i][j][(int)age] =0.;
1.279     brouard  7276: 
                   7277:      /* Computing trgradg by matcov by gradg at age and summing over h
                   7278:       * and k (nhstepm) formula 15 of article
                   7279:       * Lievre-Brouard-Heathcote
                   7280:       */
                   7281:      
1.218     brouard  7282:      for(h=0;h<=nhstepm;h++){
                   7283:        for(k=0;k<=nhstepm;k++){
                   7284:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   7285:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   7286:         for(i=1;i<=nlstate;i++)
                   7287:           for(j=1;j<=nlstate;j++)
                   7288:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   7289:        }
                   7290:      }
                   7291:                
1.279     brouard  7292:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
                   7293:       * p.j overall mortality formula 49 but computed directly because
                   7294:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   7295:       * wix is independent of theta.
                   7296:       */
1.218     brouard  7297:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   7298:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   7299:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   7300:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   7301:         varppt[j][i]=doldmp[j][i];
                   7302:      /* end ppptj */
                   7303:      /*  x centered again */
                   7304:                
1.242     brouard  7305:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  7306:                
                   7307:      if (popbased==1) {
                   7308:        if(mobilav ==0){
                   7309:         for(i=1; i<=nlstate;i++)
                   7310:           prlim[i][i]=probs[(int)age][i][ij];
                   7311:        }else{ /* mobilav */ 
                   7312:         for(i=1; i<=nlstate;i++)
                   7313:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   7314:        }
                   7315:      }
                   7316:                
                   7317:      /* This for computing probability of death (h=1 means
                   7318:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   7319:        as a weighted average of prlim.
                   7320:      */
1.235     brouard  7321:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  7322:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   7323:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   7324:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   7325:      }    
                   7326:      /* end probability of death */
                   7327:                
                   7328:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   7329:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   7330:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   7331:        for(i=1; i<=nlstate;i++){
                   7332:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   7333:        }
                   7334:      } 
                   7335:      fprintf(ficresprobmorprev,"\n");
                   7336:                
                   7337:      fprintf(ficresvij,"%.0f ",age );
                   7338:      for(i=1; i<=nlstate;i++)
                   7339:        for(j=1; j<=nlstate;j++){
                   7340:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   7341:        }
                   7342:      fprintf(ficresvij,"\n");
                   7343:      free_matrix(gp,0,nhstepm,1,nlstate);
                   7344:      free_matrix(gm,0,nhstepm,1,nlstate);
                   7345:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   7346:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   7347:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7348:    } /* End age */
                   7349:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   7350:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   7351:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   7352:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   7353:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   7354:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   7355:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   7356:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   7357:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   7358:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   7359:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   7360:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   7361:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   7362:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   7363:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   7364:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   7365:    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);
                   7366:    /*  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  7367:     */
1.218     brouard  7368:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   7369:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  7370: 
1.218     brouard  7371:    free_vector(xp,1,npar);
                   7372:    free_matrix(doldm,1,nlstate,1,nlstate);
                   7373:    free_matrix(dnewm,1,nlstate,1,npar);
                   7374:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7375:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   7376:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7377:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7378:    fclose(ficresprobmorprev);
                   7379:    fflush(ficgp);
                   7380:    fflush(fichtm); 
                   7381:  }  /* end varevsij */
1.126     brouard  7382: 
                   7383: /************ Variance of prevlim ******************/
1.269     brouard  7384:  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  7385: {
1.205     brouard  7386:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  7387:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  7388: 
1.268     brouard  7389:   double **dnewmpar,**doldm;
1.126     brouard  7390:   int i, j, nhstepm, hstepm;
                   7391:   double *xp;
                   7392:   double *gp, *gm;
                   7393:   double **gradg, **trgradg;
1.208     brouard  7394:   double **mgm, **mgp;
1.126     brouard  7395:   double age,agelim;
                   7396:   int theta;
                   7397:   
                   7398:   pstamp(ficresvpl);
1.288     brouard  7399:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  7400:   fprintf(ficresvpl,"# Age ");
                   7401:   if(nresult >=1)
                   7402:     fprintf(ficresvpl," Result# ");
1.126     brouard  7403:   for(i=1; i<=nlstate;i++)
                   7404:       fprintf(ficresvpl," %1d-%1d",i,i);
                   7405:   fprintf(ficresvpl,"\n");
                   7406: 
                   7407:   xp=vector(1,npar);
1.268     brouard  7408:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  7409:   doldm=matrix(1,nlstate,1,nlstate);
                   7410:   
                   7411:   hstepm=1*YEARM; /* Every year of age */
                   7412:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   7413:   agelim = AGESUP;
                   7414:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   7415:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7416:     if (stepm >= YEARM) hstepm=1;
                   7417:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7418:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  7419:     mgp=matrix(1,npar,1,nlstate);
                   7420:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  7421:     gp=vector(1,nlstate);
                   7422:     gm=vector(1,nlstate);
                   7423: 
                   7424:     for(theta=1; theta <=npar; theta++){
                   7425:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   7426:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7427:       }
1.288     brouard  7428:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   7429:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   7430:       /* else */
                   7431:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  7432:       for(i=1;i<=nlstate;i++){
1.126     brouard  7433:        gp[i] = prlim[i][i];
1.208     brouard  7434:        mgp[theta][i] = prlim[i][i];
                   7435:       }
1.126     brouard  7436:       for(i=1; i<=npar; i++) /* Computes gradient */
                   7437:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  7438:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   7439:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   7440:       /* else */
                   7441:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  7442:       for(i=1;i<=nlstate;i++){
1.126     brouard  7443:        gm[i] = prlim[i][i];
1.208     brouard  7444:        mgm[theta][i] = prlim[i][i];
                   7445:       }
1.126     brouard  7446:       for(i=1;i<=nlstate;i++)
                   7447:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  7448:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  7449:     } /* End theta */
                   7450: 
                   7451:     trgradg =matrix(1,nlstate,1,npar);
                   7452: 
                   7453:     for(j=1; j<=nlstate;j++)
                   7454:       for(theta=1; theta <=npar; theta++)
                   7455:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  7456:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7457:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7458:     /*   for(j=1; j<=nlstate;j++){ */
                   7459:     /*         printf(" %d ",j); */
                   7460:     /*         for(theta=1; theta <=npar; theta++) */
                   7461:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7462:     /*         printf("\n "); */
                   7463:     /*   } */
                   7464:     /* } */
                   7465:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7466:     /*   printf("\n gradg %d ",(int)age); */
                   7467:     /*   for(j=1; j<=nlstate;j++){ */
                   7468:     /*         printf("%d ",j); */
                   7469:     /*         for(theta=1; theta <=npar; theta++) */
                   7470:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7471:     /*         printf("\n "); */
                   7472:     /*   } */
                   7473:     /* } */
1.126     brouard  7474: 
                   7475:     for(i=1;i<=nlstate;i++)
                   7476:       varpl[i][(int)age] =0.;
1.209     brouard  7477:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
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:     }else{
1.268     brouard  7481:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7482:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  7483:     }
1.126     brouard  7484:     for(i=1;i<=nlstate;i++)
                   7485:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7486: 
                   7487:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  7488:     if(nresult >=1)
                   7489:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  7490:     for(i=1; i<=nlstate;i++){
1.126     brouard  7491:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  7492:       /* for(j=1;j<=nlstate;j++) */
                   7493:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   7494:     }
1.126     brouard  7495:     fprintf(ficresvpl,"\n");
                   7496:     free_vector(gp,1,nlstate);
                   7497:     free_vector(gm,1,nlstate);
1.208     brouard  7498:     free_matrix(mgm,1,npar,1,nlstate);
                   7499:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  7500:     free_matrix(gradg,1,npar,1,nlstate);
                   7501:     free_matrix(trgradg,1,nlstate,1,npar);
                   7502:   } /* End age */
                   7503: 
                   7504:   free_vector(xp,1,npar);
                   7505:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  7506:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   7507: 
                   7508: }
                   7509: 
                   7510: 
                   7511: /************ Variance of backprevalence limit ******************/
1.269     brouard  7512:  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  7513: {
                   7514:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   7515:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   7516: 
                   7517:   double **dnewmpar,**doldm;
                   7518:   int i, j, nhstepm, hstepm;
                   7519:   double *xp;
                   7520:   double *gp, *gm;
                   7521:   double **gradg, **trgradg;
                   7522:   double **mgm, **mgp;
                   7523:   double age,agelim;
                   7524:   int theta;
                   7525:   
                   7526:   pstamp(ficresvbl);
                   7527:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   7528:   fprintf(ficresvbl,"# Age ");
                   7529:   if(nresult >=1)
                   7530:     fprintf(ficresvbl," Result# ");
                   7531:   for(i=1; i<=nlstate;i++)
                   7532:       fprintf(ficresvbl," %1d-%1d",i,i);
                   7533:   fprintf(ficresvbl,"\n");
                   7534: 
                   7535:   xp=vector(1,npar);
                   7536:   dnewmpar=matrix(1,nlstate,1,npar);
                   7537:   doldm=matrix(1,nlstate,1,nlstate);
                   7538:   
                   7539:   hstepm=1*YEARM; /* Every year of age */
                   7540:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   7541:   agelim = AGEINF;
                   7542:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   7543:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7544:     if (stepm >= YEARM) hstepm=1;
                   7545:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7546:     gradg=matrix(1,npar,1,nlstate);
                   7547:     mgp=matrix(1,npar,1,nlstate);
                   7548:     mgm=matrix(1,npar,1,nlstate);
                   7549:     gp=vector(1,nlstate);
                   7550:     gm=vector(1,nlstate);
                   7551: 
                   7552:     for(theta=1; theta <=npar; theta++){
                   7553:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   7554:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7555:       }
                   7556:       if(mobilavproj > 0 )
                   7557:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7558:       else
                   7559:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7560:       for(i=1;i<=nlstate;i++){
                   7561:        gp[i] = bprlim[i][i];
                   7562:        mgp[theta][i] = bprlim[i][i];
                   7563:       }
                   7564:      for(i=1; i<=npar; i++) /* Computes gradient */
                   7565:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   7566:        if(mobilavproj > 0 )
                   7567:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7568:        else
                   7569:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7570:       for(i=1;i<=nlstate;i++){
                   7571:        gm[i] = bprlim[i][i];
                   7572:        mgm[theta][i] = bprlim[i][i];
                   7573:       }
                   7574:       for(i=1;i<=nlstate;i++)
                   7575:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   7576:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   7577:     } /* End theta */
                   7578: 
                   7579:     trgradg =matrix(1,nlstate,1,npar);
                   7580: 
                   7581:     for(j=1; j<=nlstate;j++)
                   7582:       for(theta=1; theta <=npar; theta++)
                   7583:        trgradg[j][theta]=gradg[theta][j];
                   7584:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7585:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7586:     /*   for(j=1; j<=nlstate;j++){ */
                   7587:     /*         printf(" %d ",j); */
                   7588:     /*         for(theta=1; theta <=npar; theta++) */
                   7589:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7590:     /*         printf("\n "); */
                   7591:     /*   } */
                   7592:     /* } */
                   7593:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7594:     /*   printf("\n gradg %d ",(int)age); */
                   7595:     /*   for(j=1; j<=nlstate;j++){ */
                   7596:     /*         printf("%d ",j); */
                   7597:     /*         for(theta=1; theta <=npar; theta++) */
                   7598:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7599:     /*         printf("\n "); */
                   7600:     /*   } */
                   7601:     /* } */
                   7602: 
                   7603:     for(i=1;i<=nlstate;i++)
                   7604:       varbpl[i][(int)age] =0.;
                   7605:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   7606:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7607:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7608:     }else{
                   7609:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7610:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7611:     }
                   7612:     for(i=1;i<=nlstate;i++)
                   7613:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7614: 
                   7615:     fprintf(ficresvbl,"%.0f ",age );
                   7616:     if(nresult >=1)
                   7617:       fprintf(ficresvbl,"%d ",nres );
                   7618:     for(i=1; i<=nlstate;i++)
                   7619:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   7620:     fprintf(ficresvbl,"\n");
                   7621:     free_vector(gp,1,nlstate);
                   7622:     free_vector(gm,1,nlstate);
                   7623:     free_matrix(mgm,1,npar,1,nlstate);
                   7624:     free_matrix(mgp,1,npar,1,nlstate);
                   7625:     free_matrix(gradg,1,npar,1,nlstate);
                   7626:     free_matrix(trgradg,1,nlstate,1,npar);
                   7627:   } /* End age */
                   7628: 
                   7629:   free_vector(xp,1,npar);
                   7630:   free_matrix(doldm,1,nlstate,1,npar);
                   7631:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  7632: 
                   7633: }
                   7634: 
                   7635: /************ Variance of one-step probabilities  ******************/
                   7636: 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  7637:  {
                   7638:    int i, j=0,  k1, l1, tj;
                   7639:    int k2, l2, j1,  z1;
                   7640:    int k=0, l;
                   7641:    int first=1, first1, first2;
1.326     brouard  7642:    int nres=0; /* New */
1.222     brouard  7643:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   7644:    double **dnewm,**doldm;
                   7645:    double *xp;
                   7646:    double *gp, *gm;
                   7647:    double **gradg, **trgradg;
                   7648:    double **mu;
                   7649:    double age, cov[NCOVMAX+1];
                   7650:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   7651:    int theta;
                   7652:    char fileresprob[FILENAMELENGTH];
                   7653:    char fileresprobcov[FILENAMELENGTH];
                   7654:    char fileresprobcor[FILENAMELENGTH];
                   7655:    double ***varpij;
                   7656: 
                   7657:    strcpy(fileresprob,"PROB_"); 
1.356     brouard  7658:    strcat(fileresprob,fileresu);
1.222     brouard  7659:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   7660:      printf("Problem with resultfile: %s\n", fileresprob);
                   7661:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   7662:    }
                   7663:    strcpy(fileresprobcov,"PROBCOV_"); 
                   7664:    strcat(fileresprobcov,fileresu);
                   7665:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   7666:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   7667:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   7668:    }
                   7669:    strcpy(fileresprobcor,"PROBCOR_"); 
                   7670:    strcat(fileresprobcor,fileresu);
                   7671:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   7672:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   7673:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   7674:    }
                   7675:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7676:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7677:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7678:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7679:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7680:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7681:    pstamp(ficresprob);
                   7682:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   7683:    fprintf(ficresprob,"# Age");
                   7684:    pstamp(ficresprobcov);
                   7685:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   7686:    fprintf(ficresprobcov,"# Age");
                   7687:    pstamp(ficresprobcor);
                   7688:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   7689:    fprintf(ficresprobcor,"# Age");
1.126     brouard  7690: 
                   7691: 
1.222     brouard  7692:    for(i=1; i<=nlstate;i++)
                   7693:      for(j=1; j<=(nlstate+ndeath);j++){
                   7694:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   7695:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   7696:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   7697:      }  
                   7698:    /* fprintf(ficresprob,"\n");
                   7699:       fprintf(ficresprobcov,"\n");
                   7700:       fprintf(ficresprobcor,"\n");
                   7701:    */
                   7702:    xp=vector(1,npar);
                   7703:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7704:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7705:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   7706:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   7707:    first=1;
                   7708:    fprintf(ficgp,"\n# Routine varprob");
                   7709:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   7710:    fprintf(fichtm,"\n");
                   7711: 
1.288     brouard  7712:    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  7713:    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);
                   7714:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  7715: and drawn. It helps understanding how is the covariance between two incidences.\
                   7716:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  7717:    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  7718: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   7719: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   7720: standard deviations wide on each axis. <br>\
                   7721:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   7722:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   7723: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   7724: 
1.222     brouard  7725:    cov[1]=1;
                   7726:    /* tj=cptcoveff; */
1.225     brouard  7727:    tj = (int) pow(2,cptcoveff);
1.222     brouard  7728:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   7729:    j1=0;
1.332     brouard  7730: 
                   7731:    for(nres=1;nres <=nresult; nres++){ /* For each resultline */
                   7732:    for(j1=1; j1<=tj;j1++){ /* For any combination of dummy covariates, fixed and varying */
1.342     brouard  7733:      /* 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  7734:      if(tj != 1 && TKresult[nres]!= j1)
                   7735:        continue;
                   7736: 
                   7737:    /* for(j1=1; j1<=tj;j1++){  /\* For each valid combination of covariates or only once*\/ */
                   7738:      /* for(nres=1;nres <=1; nres++){ /\* For each resultline *\/ */
                   7739:      /* /\* for(nres=1;nres <=nresult; nres++){ /\\* For each resultline *\\/ *\/ */
1.222     brouard  7740:      if  (cptcovn>0) {
1.334     brouard  7741:        fprintf(ficresprob, "\n#********** Variable ");
                   7742:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   7743:        fprintf(ficgp, "\n#********** Variable ");
                   7744:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   7745:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   7746: 
                   7747:        /* Including quantitative variables of the resultline to be done */
                   7748:        for (z1=1; z1<=cptcovs; z1++){ /* Loop on each variable of this resultline  */
1.343     brouard  7749:         /* printf("Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model); */
1.338     brouard  7750:         fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model);
                   7751:         /* 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  7752:         if(Dummy[modelresult[nres][z1]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to z1 in resultline  */
                   7753:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed referenced to model equation */
                   7754:             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  */
                   7755:             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  */
                   7756:             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  */
                   7757:             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  */
                   7758:             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  */
                   7759:             fprintf(ficresprob,"fixed ");
                   7760:             fprintf(ficresprobcov,"fixed ");
                   7761:             fprintf(ficgp,"fixed ");
                   7762:             fprintf(fichtmcov,"fixed ");
                   7763:             fprintf(ficresprobcor,"fixed ");
                   7764:           }else{
                   7765:             fprintf(ficresprob,"varyi ");
                   7766:             fprintf(ficresprobcov,"varyi ");
                   7767:             fprintf(ficgp,"varyi ");
                   7768:             fprintf(fichtmcov,"varyi ");
                   7769:             fprintf(ficresprobcor,"varyi ");
                   7770:           }
                   7771:         }else if(Dummy[modelresult[nres][z1]]==1){ /* Quanti variable */
                   7772:           /* For each selected (single) quantitative value */
1.337     brouard  7773:           fprintf(ficresprob," V%d=%lg ",Tvqresult[nres][z1],Tqresult[nres][z1]);
1.334     brouard  7774:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed */
                   7775:             fprintf(ficresprob,"fixed ");
                   7776:             fprintf(ficresprobcov,"fixed ");
                   7777:             fprintf(ficgp,"fixed ");
                   7778:             fprintf(fichtmcov,"fixed ");
                   7779:             fprintf(ficresprobcor,"fixed ");
                   7780:           }else{
                   7781:             fprintf(ficresprob,"varyi ");
                   7782:             fprintf(ficresprobcov,"varyi ");
                   7783:             fprintf(ficgp,"varyi ");
                   7784:             fprintf(fichtmcov,"varyi ");
                   7785:             fprintf(ficresprobcor,"varyi ");
                   7786:           }
                   7787:         }else{
                   7788:           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 */
                   7789:           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 */
                   7790:           exit(1);
                   7791:         }
                   7792:        } /* End loop on variable of this resultline */
                   7793:        /* for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]); */
1.222     brouard  7794:        fprintf(ficresprob, "**********\n#\n");
                   7795:        fprintf(ficresprobcov, "**********\n#\n");
                   7796:        fprintf(ficgp, "**********\n#\n");
                   7797:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   7798:        fprintf(ficresprobcor, "**********\n#");    
                   7799:        if(invalidvarcomb[j1]){
                   7800:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   7801:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   7802:         continue;
                   7803:        }
                   7804:      }
                   7805:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   7806:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7807:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   7808:      gm=vector(1,(nlstate)*(nlstate+ndeath));
1.334     brouard  7809:      for (age=bage; age<=fage; age ++){ /* Fo each age we feed the model equation with covariates, using precov as in hpxij() ? */
1.222     brouard  7810:        cov[2]=age;
                   7811:        if(nagesqr==1)
                   7812:         cov[3]= age*age;
1.334     brouard  7813:        /* New code end of combination but for each resultline */
                   7814:        for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  7815:         if(Typevar[k1]==1 || Typevar[k1] ==3){ /* A product with age */
1.334     brouard  7816:           cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.326     brouard  7817:         }else{
1.334     brouard  7818:           cov[2+nagesqr+k1]=precov[nres][k1];
1.326     brouard  7819:         }
1.334     brouard  7820:        }/* End of loop on model equation */
                   7821: /* Old code */
                   7822:        /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   7823:        /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)]; *\/ */
                   7824:        /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   7825:        /*       /\* Here comes the value of the covariate 'j1' after renumbering k with single dummy covariates *\/ */
                   7826:        /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(j1,TnsdVar[TvarsD[k]])]; */
                   7827:        /*       /\*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*\//\* j1 1 2 3 4 */
                   7828:        /*                                                                  * 1  1 1 1 1 */
                   7829:        /*                                                                  * 2  2 1 1 1 */
                   7830:        /*                                                                  * 3  1 2 1 1 */
                   7831:        /*                                                                  *\/ */
                   7832:        /*       /\* nbcode[1][1]=0 nbcode[1][2]=1;*\/ */
                   7833:        /* } */
                   7834:        /* /\* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   7835:        /* /\* ) p nbcode[Tvar[Tage[k]]][(1 & (ij-1) >> (k-1))+1] *\/ */
                   7836:        /* /\*for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; *\/ */
                   7837:        /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   7838:        /*       if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   7839:        /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(j1,TnsdVar[Tvar[Tage[k]]])]*cov[2]; */
                   7840:        /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7841:        /*       } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   7842:        /*         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]); */
                   7843:        /*         /\* cov[2+nagesqr+Tage[k]]=meanq[k]/idq[k]*cov[2];/\\* Using the mean of quantitative variable Tvar[Tage[k]] /\\* Tqresult[nres][k]; *\\/ *\/ */
                   7844:        /*         /\* exit(1); *\/ */
                   7845:        /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   7846:        /*       } */
                   7847:        /*       /\* cov[2+Tage[k]+nagesqr]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7848:        /* } */
                   7849:        /* for (k=1; k<=cptcovprod;k++){/\* For product without age *\/ */
                   7850:        /*       if(Dummy[Tvard[k][1]]==0){ */
                   7851:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7852:        /*           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]])]; */
                   7853:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7854:        /*         }else{ /\* Should we use the mean of the quantitative variables? *\/ */
                   7855:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,TnsdVar[Tvard[k][1]])] * Tqresult[nres][resultmodel[nres][k]]; */
                   7856:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   7857:        /*         } */
                   7858:        /*       }else{ */
                   7859:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7860:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(j1,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][TnsdVar[Tvard[k][1]]]; */
                   7861:        /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   7862:        /*         }else{ */
                   7863:        /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][TnsdVar[Tvard[k][1]]]*  Tqinvresult[nres][TnsdVar[Tvard[k][2]]]; */
                   7864:        /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   7865:        /*         } */
                   7866:        /*       } */
                   7867:        /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7868:        /* } */                 
1.326     brouard  7869: /* For each age and combination of dummy covariates we slightly move the parameters of delti in order to get the gradient*/                    
1.222     brouard  7870:        for(theta=1; theta <=npar; theta++){
                   7871:         for(i=1; i<=npar; i++)
                   7872:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  7873:                                
1.222     brouard  7874:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  7875:                                
1.222     brouard  7876:         k=0;
                   7877:         for(i=1; i<= (nlstate); i++){
                   7878:           for(j=1; j<=(nlstate+ndeath);j++){
                   7879:             k=k+1;
                   7880:             gp[k]=pmmij[i][j];
                   7881:           }
                   7882:         }
1.220     brouard  7883:                                
1.222     brouard  7884:         for(i=1; i<=npar; i++)
                   7885:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  7886:                                
1.222     brouard  7887:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   7888:         k=0;
                   7889:         for(i=1; i<=(nlstate); i++){
                   7890:           for(j=1; j<=(nlstate+ndeath);j++){
                   7891:             k=k+1;
                   7892:             gm[k]=pmmij[i][j];
                   7893:           }
                   7894:         }
1.220     brouard  7895:                                
1.222     brouard  7896:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   7897:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   7898:        }
1.126     brouard  7899: 
1.222     brouard  7900:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   7901:         for(theta=1; theta <=npar; theta++)
                   7902:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  7903:                        
1.222     brouard  7904:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   7905:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  7906:                        
1.222     brouard  7907:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  7908:                        
1.222     brouard  7909:        k=0;
                   7910:        for(i=1; i<=(nlstate); i++){
                   7911:         for(j=1; j<=(nlstate+ndeath);j++){
                   7912:           k=k+1;
                   7913:           mu[k][(int) age]=pmmij[i][j];
                   7914:         }
                   7915:        }
                   7916:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   7917:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   7918:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  7919:                        
1.222     brouard  7920:        /*printf("\n%d ",(int)age);
                   7921:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7922:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7923:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7924:         }*/
1.220     brouard  7925:                        
1.222     brouard  7926:        fprintf(ficresprob,"\n%d ",(int)age);
                   7927:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   7928:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  7929:                        
1.222     brouard  7930:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   7931:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   7932:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7933:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   7934:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   7935:        }
                   7936:        i=0;
                   7937:        for (k=1; k<=(nlstate);k++){
                   7938:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   7939:           i++;
                   7940:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   7941:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   7942:           for (j=1; j<=i;j++){
                   7943:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   7944:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   7945:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   7946:           }
                   7947:         }
                   7948:        }/* end of loop for state */
                   7949:      } /* end of loop for age */
                   7950:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7951:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7952:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7953:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7954:     
                   7955:      /* Confidence intervalle of pij  */
                   7956:      /*
                   7957:        fprintf(ficgp,"\nunset parametric;unset label");
                   7958:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   7959:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   7960:        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);
                   7961:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   7962:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   7963:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   7964:      */
                   7965:                
                   7966:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   7967:      first1=1;first2=2;
                   7968:      for (k2=1; k2<=(nlstate);k2++){
                   7969:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   7970:         if(l2==k2) continue;
                   7971:         j=(k2-1)*(nlstate+ndeath)+l2;
                   7972:         for (k1=1; k1<=(nlstate);k1++){
                   7973:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   7974:             if(l1==k1) continue;
                   7975:             i=(k1-1)*(nlstate+ndeath)+l1;
                   7976:             if(i<=j) continue;
                   7977:             for (age=bage; age<=fage; age ++){ 
                   7978:               if ((int)age %5==0){
                   7979:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   7980:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7981:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7982:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   7983:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   7984:                 c12=cv12/sqrt(v1*v2);
                   7985:                 /* Computing eigen value of matrix of covariance */
                   7986:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7987:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7988:                 if ((lc2 <0) || (lc1 <0) ){
                   7989:                   if(first2==1){
                   7990:                     first1=0;
                   7991:                     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);
                   7992:                   }
                   7993:                   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);
                   7994:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   7995:                   /* lc2=fabs(lc2); */
                   7996:                 }
1.220     brouard  7997:                                                                
1.222     brouard  7998:                 /* Eigen vectors */
1.280     brouard  7999:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   8000:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   8001:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   8002:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   8003:                 }else
                   8004:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  8005:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   8006:                 v21=(lc1-v1)/cv12*v11;
                   8007:                 v12=-v21;
                   8008:                 v22=v11;
                   8009:                 tnalp=v21/v11;
                   8010:                 if(first1==1){
                   8011:                   first1=0;
                   8012:                   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);
                   8013:                 }
                   8014:                 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);
                   8015:                 /*printf(fignu*/
                   8016:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   8017:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   8018:                 if(first==1){
                   8019:                   first=0;
                   8020:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   8021:                   fprintf(ficgp,"\nset parametric;unset label");
                   8022:                   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);
                   8023:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  8024:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  8025:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  8026: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  8027:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   8028:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   8029:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   8030:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   8031:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   8032:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   8033:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   8034:                   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  8035:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   8036:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  8037:                 }else{
                   8038:                   first=0;
                   8039:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   8040:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   8041:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   8042:                   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  8043:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   8044:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  8045:                 }/* if first */
                   8046:               } /* age mod 5 */
                   8047:             } /* end loop age */
                   8048:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   8049:             first=1;
                   8050:           } /*l12 */
                   8051:         } /* k12 */
                   8052:        } /*l1 */
                   8053:      }/* k1 */
1.332     brouard  8054:    }  /* loop on combination of covariates j1 */
1.326     brouard  8055:    } /* loop on nres */
1.222     brouard  8056:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   8057:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   8058:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   8059:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   8060:    free_vector(xp,1,npar);
                   8061:    fclose(ficresprob);
                   8062:    fclose(ficresprobcov);
                   8063:    fclose(ficresprobcor);
                   8064:    fflush(ficgp);
                   8065:    fflush(fichtmcov);
                   8066:  }
1.126     brouard  8067: 
                   8068: 
                   8069: /******************* Printing html file ***********/
1.201     brouard  8070: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  8071:                  int lastpass, int stepm, int weightopt, char model[],\
                   8072:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  8073:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   8074:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   8075:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.237     brouard  8076:   int jj1, k1, i1, cpt, k4, nres;
1.319     brouard  8077:   /* In fact some results are already printed in fichtm which is open */
1.126     brouard  8078:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   8079:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   8080: </ul>");
1.319     brouard  8081: /*    fprintf(fichtm,"<ul><li> model=1+age+%s\n \ */
                   8082: /* </ul>", model); */
1.214     brouard  8083:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   8084:    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",
                   8085:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
1.332     brouard  8086:    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  8087:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   8088:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  8089:    fprintf(fichtm,"\
                   8090:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  8091:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  8092:    fprintf(fichtm,"\
1.217     brouard  8093:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   8094:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   8095:    fprintf(fichtm,"\
1.288     brouard  8096:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  8097:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  8098:    fprintf(fichtm,"\
1.288     brouard  8099:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  8100:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   8101:    fprintf(fichtm,"\
1.211     brouard  8102:  - (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  8103:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  8104:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  8105:    if(prevfcast==1){
                   8106:      fprintf(fichtm,"\
                   8107:  - Prevalence projections by age and states:                           \
1.201     brouard  8108:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  8109:    }
1.126     brouard  8110: 
                   8111: 
1.225     brouard  8112:    m=pow(2,cptcoveff);
1.222     brouard  8113:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  8114: 
1.317     brouard  8115:    fprintf(fichtm," \n<ul><li><b>Graphs (first order)</b></li><p>");
1.264     brouard  8116: 
                   8117:    jj1=0;
                   8118: 
                   8119:    fprintf(fichtm," \n<ul>");
1.337     brouard  8120:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8121:      /* k1=nres; */
1.338     brouard  8122:      k1=TKresult[nres];
                   8123:      if(TKresult[nres]==0)k1=1; /* To be checked for no result */
1.337     brouard  8124:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   8125:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   8126:    /*     continue; */
1.264     brouard  8127:      jj1++;
                   8128:      if (cptcovn > 0) {
                   8129:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
1.337     brouard  8130:        for (cpt=1; cpt<=cptcovs;cpt++){ /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   8131:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  8132:        }
1.337     brouard  8133:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   8134:        /*       fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   8135:        /* } */
                   8136:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8137:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8138:        /* } */
1.264     brouard  8139:        fprintf(fichtm,"\">");
                   8140:        
                   8141:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   8142:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  8143:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8144:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  8145:        }
1.337     brouard  8146:        /* fprintf(fichtm,"************ Results for covariates"); */
                   8147:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   8148:        /*       fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   8149:        /* } */
                   8150:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8151:        /*       fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8152:        /* } */
1.264     brouard  8153:        if(invalidvarcomb[k1]){
                   8154:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   8155:         continue;
                   8156:        }
                   8157:        fprintf(fichtm,"</a></li>");
                   8158:      } /* cptcovn >0 */
                   8159:    }
1.317     brouard  8160:    fprintf(fichtm," \n</ul>");
1.264     brouard  8161: 
1.222     brouard  8162:    jj1=0;
1.237     brouard  8163: 
1.337     brouard  8164:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8165:      /* k1=nres; */
1.338     brouard  8166:      k1=TKresult[nres];
                   8167:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8168:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   8169:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   8170:    /*     continue; */
1.220     brouard  8171: 
1.222     brouard  8172:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   8173:      jj1++;
                   8174:      if (cptcovn > 0) {
1.264     brouard  8175:        fprintf(fichtm,"\n<p><a name=\"rescov");
1.337     brouard  8176:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8177:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  8178:        }
1.337     brouard  8179:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8180:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8181:        /* } */
1.264     brouard  8182:        fprintf(fichtm,"\"</a>");
                   8183:  
1.222     brouard  8184:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  8185:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8186:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8187:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  8188:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   8189:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  8190:        }
1.230     brouard  8191:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.338     brouard  8192:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.222     brouard  8193:        if(invalidvarcomb[k1]){
                   8194:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   8195:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   8196:         continue;
                   8197:        }
                   8198:      }
                   8199:      /* aij, bij */
1.259     brouard  8200:      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  8201: <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  8202:      /* Pij */
1.241     brouard  8203:      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> \
                   8204: <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  8205:      /* Quasi-incidences */
                   8206:      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  8207:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  8208:  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  8209: 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> \
                   8210: <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  8211:      /* Survival functions (period) in state j */
                   8212:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  8213:        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);
                   8214:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   8215:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.222     brouard  8216:      }
                   8217:      /* State specific survival functions (period) */
                   8218:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  8219:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
                   8220:  And probability to be observed in various states (up to %d) being in state %d at different ages.      \
1.329     brouard  8221:  <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);
                   8222:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   8223:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.222     brouard  8224:      }
1.288     brouard  8225:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  8226:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  8227:        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  8228:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
1.329     brouard  8229:       fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.222     brouard  8230:      }
1.296     brouard  8231:      if(prevbcast==1){
1.288     brouard  8232:        /* Backward prevalence in each health state */
1.222     brouard  8233:        for(cpt=1; cpt<=nlstate;cpt++){
1.338     brouard  8234:         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);
                   8235:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJB_"),subdirf2(optionfilefiname,"PIJB_"));
                   8236:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.222     brouard  8237:        }
1.217     brouard  8238:      }
1.222     brouard  8239:      if(prevfcast==1){
1.288     brouard  8240:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  8241:        for(cpt=1; cpt<=nlstate;cpt++){
1.314     brouard  8242:         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);
                   8243:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
                   8244:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
                   8245:                 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  8246:        }
                   8247:      }
1.296     brouard  8248:      if(prevbcast==1){
1.268     brouard  8249:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   8250:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  8251:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
                   8252:  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 \
                   8253:  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  8254: 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);
                   8255:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
                   8256:         fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
1.268     brouard  8257:        }
                   8258:      }
1.220     brouard  8259:         
1.222     brouard  8260:      for(cpt=1; cpt<=nlstate;cpt++) {
1.314     brouard  8261:        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);
                   8262:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
                   8263:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
1.222     brouard  8264:      }
                   8265:      /* } /\* end i1 *\/ */
1.337     brouard  8266:    }/* End k1=nres */
1.222     brouard  8267:    fprintf(fichtm,"</ul>");
1.126     brouard  8268: 
1.222     brouard  8269:    fprintf(fichtm,"\
1.126     brouard  8270: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  8271:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  8272:  - 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  8273: But because parameters are usually highly correlated (a higher incidence of disability \
                   8274: and a higher incidence of recovery can give very close observed transition) it might \
                   8275: be very useful to look not only at linear confidence intervals estimated from the \
                   8276: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   8277: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   8278: covariance matrix of the one-step probabilities. \
                   8279: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  8280: 
1.222     brouard  8281:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   8282:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   8283:    fprintf(fichtm,"\
1.126     brouard  8284:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  8285:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  8286: 
1.222     brouard  8287:    fprintf(fichtm,"\
1.126     brouard  8288:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  8289:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   8290:    fprintf(fichtm,"\
1.126     brouard  8291:  - 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): \
                   8292:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  8293:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  8294:    fprintf(fichtm,"\
1.126     brouard  8295:  - (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): \
                   8296:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  8297:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  8298:    fprintf(fichtm,"\
1.288     brouard  8299:  - 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  8300:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   8301:    fprintf(fichtm,"\
1.128     brouard  8302:  - 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  8303:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   8304:    fprintf(fichtm,"\
1.288     brouard  8305:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  8306:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  8307: 
                   8308: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   8309: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   8310: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   8311: /*     <br>",fileres,fileres,fileres,fileres); */
                   8312: /*  else  */
1.338     brouard  8313: /*    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  8314:    fflush(fichtm);
1.126     brouard  8315: 
1.225     brouard  8316:    m=pow(2,cptcoveff);
1.222     brouard  8317:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  8318: 
1.317     brouard  8319:    fprintf(fichtm," <ul><li><b>Graphs (second order)</b></li><p>");
                   8320: 
                   8321:   jj1=0;
                   8322: 
                   8323:    fprintf(fichtm," \n<ul>");
1.337     brouard  8324:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8325:      /* k1=nres; */
1.338     brouard  8326:      k1=TKresult[nres];
1.337     brouard  8327:      /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   8328:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8329:      /*   continue; */
1.317     brouard  8330:      jj1++;
                   8331:      if (cptcovn > 0) {
                   8332:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescovsecond");
1.337     brouard  8333:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8334:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8335:        }
                   8336:        fprintf(fichtm,"\">");
                   8337:        
                   8338:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   8339:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  8340:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8341:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8342:        }
                   8343:        if(invalidvarcomb[k1]){
                   8344:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   8345:         continue;
                   8346:        }
                   8347:        fprintf(fichtm,"</a></li>");
                   8348:      } /* cptcovn >0 */
1.337     brouard  8349:    } /* End nres */
1.317     brouard  8350:    fprintf(fichtm," \n</ul>");
                   8351: 
1.222     brouard  8352:    jj1=0;
1.237     brouard  8353: 
1.241     brouard  8354:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8355:      /* k1=nres; */
1.338     brouard  8356:      k1=TKresult[nres];
                   8357:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8358:      /* for(k1=1; k1<=m;k1++){ */
                   8359:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8360:      /*   continue; */
1.222     brouard  8361:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   8362:      jj1++;
1.126     brouard  8363:      if (cptcovn > 0) {
1.317     brouard  8364:        fprintf(fichtm,"\n<p><a name=\"rescovsecond");
1.337     brouard  8365:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8366:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8367:        }
                   8368:        fprintf(fichtm,"\"</a>");
                   8369:        
1.126     brouard  8370:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  8371:        for (cpt=1; cpt<=cptcovs;cpt++){  /**< cptcoveff number of variables */
                   8372:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8373:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  8374:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
1.317     brouard  8375:        }
1.237     brouard  8376: 
1.338     brouard  8377:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.220     brouard  8378: 
1.222     brouard  8379:        if(invalidvarcomb[k1]){
                   8380:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   8381:         continue;
                   8382:        }
1.337     brouard  8383:      } /* If cptcovn >0 */
1.126     brouard  8384:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  8385:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.314     brouard  8386: 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);
                   8387:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   8388:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
1.126     brouard  8389:      }
                   8390:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.314     brouard  8391: health expectancies in each live states (1 to %d). If popbased=1 the smooth (due to the model) \
1.128     brouard  8392: true period expectancies (those weighted with period prevalences are also\
                   8393:  drawn in addition to the population based expectancies computed using\
1.314     brouard  8394:  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);
                   8395:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
                   8396:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  8397:      /* } /\* end i1 *\/ */
1.241     brouard  8398:   }/* End nres */
1.222     brouard  8399:    fprintf(fichtm,"</ul>");
                   8400:    fflush(fichtm);
1.126     brouard  8401: }
                   8402: 
                   8403: /******************* Gnuplot file **************/
1.296     brouard  8404: 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  8405: 
1.354     brouard  8406:   char dirfileres[256],optfileres[256];
                   8407:   char gplotcondition[256], gplotlabel[256];
1.343     brouard  8408:   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  8409:   int lv=0, vlv=0, kl=0;
1.130     brouard  8410:   int ng=0;
1.201     brouard  8411:   int vpopbased;
1.223     brouard  8412:   int ioffset; /* variable offset for columns */
1.270     brouard  8413:   int iyearc=1; /* variable column for year of projection  */
                   8414:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  8415:   int nres=0; /* Index of resultline */
1.266     brouard  8416:   int istart=1; /* For starting graphs in projections */
1.219     brouard  8417: 
1.126     brouard  8418: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   8419: /*     printf("Problem with file %s",optionfilegnuplot); */
                   8420: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   8421: /*   } */
                   8422: 
                   8423:   /*#ifdef windows */
                   8424:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  8425:   /*#endif */
1.225     brouard  8426:   m=pow(2,cptcoveff);
1.126     brouard  8427: 
1.274     brouard  8428:   /* diagram of the model */
                   8429:   fprintf(ficgp,"\n#Diagram of the model \n");
                   8430:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   8431:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   8432:   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);
                   8433: 
1.343     brouard  8434:   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  8435:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   8436:   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);
                   8437:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   8438:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   8439:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   8440:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   8441: 
1.202     brouard  8442:   /* Contribution to likelihood */
                   8443:   /* Plot the probability implied in the likelihood */
1.223     brouard  8444:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   8445:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   8446:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   8447:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  8448: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  8449:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   8450: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  8451:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   8452:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8453:   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));
                   8454:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8455:   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));
                   8456:   for (i=1; i<= nlstate ; i ++) {
                   8457:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   8458:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   8459:     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);
                   8460:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   8461:       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);
                   8462:     }
                   8463:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8464:   }
                   8465:   /* 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 */               
                   8466:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   8467:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   8468:   fprintf(ficgp,"\nset out;unset log\n");
                   8469:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  8470: 
1.343     brouard  8471:   /* Plot the probability implied in the likelihood by covariate value */
                   8472:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
                   8473:   /* if(debugILK==1){ */
                   8474:   for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
1.347     brouard  8475:     kvar=Tvar[TvarFind[kf]]; /* variable name */
                   8476:     /* k=18+Tvar[TvarFind[kf]];/\*offset because there are 18 columns in the ILK_ file but could be placed else where *\/ */
1.350     brouard  8477:     /* k=18+kf;/\*offset because there are 18 columns in the ILK_ file *\/ */
1.356     brouard  8478:     /* k=19+kf;/\*offset because there are 19 columns in the ILK_ file *\/ */
1.355     brouard  8479:     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  8480:     for (i=1; i<= nlstate ; i ++) {
                   8481:       fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   8482:       fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
1.348     brouard  8483:       if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
                   8484:        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);
                   8485:        for (j=2; j<= nlstate+ndeath ; j ++) {
                   8486:          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);
                   8487:        }
                   8488:       }else{
                   8489:        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);
                   8490:        for (j=2; j<= nlstate+ndeath ; j ++) {
                   8491:          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);
                   8492:        }
1.343     brouard  8493:       }
                   8494:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8495:     }
                   8496:   } /* End of each covariate dummy */
                   8497:   for(ncovv=1, iposold=0, kk=0; ncovv <= ncovvt ; ncovv++){
                   8498:     /* Other example        V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   8499:      *     kmodel       =     1   2     3     4         5        6        7       8        9
                   8500:      *  varying                   1     2                                 3       4        5
                   8501:      *  ncovv                     1     2                                3 4     5 6      7 8
                   8502:      * TvarVV[ncovv]             V3     5                                1 3     3 5      1 5
                   8503:      * TvarVVind[ncovv]=kmodel    2     3                                7 7     8 8      9 9
                   8504:      * TvarFind[kmodel]       1   0     0     0         0        0        0       0        0
                   8505:      * kdata     ncovcol=[V1 V2] nqv=0 ntv=[V3 V4] nqtv=V5
                   8506:      * Dummy[kmodel]          0   0     1     2         2        3        1       1        1
                   8507:      */
                   8508:     ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   8509:     kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   8510:     /* 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]); */
                   8511:     if(ipos!=iposold){ /* Not a product or first of a product */
                   8512:       /* printf(" %d",ipos); */
                   8513:       /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   8514:       /* printf(" DebugILK ficgp suite ipos=%d != iposold=%d\n", ipos, iposold); */
                   8515:       kk++; /* Position of the ncovv column in ILK_ */
                   8516:       k=18+ncovf+kk; /*offset because there are 18 columns in the ILK_ file plus ncovf fixed covariate */
                   8517:       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)  */
                   8518:        for (i=1; i<= nlstate ; i ++) {
                   8519:          fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   8520:          fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
                   8521: 
1.348     brouard  8522:            /* printf("Before DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
1.343     brouard  8523:          if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
                   8524:            /* printf("DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
                   8525:            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);
                   8526:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   8527:              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);
                   8528:            }
                   8529:          }else{
                   8530:            /* printf("DebugILK gnuplotversion=%g <5.2\n",gnuplotversion); */
                   8531:            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);
                   8532:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   8533:              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);
                   8534:            }
                   8535:          }
                   8536:          fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8537:        }
                   8538:       }/* End if dummy varying */
                   8539:     }else{ /*Product */
                   8540:       /* printf("*"); */
                   8541:       /* fprintf(ficresilk,"*"); */
                   8542:     }
                   8543:     iposold=ipos;
                   8544:   } /* For each time varying covariate */
                   8545:   /* } /\* debugILK==1 *\/ */
                   8546:   /* 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 */               
                   8547:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   8548:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   8549:   fprintf(ficgp,"\nset out;unset log\n");
                   8550:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
                   8551: 
                   8552: 
                   8553:   
1.126     brouard  8554:   strcpy(dirfileres,optionfilefiname);
                   8555:   strcpy(optfileres,"vpl");
1.223     brouard  8556:   /* 1eme*/
1.238     brouard  8557:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
1.337     brouard  8558:     /* for (k1=1; k1<= m ; k1 ++){ /\* For each valid combination of covariate *\/ */
1.236     brouard  8559:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8560:        k1=TKresult[nres];
1.338     brouard  8561:        if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.238     brouard  8562:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.337     brouard  8563:        /* if(m != 1 && TKresult[nres]!= k1) */
                   8564:        /*   continue; */
1.238     brouard  8565:        /* We are interested in selected combination by the resultline */
1.246     brouard  8566:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  8567:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  8568:        strcpy(gplotlabel,"(");
1.337     brouard  8569:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8570:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8571:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8572: 
                   8573:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate k get corresponding value lv for combination k1 *\/ */
                   8574:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the value of the covariate corresponding to k1 combination *\\/ *\/ */
                   8575:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8576:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8577:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8578:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8579:        /*   vlv= nbcode[Tvaraff[k]][lv]; /\* vlv is the value of the covariate lv, 0 or 1 *\/ */
                   8580:        /*   /\* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv *\/ */
                   8581:        /*   /\* printf(" V%d=%d ",Tvaraff[k],vlv); *\/ */
                   8582:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8583:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8584:        /* } */
                   8585:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8586:        /*   /\* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); *\/ */
                   8587:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8588:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.264     brouard  8589:        }
                   8590:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  8591:        /* printf("\n#\n"); */
1.238     brouard  8592:        fprintf(ficgp,"\n#\n");
                   8593:        if(invalidvarcomb[k1]){
1.260     brouard  8594:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  8595:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8596:          continue;
                   8597:        }
1.235     brouard  8598:       
1.241     brouard  8599:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   8600:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  8601:        /* 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  8602:        fprintf(ficgp,"set title \"Alive state %d %s model=1+age+%s\" font \"Helvetica,12\"\n",cpt,gplotlabel,model);
1.260     brouard  8603:        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);
                   8604:        /* 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); */
                   8605:       /* k1-1 error should be nres-1*/
1.238     brouard  8606:        for (i=1; i<= nlstate ; i ++) {
                   8607:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8608:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   8609:        }
1.288     brouard  8610:        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  8611:        for (i=1; i<= nlstate ; i ++) {
                   8612:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8613:          else fprintf(ficgp," %%*lf (%%*lf)");
                   8614:        } 
1.260     brouard  8615:        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  8616:        for (i=1; i<= nlstate ; i ++) {
                   8617:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8618:          else fprintf(ficgp," %%*lf (%%*lf)");
                   8619:        }  
1.265     brouard  8620:        /* 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)); */
                   8621:        
                   8622:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   8623:         if(cptcoveff ==0){
1.271     brouard  8624:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  8625:        }else{
                   8626:          kl=0;
                   8627:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  8628:            /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8629:            lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.265     brouard  8630:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8631:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8632:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8633:            vlv= nbcode[Tvaraff[k]][lv];
                   8634:            kl++;
                   8635:            /* 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 *\/ */
                   8636:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8637:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8638:            /* ''  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*/
                   8639:            if(k==cptcoveff){
                   8640:              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], \
                   8641:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   8642:            }else{
                   8643:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   8644:              kl++;
                   8645:            }
                   8646:          } /* end covariate */
                   8647:        } /* end if no covariate */
                   8648: 
1.296     brouard  8649:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  8650:          /* 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  8651:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  8652:          if(cptcoveff ==0){
1.245     brouard  8653:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  8654:          }else{
                   8655:            kl=0;
                   8656:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  8657:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8658:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.238     brouard  8659:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8660:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8661:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8662:              /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8663:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.223     brouard  8664:              kl++;
1.238     brouard  8665:              /* 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 *\/ */
                   8666:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8667:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8668:              /* ''  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*/
                   8669:              if(k==cptcoveff){
1.245     brouard  8670:                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  8671:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  8672:              }else{
1.332     brouard  8673:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]);
1.238     brouard  8674:                kl++;
                   8675:              }
                   8676:            } /* end covariate */
                   8677:          } /* end if no covariate */
1.296     brouard  8678:          if(prevbcast == 1){
1.268     brouard  8679:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   8680:            /* k1-1 error should be nres-1*/
                   8681:            for (i=1; i<= nlstate ; i ++) {
                   8682:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8683:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   8684:            }
1.271     brouard  8685:            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  8686:            for (i=1; i<= nlstate ; i ++) {
                   8687:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8688:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8689:            } 
1.276     brouard  8690:            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  8691:            for (i=1; i<= nlstate ; i ++) {
                   8692:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8693:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8694:            } 
1.274     brouard  8695:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  8696:          } /* end if backprojcast */
1.296     brouard  8697:        } /* end if prevbcast */
1.276     brouard  8698:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   8699:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  8700:       } /* nres */
1.337     brouard  8701:     /* } /\* k1 *\/ */
1.201     brouard  8702:   } /* cpt */
1.235     brouard  8703: 
                   8704:   
1.126     brouard  8705:   /*2 eme*/
1.337     brouard  8706:   /* for (k1=1; k1<= m ; k1 ++){   */
1.238     brouard  8707:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8708:       k1=TKresult[nres];
1.338     brouard  8709:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8710:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8711:       /*       continue; */
1.238     brouard  8712:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  8713:       strcpy(gplotlabel,"(");
1.337     brouard  8714:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8715:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8716:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8717:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8718:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8719:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8720:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8721:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8722:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8723:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8724:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8725:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8726:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8727:       /* } */
                   8728:       /* /\* for(k=1; k <= ncovds; k++){ *\/ */
                   8729:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8730:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8731:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8732:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  8733:       }
1.264     brouard  8734:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8735:       fprintf(ficgp,"\n#\n");
1.223     brouard  8736:       if(invalidvarcomb[k1]){
                   8737:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8738:        continue;
                   8739:       }
1.219     brouard  8740:                        
1.241     brouard  8741:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  8742:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  8743:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   8744:        if(vpopbased==0){
1.238     brouard  8745:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  8746:        }else
1.238     brouard  8747:          fprintf(ficgp,"\nreplot ");
                   8748:        for (i=1; i<= nlstate+1 ; i ++) {
                   8749:          k=2*i;
1.261     brouard  8750:          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  8751:          for (j=1; j<= nlstate+1 ; j ++) {
                   8752:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8753:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8754:          }   
                   8755:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   8756:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
1.261     brouard  8757:          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  8758:          for (j=1; j<= nlstate+1 ; j ++) {
                   8759:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8760:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8761:          }   
                   8762:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  8763:          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  8764:          for (j=1; j<= nlstate+1 ; j ++) {
                   8765:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8766:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8767:          }   
                   8768:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   8769:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   8770:        } /* state */
                   8771:       } /* vpopbased */
1.264     brouard  8772:       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  8773:     } /* end nres */
1.337     brouard  8774:   /* } /\* k1 end 2 eme*\/ */
1.238     brouard  8775:        
                   8776:        
                   8777:   /*3eme*/
1.337     brouard  8778:   /* for (k1=1; k1<= m ; k1 ++){ */
1.238     brouard  8779:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8780:       k1=TKresult[nres];
1.338     brouard  8781:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8782:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8783:       /*       continue; */
1.238     brouard  8784: 
1.332     brouard  8785:       for (cpt=1; cpt<= nlstate ; cpt ++) { /* Fragile no verification of covariate values */
1.261     brouard  8786:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  8787:        strcpy(gplotlabel,"(");
1.337     brouard  8788:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8789:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8790:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8791:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8792:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8793:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8794:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8795:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8796:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8797:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8798:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8799:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8800:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8801:        /* } */
                   8802:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8803:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   8804:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   8805:        }
1.264     brouard  8806:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8807:        fprintf(ficgp,"\n#\n");
                   8808:        if(invalidvarcomb[k1]){
                   8809:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8810:          continue;
                   8811:        }
                   8812:                        
                   8813:        /*       k=2+nlstate*(2*cpt-2); */
                   8814:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  8815:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  8816:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  8817:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  8818: 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  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);
                   8822:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8823:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8824:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  8825:                                
1.238     brouard  8826:        */
                   8827:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  8828:          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  8829:          /*    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  8830:                                
1.238     brouard  8831:        } 
1.261     brouard  8832:        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  8833:       }
1.264     brouard  8834:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  8835:     } /* end nres */
1.337     brouard  8836:   /* } /\* end kl 3eme *\/ */
1.126     brouard  8837:   
1.223     brouard  8838:   /* 4eme */
1.201     brouard  8839:   /* Survival functions (period) from state i in state j by initial state i */
1.337     brouard  8840:   /* for (k1=1; k1<=m; k1++){    /\* For each covariate and each value *\/ */
1.238     brouard  8841:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8842:       k1=TKresult[nres];
1.338     brouard  8843:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8844:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8845:       /*       continue; */
1.238     brouard  8846:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  8847:        strcpy(gplotlabel,"(");
1.337     brouard  8848:        fprintf(ficgp,"\n#\n#\n# Survival functions in state %d : 'LIJ_' files, cov=%d state=%d", cpt, k1, cpt);
                   8849:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8850:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8851:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8852:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8853:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8854:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8855:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8856:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8857:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8858:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8859:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8860:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8861:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8862:        /* } */
                   8863:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8864:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8865:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  8866:        }       
1.264     brouard  8867:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8868:        fprintf(ficgp,"\n#\n");
                   8869:        if(invalidvarcomb[k1]){
                   8870:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8871:          continue;
1.223     brouard  8872:        }
1.238     brouard  8873:       
1.241     brouard  8874:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  8875:        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  8876:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8877: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8878:        k=3;
                   8879:        for (i=1; i<= nlstate ; i ++){
                   8880:          if(i==1){
                   8881:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8882:          }else{
                   8883:            fprintf(ficgp,", '' ");
                   8884:          }
                   8885:          l=(nlstate+ndeath)*(i-1)+1;
                   8886:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8887:          for (j=2; j<= nlstate+ndeath ; j ++)
                   8888:            fprintf(ficgp,"+$%d",k+l+j-1);
                   8889:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   8890:        } /* nlstate */
1.264     brouard  8891:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8892:       } /* end cpt state*/ 
                   8893:     } /* end nres */
1.337     brouard  8894:   /* } /\* end covariate k1 *\/   */
1.238     brouard  8895: 
1.220     brouard  8896: /* 5eme */
1.201     brouard  8897:   /* Survival functions (period) from state i in state j by final state j */
1.337     brouard  8898:   /* for (k1=1; k1<= m ; k1++){ /\* For each covariate combination if any *\/ */
1.238     brouard  8899:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8900:       k1=TKresult[nres];
1.338     brouard  8901:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8902:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8903:       /*       continue; */
1.238     brouard  8904:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  8905:        strcpy(gplotlabel,"(");
1.238     brouard  8906:        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  8907:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8908:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8909:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8910:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8911:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8912:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8913:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8914:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8915:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8916:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8917:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8918:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8919:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8920:        /* } */
                   8921:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8922:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8923:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  8924:        }       
1.264     brouard  8925:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8926:        fprintf(ficgp,"\n#\n");
                   8927:        if(invalidvarcomb[k1]){
                   8928:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8929:          continue;
                   8930:        }
1.227     brouard  8931:       
1.241     brouard  8932:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  8933:        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  8934:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8935: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8936:        k=3;
                   8937:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8938:          if(j==1)
                   8939:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8940:          else
                   8941:            fprintf(ficgp,", '' ");
                   8942:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8943:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   8944:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   8945:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   8946:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   8947:        } /* nlstate */
                   8948:        fprintf(ficgp,", '' ");
                   8949:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   8950:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8951:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8952:          if(j < nlstate)
                   8953:            fprintf(ficgp,"$%d +",k+l);
                   8954:          else
                   8955:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   8956:        }
1.264     brouard  8957:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8958:       } /* end cpt state*/ 
1.337     brouard  8959:     /* } /\* end covariate *\/   */
1.238     brouard  8960:   } /* end nres */
1.227     brouard  8961:   
1.220     brouard  8962: /* 6eme */
1.202     brouard  8963:   /* CV preval stable (period) for each covariate */
1.337     brouard  8964:   /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8965:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8966:      k1=TKresult[nres];
1.338     brouard  8967:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8968:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8969:      /*  continue; */
1.255     brouard  8970:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  8971:       strcpy(gplotlabel,"(");      
1.288     brouard  8972:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8973:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8974:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8975:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8976:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8977:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8978:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8979:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8980:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8981:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8982:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8983:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8984:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8985:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8986:       /* } */
                   8987:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8988:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8989:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8990:       }        
1.264     brouard  8991:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8992:       fprintf(ficgp,"\n#\n");
1.223     brouard  8993:       if(invalidvarcomb[k1]){
1.227     brouard  8994:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8995:        continue;
1.223     brouard  8996:       }
1.227     brouard  8997:       
1.241     brouard  8998:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  8999:       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  9000:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  9001: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  9002:       k=3; /* Offset */
1.255     brouard  9003:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  9004:        if(i==1)
                   9005:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   9006:        else
                   9007:          fprintf(ficgp,", '' ");
1.255     brouard  9008:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  9009:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   9010:        for (j=2; j<= nlstate ; j ++)
                   9011:          fprintf(ficgp,"+$%d",k+l+j-1);
                   9012:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  9013:       } /* nlstate */
1.264     brouard  9014:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  9015:     } /* end cpt state*/ 
                   9016:   } /* end covariate */  
1.227     brouard  9017:   
                   9018:   
1.220     brouard  9019: /* 7eme */
1.296     brouard  9020:   if(prevbcast == 1){
1.288     brouard  9021:     /* CV backward prevalence  for each covariate */
1.337     brouard  9022:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  9023:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  9024:       k1=TKresult[nres];
1.338     brouard  9025:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9026:       /* if(m != 1 && TKresult[nres]!= k1) */
                   9027:       /*       continue; */
1.268     brouard  9028:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  9029:        strcpy(gplotlabel,"(");      
1.288     brouard  9030:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  9031:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9032:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9033:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9034:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   9035:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   9036:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   9037:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9038:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9039:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9040:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9041:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9042:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9043:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9044:        /* } */
                   9045:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9046:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9047:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  9048:        }       
1.264     brouard  9049:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  9050:        fprintf(ficgp,"\n#\n");
                   9051:        if(invalidvarcomb[k1]){
                   9052:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   9053:          continue;
                   9054:        }
                   9055:        
1.241     brouard  9056:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  9057:        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  9058:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  9059: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  9060:        k=3; /* Offset */
1.268     brouard  9061:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  9062:          if(i==1)
                   9063:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   9064:          else
                   9065:            fprintf(ficgp,", '' ");
                   9066:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  9067:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.324     brouard  9068:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   9069:          /* 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  9070:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  9071:          /* for (j=2; j<= nlstate ; j ++) */
                   9072:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   9073:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  9074:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  9075:        } /* nlstate */
1.264     brouard  9076:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  9077:       } /* end cpt state*/ 
                   9078:     } /* end covariate */  
1.296     brouard  9079:   } /* End if prevbcast */
1.218     brouard  9080:   
1.223     brouard  9081:   /* 8eme */
1.218     brouard  9082:   if(prevfcast==1){
1.288     brouard  9083:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  9084:     
1.337     brouard  9085:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  9086:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  9087:       k1=TKresult[nres];
1.338     brouard  9088:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9089:       /* if(m != 1 && TKresult[nres]!= k1) */
                   9090:       /*       continue; */
1.211     brouard  9091:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  9092:        strcpy(gplotlabel,"(");      
1.288     brouard  9093:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  9094:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9095:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9096:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9097:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   9098:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   9099:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   9100:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9101:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9102:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9103:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9104:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9105:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9106:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9107:        /* } */
                   9108:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9109:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9110:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  9111:        }       
1.264     brouard  9112:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  9113:        fprintf(ficgp,"\n#\n");
                   9114:        if(invalidvarcomb[k1]){
                   9115:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   9116:          continue;
                   9117:        }
                   9118:        
                   9119:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  9120:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  9121:        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  9122:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  9123: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  9124: 
                   9125:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   9126:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9127:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9128:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  9129:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9130:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   9131:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9132:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  9133:          if(i==istart){
1.227     brouard  9134:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   9135:          }else{
                   9136:            fprintf(ficgp,",\\\n '' ");
                   9137:          }
                   9138:          if(cptcoveff ==0){ /* No covariate */
                   9139:            ioffset=2; /* Age is in 2 */
                   9140:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9141:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9142:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9143:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9144:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  9145:            if(i==nlstate+1){
1.270     brouard  9146:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  9147:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   9148:              fprintf(ficgp,",\\\n '' ");
                   9149:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  9150:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  9151:                     offyear,                           \
1.268     brouard  9152:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  9153:            }else
1.227     brouard  9154:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   9155:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   9156:          }else{ /* more than 2 covariates */
1.270     brouard  9157:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   9158:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9159:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   9160:            iyearc=ioffset-1;
                   9161:            iagec=ioffset;
1.227     brouard  9162:            fprintf(ficgp," u %d:(",ioffset); 
                   9163:            kl=0;
                   9164:            strcpy(gplotcondition,"(");
1.351     brouard  9165:            /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
1.332     brouard  9166:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
1.351     brouard  9167:            for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9168:              /* lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   9169:              lv=Tvresult[nres][k];
                   9170:              vlv=TinvDoQresult[nres][Tvresult[nres][k]];
1.227     brouard  9171:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   9172:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   9173:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  9174:              /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
1.351     brouard  9175:              /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
1.227     brouard  9176:              kl++;
1.351     brouard  9177:              /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
                   9178:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,lv, kl+1, vlv );
1.227     brouard  9179:              kl++;
1.351     brouard  9180:              if(k <cptcovs && cptcovs>1)
1.227     brouard  9181:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   9182:            }
                   9183:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   9184:            /* 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 *\/ */
                   9185:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   9186:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   9187:            /* ''  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*/
                   9188:            if(i==nlstate+1){
1.270     brouard  9189:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   9190:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  9191:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  9192:              fprintf(ficgp," u %d:(",iagec); 
                   9193:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   9194:                      iyearc, iagec, offyear,                           \
                   9195:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  9196: /*  '' 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  9197:            }else{
                   9198:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   9199:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   9200:            }
                   9201:          } /* end if covariate */
                   9202:        } /* nlstate */
1.264     brouard  9203:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  9204:       } /* end cpt state*/
                   9205:     } /* end covariate */
                   9206:   } /* End if prevfcast */
1.227     brouard  9207:   
1.296     brouard  9208:   if(prevbcast==1){
1.268     brouard  9209:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   9210:     
1.337     brouard  9211:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.268     brouard  9212:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  9213:      k1=TKresult[nres];
1.338     brouard  9214:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9215:        /* if(m != 1 && TKresult[nres]!= k1) */
                   9216:        /*      continue; */
1.268     brouard  9217:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   9218:        strcpy(gplotlabel,"(");      
                   9219:        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  9220:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9221:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9222:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9223:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   9224:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   9225:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9226:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9227:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9228:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9229:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9230:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9231:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9232:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9233:        /* } */
                   9234:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9235:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9236:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.268     brouard  9237:        }       
                   9238:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   9239:        fprintf(ficgp,"\n#\n");
                   9240:        if(invalidvarcomb[k1]){
                   9241:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   9242:          continue;
                   9243:        }
                   9244:        
                   9245:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   9246:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   9247:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   9248:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   9249: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   9250: 
                   9251:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   9252:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9253:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9254:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   9255:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9256:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   9257:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9258:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   9259:          if(i==istart){
                   9260:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   9261:          }else{
                   9262:            fprintf(ficgp,",\\\n '' ");
                   9263:          }
1.351     brouard  9264:          /* if(cptcoveff ==0){ /\* No covariate *\/ */
                   9265:          if(cptcovs ==0){ /* No covariate */
1.268     brouard  9266:            ioffset=2; /* Age is in 2 */
                   9267:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9268:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9269:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9270:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9271:            fprintf(ficgp," u %d:(", ioffset); 
                   9272:            if(i==nlstate+1){
1.270     brouard  9273:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  9274:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   9275:              fprintf(ficgp,",\\\n '' ");
                   9276:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  9277:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  9278:                     offbyear,                          \
                   9279:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   9280:            }else
                   9281:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   9282:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   9283:          }else{ /* more than 2 covariates */
1.270     brouard  9284:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   9285:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9286:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   9287:            iyearc=ioffset-1;
                   9288:            iagec=ioffset;
1.268     brouard  9289:            fprintf(ficgp," u %d:(",ioffset); 
                   9290:            kl=0;
                   9291:            strcpy(gplotcondition,"(");
1.337     brouard  9292:            for (k=1; k<=cptcovs; k++){    /* For each covariate k of the resultline, get corresponding value lv for combination k1 */
1.338     brouard  9293:              if(Dummy[modelresult[nres][k]]==0){  /* To be verified */
1.337     brouard  9294:                /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
                   9295:                /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9296:                /* lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9297:                lv=Tvresult[nres][k];
                   9298:                vlv=TinvDoQresult[nres][Tvresult[nres][k]];
                   9299:                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   9300:                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   9301:                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   9302:                /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   9303:                /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9304:                kl++;
                   9305:                /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
                   9306:                sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%lg " ,kl,Tvresult[nres][k], kl+1,TinvDoQresult[nres][Tvresult[nres][k]]);
                   9307:                kl++;
1.338     brouard  9308:                if(k <cptcovs && cptcovs>1)
1.337     brouard  9309:                  sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   9310:              }
1.268     brouard  9311:            }
                   9312:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   9313:            /* 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 *\/ */
                   9314:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   9315:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   9316:            /* ''  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*/
                   9317:            if(i==nlstate+1){
1.270     brouard  9318:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   9319:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  9320:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  9321:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  9322:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  9323:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   9324:                      iyearc,iagec,offbyear,                            \
                   9325:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  9326: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   9327:            }else{
                   9328:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   9329:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   9330:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   9331:            }
                   9332:          } /* end if covariate */
                   9333:        } /* nlstate */
                   9334:        fprintf(ficgp,"\nset out; unset label;\n");
                   9335:       } /* end cpt state*/
                   9336:     } /* end covariate */
1.296     brouard  9337:   } /* End if prevbcast */
1.268     brouard  9338:   
1.227     brouard  9339:   
1.238     brouard  9340:   /* 9eme writing MLE parameters */
                   9341:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  9342:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  9343:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  9344:     for(k=1; k <=(nlstate+ndeath); k++){
                   9345:       if (k != i) {
1.227     brouard  9346:        fprintf(ficgp,"#   current state %d\n",k);
                   9347:        for(j=1; j <=ncovmodel; j++){
                   9348:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   9349:          jk++; 
                   9350:        }
                   9351:        fprintf(ficgp,"\n");
1.126     brouard  9352:       }
                   9353:     }
1.223     brouard  9354:   }
1.187     brouard  9355:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  9356:   
1.145     brouard  9357:   /*goto avoid;*/
1.238     brouard  9358:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   9359:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  9360:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   9361:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   9362:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   9363:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   9364:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9365:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   9366:   fprintf(ficgp,"# p11=1/(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,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   9369:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9370:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   9371:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   9372:   fprintf(ficgp,"#\n");
1.223     brouard  9373:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  9374:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.338     brouard  9375:     fprintf(ficgp,"#model=1+age+%s \n",model);
1.238     brouard  9376:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.351     brouard  9377:     /* fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/\* to be checked *\/ */
                   9378:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcovs,m);/* to be checked */
1.337     brouard  9379:     /* for(k1=1; k1 <=m; k1++)  /\* For each combination of covariate *\/ */
1.237     brouard  9380:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  9381:      /* k1=nres; */
1.338     brouard  9382:       k1=TKresult[nres];
                   9383:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9384:       fprintf(ficgp,"\n\n# Resultline k1=%d ",k1);
1.264     brouard  9385:       strcpy(gplotlabel,"(");
1.276     brouard  9386:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.337     brouard  9387:       for (k=1; k<=cptcovs; k++){  /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   9388:        /* for each resultline nres, and position k, Tvresult[nres][k] gives the name of the variable and
                   9389:           TinvDoQresult[nres][Tvresult[nres][k]] gives its value double or integer) */
                   9390:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9391:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9392:       }
                   9393:       /* if(m != 1 && TKresult[nres]!= k1) */
                   9394:       /*       continue; */
                   9395:       /* fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1); */
                   9396:       /* strcpy(gplotlabel,"("); */
                   9397:       /* /\*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*\/ */
                   9398:       /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   9399:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   9400:       /*       lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9401:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9402:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9403:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9404:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9405:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9406:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9407:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9408:       /* } */
                   9409:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9410:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9411:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9412:       /* }      */
1.264     brouard  9413:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  9414:       fprintf(ficgp,"\n#\n");
1.264     brouard  9415:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  9416:       fprintf(ficgp,"\nset key outside ");
                   9417:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   9418:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  9419:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   9420:       if (ng==1){
                   9421:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   9422:        fprintf(ficgp,"\nunset log y");
                   9423:       }else if (ng==2){
                   9424:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   9425:        fprintf(ficgp,"\nset log y");
                   9426:       }else if (ng==3){
                   9427:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   9428:        fprintf(ficgp,"\nset log y");
                   9429:       }else
                   9430:        fprintf(ficgp,"\nunset title ");
                   9431:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   9432:       i=1;
                   9433:       for(k2=1; k2<=nlstate; k2++) {
                   9434:        k3=i;
                   9435:        for(k=1; k<=(nlstate+ndeath); k++) {
                   9436:          if (k != k2){
                   9437:            switch( ng) {
                   9438:            case 1:
                   9439:              if(nagesqr==0)
                   9440:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   9441:              else /* nagesqr =1 */
                   9442:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   9443:              break;
                   9444:            case 2: /* ng=2 */
                   9445:              if(nagesqr==0)
                   9446:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   9447:              else /* nagesqr =1 */
                   9448:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   9449:              break;
                   9450:            case 3:
                   9451:              if(nagesqr==0)
                   9452:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   9453:              else /* nagesqr =1 */
                   9454:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   9455:              break;
                   9456:            }
                   9457:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  9458:            ijp=1; /* product no age */
                   9459:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   9460:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  9461:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.329     brouard  9462:              switch(Typevar[j]){
                   9463:              case 1:
                   9464:                if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   9465:                  if(j==Tage[ij]) { /* Product by age  To be looked at!!*//* Bug valgrind */
                   9466:                    if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   9467:                      if(DummyV[j]==0){/* Bug valgrind */
                   9468:                        fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   9469:                      }else{ /* quantitative */
                   9470:                        fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   9471:                        /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9472:                      }
                   9473:                      ij++;
1.268     brouard  9474:                    }
1.237     brouard  9475:                  }
1.329     brouard  9476:                }
                   9477:                break;
                   9478:              case 2:
                   9479:                if(cptcovprod >0){
                   9480:                  if(j==Tprod[ijp]) { /* */ 
                   9481:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9482:                    if(ijp <=cptcovprod) { /* Product */
                   9483:                      if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   9484:                        if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   9485:                          /* 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)]); */
                   9486:                          fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9487:                        }else{ /* Vn is dummy and Vm is quanti */
                   9488:                          /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9489:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9490:                        }
                   9491:                      }else{ /* Vn*Vm Vn is quanti */
                   9492:                        if(DummyV[Tvard[ijp][2]]==0){
                   9493:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   9494:                        }else{ /* Both quanti */
                   9495:                          fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9496:                        }
1.268     brouard  9497:                      }
1.329     brouard  9498:                      ijp++;
1.237     brouard  9499:                    }
1.329     brouard  9500:                  } /* end Tprod */
                   9501:                }
                   9502:                break;
1.349     brouard  9503:              case 3:
                   9504:                if(cptcovdageprod >0){
                   9505:                  /* if(j==Tprod[ijp]) { */ /* not necessary */ 
                   9506:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
1.350     brouard  9507:                    if(ijp <=cptcovprod) { /* Product Vn*Vm and age*VN*Vm*/
                   9508:                      if(DummyV[Tvardk[ijp][1]]==0){/* Vn is dummy */
                   9509:                        if(DummyV[Tvardk[ijp][2]]==0){/* Vn and Vm are dummy */
1.349     brouard  9510:                          /* 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)]); */
                   9511:                          fprintf(ficgp,"+p%d*%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9512:                        }else{ /* Vn is dummy and Vm is quanti */
                   9513:                          /* 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  9514:                          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  9515:                        }
1.350     brouard  9516:                      }else{ /* age* Vn*Vm Vn is quanti HERE */
1.349     brouard  9517:                        if(DummyV[Tvard[ijp][2]]==0){
1.350     brouard  9518:                          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  9519:                        }else{ /* Both quanti */
1.350     brouard  9520:                          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  9521:                        }
                   9522:                      }
                   9523:                      ijp++;
                   9524:                    }
                   9525:                    /* } */ /* end Tprod */
                   9526:                }
                   9527:                break;
1.329     brouard  9528:              case 0:
                   9529:                /* simple covariate */
1.264     brouard  9530:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  9531:                if(Dummy[j]==0){
                   9532:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   9533:                }else{ /* quantitative */
                   9534:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  9535:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  9536:                }
1.329     brouard  9537:               /* end simple */
                   9538:                break;
                   9539:              default:
                   9540:                break;
                   9541:              } /* end switch */
1.237     brouard  9542:            } /* end j */
1.329     brouard  9543:          }else{ /* k=k2 */
                   9544:            if(ng !=1 ){ /* For logit formula of log p11 is more difficult to get */
                   9545:              fprintf(ficgp," (1.");i=i-ncovmodel;
                   9546:            }else
                   9547:              i=i-ncovmodel;
1.223     brouard  9548:          }
1.227     brouard  9549:          
1.223     brouard  9550:          if(ng != 1){
                   9551:            fprintf(ficgp,")/(1");
1.227     brouard  9552:            
1.264     brouard  9553:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  9554:              if(nagesqr==0)
1.264     brouard  9555:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  9556:              else /* nagesqr =1 */
1.264     brouard  9557:                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  9558:               
1.223     brouard  9559:              ij=1;
1.329     brouard  9560:              ijp=1;
                   9561:              /* for(j=3; j <=ncovmodel-nagesqr; j++){ */
                   9562:              for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
                   9563:                switch(Typevar[j]){
                   9564:                case 1:
                   9565:                  if(cptcovage >0){ 
                   9566:                    if(j==Tage[ij]) { /* Bug valgrind */
                   9567:                      if(ij <=cptcovage) { /* Bug valgrind */
                   9568:                        if(DummyV[j]==0){/* Bug valgrind */
                   9569:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]); */
                   9570:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,nbcode[Tvar[j]][codtabm(k1,j)]); */
                   9571:                          fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]);
                   9572:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);; */
                   9573:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9574:                        }else{ /* quantitative */
                   9575:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   9576:                          fprintf(ficgp,"+p%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   9577:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   9578:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9579:                        }
                   9580:                        ij++;
                   9581:                      }
                   9582:                    }
                   9583:                  }
                   9584:                  break;
                   9585:                case 2:
                   9586:                  if(cptcovprod >0){
                   9587:                    if(j==Tprod[ijp]) { /* */ 
                   9588:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9589:                      if(ijp <=cptcovprod) { /* Product */
                   9590:                        if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   9591:                          if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   9592:                            /* 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)]); */
                   9593:                            fprintf(ficgp,"+p%d*%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9594:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   9595:                          }else{ /* Vn is dummy and Vm is quanti */
                   9596:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9597:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9598:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9599:                          }
                   9600:                        }else{ /* Vn*Vm Vn is quanti */
                   9601:                          if(DummyV[Tvard[ijp][2]]==0){
                   9602:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   9603:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   9604:                          }else{ /* Both quanti */
                   9605:                            fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9606:                            /* fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9607:                          } 
                   9608:                        }
                   9609:                        ijp++;
                   9610:                      }
                   9611:                    } /* end Tprod */
                   9612:                  } /* end if */
                   9613:                  break;
1.349     brouard  9614:                case 3:
                   9615:                  if(cptcovdageprod >0){
                   9616:                    /* if(j==Tprod[ijp]) { /\* *\/  */
                   9617:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9618:                      if(ijp <=cptcovprod) { /* Product */
1.350     brouard  9619:                        if(DummyV[Tvardk[ijp][1]]==0){/* Vn is dummy */
                   9620:                          if(DummyV[Tvardk[ijp][2]]==0){/* Vn and Vm are dummy */
1.349     brouard  9621:                            /* 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  9622:                            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  9623:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   9624:                          }else{ /* Vn is dummy and Vm is quanti */
                   9625:                            /* 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  9626:                            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  9627:                            /* fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9628:                          }
                   9629:                        }else{ /* Vn*Vm Vn is quanti */
1.350     brouard  9630:                          if(DummyV[Tvardk[ijp][2]]==0){
                   9631:                            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  9632:                            /* fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   9633:                          }else{ /* Both quanti */
1.350     brouard  9634:                            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  9635:                            /* fprintf(ficgp,"+p%d*%f*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9636:                          } 
                   9637:                        }
                   9638:                        ijp++;
                   9639:                      }
                   9640:                    /* } /\* end Tprod *\/ */
                   9641:                  } /* end if */
                   9642:                  break;
1.329     brouard  9643:                case 0: 
                   9644:                  /* simple covariate */
                   9645:                  /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
                   9646:                  if(Dummy[j]==0){
                   9647:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   9648:                    fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]); /*  */
                   9649:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   9650:                  }else{ /* quantitative */
                   9651:                    fprintf(ficgp,"+p%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* */
                   9652:                    /* fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* *\/ */
                   9653:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9654:                  }
                   9655:                  /* end simple */
                   9656:                  /* fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);/\* Valgrind bug nbcode *\/ */
                   9657:                  break;
                   9658:                default:
                   9659:                  break;
                   9660:                } /* end switch */
1.223     brouard  9661:              }
                   9662:              fprintf(ficgp,")");
                   9663:            }
                   9664:            fprintf(ficgp,")");
                   9665:            if(ng ==2)
1.276     brouard  9666:              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  9667:            else /* ng= 3 */
1.276     brouard  9668:              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  9669:           }else{ /* end ng <> 1 */
1.223     brouard  9670:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  9671:              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  9672:          }
                   9673:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   9674:            fprintf(ficgp,",");
                   9675:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   9676:            fprintf(ficgp,",");
                   9677:          i=i+ncovmodel;
                   9678:        } /* end k */
                   9679:       } /* end k2 */
1.276     brouard  9680:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   9681:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.337     brouard  9682:     } /* end resultline */
1.223     brouard  9683:   } /* end ng */
                   9684:   /* avoid: */
                   9685:   fflush(ficgp); 
1.126     brouard  9686: }  /* end gnuplot */
                   9687: 
                   9688: 
                   9689: /*************** Moving average **************/
1.219     brouard  9690: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  9691:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  9692:    
1.222     brouard  9693:    int i, cpt, cptcod;
                   9694:    int modcovmax =1;
                   9695:    int mobilavrange, mob;
                   9696:    int iage=0;
1.288     brouard  9697:    int firstA1=0, firstA2=0;
1.222     brouard  9698: 
1.266     brouard  9699:    double sum=0., sumr=0.;
1.222     brouard  9700:    double age;
1.266     brouard  9701:    double *sumnewp, *sumnewm, *sumnewmr;
                   9702:    double *agemingood, *agemaxgood; 
                   9703:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  9704:   
                   9705:   
1.278     brouard  9706:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   9707:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  9708: 
                   9709:    sumnewp = vector(1,ncovcombmax);
                   9710:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  9711:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  9712:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  9713:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  9714:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  9715:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  9716: 
                   9717:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  9718:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  9719:      sumnewp[cptcod]=0.;
1.266     brouard  9720:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   9721:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  9722:    }
                   9723:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   9724:   
1.266     brouard  9725:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   9726:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  9727:      else mobilavrange=mobilav;
                   9728:      for (age=bage; age<=fage; age++)
                   9729:        for (i=1; i<=nlstate;i++)
                   9730:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   9731:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9732:      /* We keep the original values on the extreme ages bage, fage and for 
                   9733:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   9734:        we use a 5 terms etc. until the borders are no more concerned. 
                   9735:      */ 
                   9736:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   9737:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  9738:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   9739:           sumnewm[cptcod]=0.;
                   9740:           for (i=1; i<=nlstate;i++){
1.222     brouard  9741:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   9742:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   9743:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   9744:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   9745:             }
                   9746:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  9747:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9748:           } /* end i */
                   9749:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   9750:         } /* end cptcod */
1.222     brouard  9751:        }/* end age */
                   9752:      }/* end mob */
1.266     brouard  9753:    }else{
                   9754:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  9755:      return -1;
1.266     brouard  9756:    }
                   9757: 
                   9758:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  9759:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   9760:      if(invalidvarcomb[cptcod]){
                   9761:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   9762:        continue;
                   9763:      }
1.219     brouard  9764: 
1.266     brouard  9765:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   9766:        sumnewm[cptcod]=0.;
                   9767:        sumnewmr[cptcod]=0.;
                   9768:        for (i=1; i<=nlstate;i++){
                   9769:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9770:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9771:        }
                   9772:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9773:         agemingoodr[cptcod]=age;
                   9774:        }
                   9775:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9776:           agemingood[cptcod]=age;
                   9777:        }
                   9778:      } /* age */
                   9779:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  9780:        sumnewm[cptcod]=0.;
1.266     brouard  9781:        sumnewmr[cptcod]=0.;
1.222     brouard  9782:        for (i=1; i<=nlstate;i++){
                   9783:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9784:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9785:        }
                   9786:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9787:         agemaxgoodr[cptcod]=age;
1.222     brouard  9788:        }
                   9789:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  9790:         agemaxgood[cptcod]=age;
                   9791:        }
                   9792:      } /* age */
                   9793:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   9794:      /* but they will change */
1.288     brouard  9795:      firstA1=0;firstA2=0;
1.266     brouard  9796:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   9797:        sumnewm[cptcod]=0.;
                   9798:        sumnewmr[cptcod]=0.;
                   9799:        for (i=1; i<=nlstate;i++){
                   9800:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9801:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9802:        }
                   9803:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9804:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9805:           agemaxgoodr[cptcod]=age;  /* age min */
                   9806:           for (i=1; i<=nlstate;i++)
                   9807:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9808:         }else{ /* bad we change the value with the values of good ages */
                   9809:           for (i=1; i<=nlstate;i++){
                   9810:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   9811:           } /* i */
                   9812:         } /* end bad */
                   9813:        }else{
                   9814:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9815:           agemaxgood[cptcod]=age;
                   9816:         }else{ /* bad we change the value with the values of good ages */
                   9817:           for (i=1; i<=nlstate;i++){
                   9818:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   9819:           } /* i */
                   9820:         } /* end bad */
                   9821:        }/* end else */
                   9822:        sum=0.;sumr=0.;
                   9823:        for (i=1; i<=nlstate;i++){
                   9824:         sum+=mobaverage[(int)age][i][cptcod];
                   9825:         sumr+=probs[(int)age][i][cptcod];
                   9826:        }
                   9827:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  9828:         if(!firstA1){
                   9829:           firstA1=1;
                   9830:           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);
                   9831:         }
                   9832:         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  9833:        } /* end bad */
                   9834:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9835:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  9836:         if(!firstA2){
                   9837:           firstA2=1;
                   9838:           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);
                   9839:         }
                   9840:         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  9841:        } /* end bad */
                   9842:      }/* age */
1.266     brouard  9843: 
                   9844:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  9845:        sumnewm[cptcod]=0.;
1.266     brouard  9846:        sumnewmr[cptcod]=0.;
1.222     brouard  9847:        for (i=1; i<=nlstate;i++){
                   9848:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9849:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9850:        } 
                   9851:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9852:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   9853:           agemingoodr[cptcod]=age;
                   9854:           for (i=1; i<=nlstate;i++)
                   9855:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9856:         }else{ /* bad we change the value with the values of good ages */
                   9857:           for (i=1; i<=nlstate;i++){
                   9858:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   9859:           } /* i */
                   9860:         } /* end bad */
                   9861:        }else{
                   9862:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9863:           agemingood[cptcod]=age;
                   9864:         }else{ /* bad */
                   9865:           for (i=1; i<=nlstate;i++){
                   9866:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   9867:           } /* i */
                   9868:         } /* end bad */
                   9869:        }/* end else */
                   9870:        sum=0.;sumr=0.;
                   9871:        for (i=1; i<=nlstate;i++){
                   9872:         sum+=mobaverage[(int)age][i][cptcod];
                   9873:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  9874:        }
1.266     brouard  9875:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  9876:         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  9877:        } /* end bad */
                   9878:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9879:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  9880:         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  9881:        } /* end bad */
                   9882:      }/* age */
1.266     brouard  9883: 
1.222     brouard  9884:                
                   9885:      for (age=bage; age<=fage; age++){
1.235     brouard  9886:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  9887:        sumnewp[cptcod]=0.;
                   9888:        sumnewm[cptcod]=0.;
                   9889:        for (i=1; i<=nlstate;i++){
                   9890:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   9891:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9892:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   9893:        }
                   9894:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   9895:      }
                   9896:      /* printf("\n"); */
                   9897:      /* } */
1.266     brouard  9898: 
1.222     brouard  9899:      /* brutal averaging */
1.266     brouard  9900:      /* for (i=1; i<=nlstate;i++){ */
                   9901:      /*   for (age=1; age<=bage; age++){ */
                   9902:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   9903:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9904:      /*   }     */
                   9905:      /*   for (age=fage; age<=AGESUP; age++){ */
                   9906:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   9907:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9908:      /*   } */
                   9909:      /* } /\* end i status *\/ */
                   9910:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   9911:      /*   for (age=1; age<=AGESUP; age++){ */
                   9912:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   9913:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   9914:      /*   } */
                   9915:      /* } */
1.222     brouard  9916:    }/* end cptcod */
1.266     brouard  9917:    free_vector(agemaxgoodr,1, ncovcombmax);
                   9918:    free_vector(agemaxgood,1, ncovcombmax);
                   9919:    free_vector(agemingood,1, ncovcombmax);
                   9920:    free_vector(agemingoodr,1, ncovcombmax);
                   9921:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  9922:    free_vector(sumnewm,1, ncovcombmax);
                   9923:    free_vector(sumnewp,1, ncovcombmax);
                   9924:    return 0;
                   9925:  }/* End movingaverage */
1.218     brouard  9926:  
1.126     brouard  9927: 
1.296     brouard  9928:  
1.126     brouard  9929: /************** Forecasting ******************/
1.296     brouard  9930: /* 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)*/
                   9931: 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){
                   9932:   /* dateintemean, mean date of interviews
                   9933:      dateprojd, year, month, day of starting projection 
                   9934:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  9935:      agemin, agemax range of age
                   9936:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   9937:   */
1.296     brouard  9938:   /* double anprojd, mprojd, jprojd; */
                   9939:   /* double anprojf, mprojf, jprojf; */
1.267     brouard  9940:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  9941:   double agec; /* generic age */
1.296     brouard  9942:   double agelim, ppij, yp,yp1,yp2;
1.126     brouard  9943:   double *popeffectif,*popcount;
                   9944:   double ***p3mat;
1.218     brouard  9945:   /* double ***mobaverage; */
1.126     brouard  9946:   char fileresf[FILENAMELENGTH];
                   9947: 
                   9948:   agelim=AGESUP;
1.211     brouard  9949:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9950:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9951:      We still use firstpass and lastpass as another selection.
                   9952:   */
1.214     brouard  9953:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9954:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  9955:  
1.201     brouard  9956:   strcpy(fileresf,"F_"); 
                   9957:   strcat(fileresf,fileresu);
1.126     brouard  9958:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   9959:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   9960:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   9961:   }
1.235     brouard  9962:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   9963:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  9964: 
1.225     brouard  9965:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  9966: 
                   9967: 
                   9968:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9969:   if (stepm<=12) stepsize=1;
                   9970:   if(estepm < stepm){
                   9971:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9972:   }
1.270     brouard  9973:   else{
                   9974:     hstepm=estepm;   
                   9975:   }
                   9976:   if(estepm > stepm){ /* Yes every two year */
                   9977:     stepsize=2;
                   9978:   }
1.296     brouard  9979:   hstepm=hstepm/stepm;
1.126     brouard  9980: 
1.296     brouard  9981:   
                   9982:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9983:   /*                              fractional in yp1 *\/ */
                   9984:   /* aintmean=yp; */
                   9985:   /* yp2=modf((yp1*12),&yp); */
                   9986:   /* mintmean=yp; */
                   9987:   /* yp1=modf((yp2*30.5),&yp); */
                   9988:   /* jintmean=yp; */
                   9989:   /* if(jintmean==0) jintmean=1; */
                   9990:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  9991: 
1.296     brouard  9992: 
                   9993:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   9994:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   9995:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.351     brouard  9996:   /* i1=pow(2,cptcoveff); */
                   9997:   /* if (cptcovn < 1){i1=1;} */
1.126     brouard  9998:   
1.296     brouard  9999:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  10000:   
                   10001:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  10002:   
1.126     brouard  10003: /*           if (h==(int)(YEARM*yearp)){ */
1.351     brouard  10004:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10005:     k=TKresult[nres];
                   10006:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   10007:     /*  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) *\/ */
                   10008:     /* if(i1 != 1 && TKresult[nres]!= k) */
                   10009:     /*   continue; */
                   10010:     /* if(invalidvarcomb[k]){ */
                   10011:     /*   printf("\nCombination (%d) projection ignored because no cases \n",k);  */
                   10012:     /*   continue; */
                   10013:     /* } */
1.227     brouard  10014:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
1.351     brouard  10015:     for(j=1;j<=cptcovs;j++){
                   10016:       /* for(j=1;j<=cptcoveff;j++) { */
                   10017:     /*   /\* fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); *\/ */
                   10018:     /*   fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10019:     /* } */
                   10020:     /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10021:     /*   fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   10022:     /* } */
                   10023:       fprintf(ficresf," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.235     brouard  10024:     }
1.351     brouard  10025:  
1.227     brouard  10026:     fprintf(ficresf," yearproj age");
                   10027:     for(j=1; j<=nlstate+ndeath;j++){ 
                   10028:       for(i=1; i<=nlstate;i++)               
                   10029:        fprintf(ficresf," p%d%d",i,j);
                   10030:       fprintf(ficresf," wp.%d",j);
                   10031:     }
1.296     brouard  10032:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  10033:       fprintf(ficresf,"\n");
1.296     brouard  10034:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  10035:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   10036:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  10037:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   10038:        nhstepm = nhstepm/hstepm; 
                   10039:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10040:        oldm=oldms;savm=savms;
1.268     brouard  10041:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  10042:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  10043:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  10044:        for (h=0; h<=nhstepm; h++){
                   10045:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  10046:            break;
                   10047:          }
                   10048:        }
                   10049:        fprintf(ficresf,"\n");
1.351     brouard  10050:        /* for(j=1;j<=cptcoveff;j++)  */
                   10051:        for(j=1;j<=cptcovs;j++) 
                   10052:          fprintf(ficresf,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.332     brouard  10053:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Tvaraff not correct *\/ */
1.351     brouard  10054:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* TnsdVar[Tvaraff]  correct *\/ */
1.296     brouard  10055:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  10056:        
                   10057:        for(j=1; j<=nlstate+ndeath;j++) {
                   10058:          ppij=0.;
                   10059:          for(i=1; i<=nlstate;i++) {
1.278     brouard  10060:            if (mobilav>=1)
                   10061:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   10062:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   10063:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   10064:            }
1.268     brouard  10065:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   10066:          } /* end i */
                   10067:          fprintf(ficresf," %.3f", ppij);
                   10068:        }/* end j */
1.227     brouard  10069:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10070:       } /* end agec */
1.266     brouard  10071:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   10072:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  10073:     } /* end yearp */
                   10074:   } /* end  k */
1.219     brouard  10075:        
1.126     brouard  10076:   fclose(ficresf);
1.215     brouard  10077:   printf("End of Computing forecasting \n");
                   10078:   fprintf(ficlog,"End of Computing forecasting\n");
                   10079: 
1.126     brouard  10080: }
                   10081: 
1.269     brouard  10082: /************** Back Forecasting ******************/
1.296     brouard  10083:  /* 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){ */
                   10084:  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){
                   10085:   /* back1, year, month, day of starting backprojection
1.267     brouard  10086:      agemin, agemax range of age
                   10087:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  10088:      anback2 year of end of backprojection (same day and month as back1).
                   10089:      prevacurrent and prev are prevalences.
1.267     brouard  10090:   */
                   10091:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   10092:   double agec; /* generic age */
1.302     brouard  10093:   double agelim, ppij, ppi, yp,yp1,yp2; /* ,jintmean,mintmean,aintmean;*/
1.267     brouard  10094:   double *popeffectif,*popcount;
                   10095:   double ***p3mat;
                   10096:   /* double ***mobaverage; */
                   10097:   char fileresfb[FILENAMELENGTH];
                   10098:  
1.268     brouard  10099:   agelim=AGEINF;
1.267     brouard  10100:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   10101:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   10102:      We still use firstpass and lastpass as another selection.
                   10103:   */
                   10104:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   10105:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   10106: 
                   10107:   /*Do we need to compute prevalence again?*/
                   10108: 
                   10109:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   10110:   
                   10111:   strcpy(fileresfb,"FB_");
                   10112:   strcat(fileresfb,fileresu);
                   10113:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   10114:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   10115:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   10116:   }
                   10117:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   10118:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   10119:   
                   10120:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   10121:   
                   10122:    
                   10123:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   10124:   if (stepm<=12) stepsize=1;
                   10125:   if(estepm < stepm){
                   10126:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   10127:   }
1.270     brouard  10128:   else{
                   10129:     hstepm=estepm;   
                   10130:   }
                   10131:   if(estepm >= stepm){ /* Yes every two year */
                   10132:     stepsize=2;
                   10133:   }
1.267     brouard  10134:   
                   10135:   hstepm=hstepm/stepm;
1.296     brouard  10136:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   10137:   /*                              fractional in yp1 *\/ */
                   10138:   /* aintmean=yp; */
                   10139:   /* yp2=modf((yp1*12),&yp); */
                   10140:   /* mintmean=yp; */
                   10141:   /* yp1=modf((yp2*30.5),&yp); */
                   10142:   /* jintmean=yp; */
                   10143:   /* if(jintmean==0) jintmean=1; */
                   10144:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  10145:   
1.351     brouard  10146:   /* i1=pow(2,cptcoveff); */
                   10147:   /* if (cptcovn < 1){i1=1;} */
1.267     brouard  10148:   
1.296     brouard  10149:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   10150:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  10151:   
                   10152:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   10153:   
1.351     brouard  10154:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10155:     k=TKresult[nres];
                   10156:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   10157:   /* for(k=1; k<=i1;k++){ */
                   10158:   /*   if(i1 != 1 && TKresult[nres]!= k) */
                   10159:   /*     continue; */
                   10160:   /*   if(invalidvarcomb[k]){ */
                   10161:   /*     printf("\nCombination (%d) projection ignored because no cases \n",k);  */
                   10162:   /*     continue; */
                   10163:   /*   } */
1.268     brouard  10164:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.351     brouard  10165:     for(j=1;j<=cptcovs;j++){
                   10166:     /* for(j=1;j<=cptcoveff;j++) { */
                   10167:     /*   fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10168:     /* } */
                   10169:       fprintf(ficresfb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.267     brouard  10170:     }
1.351     brouard  10171:    /*  fprintf(ficrespij,"******\n"); */
                   10172:    /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10173:    /*    fprintf(ficresfb," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   10174:    /*  } */
1.267     brouard  10175:     fprintf(ficresfb," yearbproj age");
                   10176:     for(j=1; j<=nlstate+ndeath;j++){
                   10177:       for(i=1; i<=nlstate;i++)
1.268     brouard  10178:        fprintf(ficresfb," b%d%d",i,j);
                   10179:       fprintf(ficresfb," b.%d",j);
1.267     brouard  10180:     }
1.296     brouard  10181:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  10182:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   10183:       fprintf(ficresfb,"\n");
1.296     brouard  10184:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  10185:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  10186:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   10187:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  10188:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  10189:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  10190:        nhstepm = nhstepm/hstepm;
                   10191:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10192:        oldm=oldms;savm=savms;
1.268     brouard  10193:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  10194:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  10195:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  10196:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   10197:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   10198:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  10199:        for (h=0; h<=nhstepm; h++){
1.268     brouard  10200:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   10201:            break;
                   10202:          }
                   10203:        }
                   10204:        fprintf(ficresfb,"\n");
1.351     brouard  10205:        /* for(j=1;j<=cptcoveff;j++) */
                   10206:        for(j=1;j<=cptcovs;j++)
                   10207:          fprintf(ficresfb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   10208:          /* fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.296     brouard  10209:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  10210:        for(i=1; i<=nlstate+ndeath;i++) {
                   10211:          ppij=0.;ppi=0.;
                   10212:          for(j=1; j<=nlstate;j++) {
                   10213:            /* if (mobilav==1) */
1.269     brouard  10214:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   10215:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   10216:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   10217:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  10218:              /* else { */
                   10219:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   10220:              /* } */
1.268     brouard  10221:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   10222:          } /* end j */
                   10223:          if(ppi <0.99){
                   10224:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   10225:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   10226:          }
                   10227:          fprintf(ficresfb," %.3f", ppij);
                   10228:        }/* end j */
1.267     brouard  10229:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10230:       } /* end agec */
                   10231:     } /* end yearp */
                   10232:   } /* end k */
1.217     brouard  10233:   
1.267     brouard  10234:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  10235:   
1.267     brouard  10236:   fclose(ficresfb);
                   10237:   printf("End of Computing Back forecasting \n");
                   10238:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  10239:        
1.267     brouard  10240: }
1.217     brouard  10241: 
1.269     brouard  10242: /* Variance of prevalence limit: varprlim */
                   10243:  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  10244:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  10245:  
                   10246:    char fileresvpl[FILENAMELENGTH];  
                   10247:    FILE *ficresvpl;
                   10248:    double **oldm, **savm;
                   10249:    double **varpl; /* Variances of prevalence limits by age */   
                   10250:    int i1, k, nres, j ;
                   10251:    
                   10252:     strcpy(fileresvpl,"VPL_");
                   10253:     strcat(fileresvpl,fileresu);
                   10254:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  10255:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  10256:       exit(0);
                   10257:     }
1.288     brouard  10258:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   10259:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  10260:     
                   10261:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   10262:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   10263:     
                   10264:     i1=pow(2,cptcoveff);
                   10265:     if (cptcovn < 1){i1=1;}
                   10266: 
1.337     brouard  10267:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10268:        k=TKresult[nres];
1.338     brouard  10269:        if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  10270:      /* for(k=1; k<=i1;k++){ /\* We find the combination equivalent to result line values of dummies *\/ */
1.269     brouard  10271:       if(i1 != 1 && TKresult[nres]!= k)
                   10272:        continue;
                   10273:       fprintf(ficresvpl,"\n#****** ");
                   10274:       printf("\n#****** ");
                   10275:       fprintf(ficlog,"\n#****** ");
1.337     brouard  10276:       for(j=1;j<=cptcovs;j++) {
                   10277:        fprintf(ficresvpl,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   10278:        fprintf(ficlog,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   10279:        printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   10280:        /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10281:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.269     brouard  10282:       }
1.337     brouard  10283:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   10284:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10285:       /*       fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10286:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10287:       /* }      */
1.269     brouard  10288:       fprintf(ficresvpl,"******\n");
                   10289:       printf("******\n");
                   10290:       fprintf(ficlog,"******\n");
                   10291:       
                   10292:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   10293:       oldm=oldms;savm=savms;
                   10294:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   10295:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   10296:       /*}*/
                   10297:     }
                   10298:     
                   10299:     fclose(ficresvpl);
1.288     brouard  10300:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   10301:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  10302: 
                   10303:  }
                   10304: /* Variance of back prevalence: varbprlim */
                   10305:  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){
                   10306:       /*------- Variance of back (stable) prevalence------*/
                   10307: 
                   10308:    char fileresvbl[FILENAMELENGTH];  
                   10309:    FILE  *ficresvbl;
                   10310: 
                   10311:    double **oldm, **savm;
                   10312:    double **varbpl; /* Variances of back prevalence limits by age */   
                   10313:    int i1, k, nres, j ;
                   10314: 
                   10315:    strcpy(fileresvbl,"VBL_");
                   10316:    strcat(fileresvbl,fileresu);
                   10317:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   10318:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   10319:      exit(0);
                   10320:    }
                   10321:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   10322:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   10323:    
                   10324:    
                   10325:    i1=pow(2,cptcoveff);
                   10326:    if (cptcovn < 1){i1=1;}
                   10327:    
1.337     brouard  10328:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10329:      k=TKresult[nres];
1.338     brouard  10330:      if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  10331:     /* for(k=1; k<=i1;k++){ */
                   10332:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   10333:     /*          continue; */
1.269     brouard  10334:        fprintf(ficresvbl,"\n#****** ");
                   10335:        printf("\n#****** ");
                   10336:        fprintf(ficlog,"\n#****** ");
1.337     brouard  10337:        for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */
1.338     brouard  10338:         printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   10339:         fprintf(ficresvbl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   10340:         fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
1.337     brouard  10341:        /* for(j=1;j<=cptcoveff;j++) { */
                   10342:        /*       fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10343:        /*       fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10344:        /*       printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10345:        /* } */
                   10346:        /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   10347:        /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10348:        /*       fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10349:        /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
1.269     brouard  10350:        }
                   10351:        fprintf(ficresvbl,"******\n");
                   10352:        printf("******\n");
                   10353:        fprintf(ficlog,"******\n");
                   10354:        
                   10355:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   10356:        oldm=oldms;savm=savms;
                   10357:        
                   10358:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   10359:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   10360:        /*}*/
                   10361:      }
                   10362:    
                   10363:    fclose(ficresvbl);
                   10364:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   10365:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   10366: 
                   10367:  } /* End of varbprlim */
                   10368: 
1.126     brouard  10369: /************** Forecasting *****not tested NB*************/
1.227     brouard  10370: /* 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  10371:   
1.227     brouard  10372: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   10373: /*   int *popage; */
                   10374: /*   double calagedatem, agelim, kk1, kk2; */
                   10375: /*   double *popeffectif,*popcount; */
                   10376: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   10377: /*   /\* double ***mobaverage; *\/ */
                   10378: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  10379: 
1.227     brouard  10380: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10381: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10382: /*   agelim=AGESUP; */
                   10383: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  10384:   
1.227     brouard  10385: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  10386:   
                   10387:   
1.227     brouard  10388: /*   strcpy(filerespop,"POP_");  */
                   10389: /*   strcat(filerespop,fileresu); */
                   10390: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   10391: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   10392: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   10393: /*   } */
                   10394: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   10395: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  10396: 
1.227     brouard  10397: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  10398: 
1.227     brouard  10399: /*   /\* if (mobilav!=0) { *\/ */
                   10400: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   10401: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   10402: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   10403: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   10404: /*   /\*   } *\/ */
                   10405: /*   /\* } *\/ */
1.126     brouard  10406: 
1.227     brouard  10407: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   10408: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  10409:   
1.227     brouard  10410: /*   agelim=AGESUP; */
1.126     brouard  10411:   
1.227     brouard  10412: /*   hstepm=1; */
                   10413: /*   hstepm=hstepm/stepm;  */
1.218     brouard  10414:        
1.227     brouard  10415: /*   if (popforecast==1) { */
                   10416: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   10417: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   10418: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   10419: /*     }  */
                   10420: /*     popage=ivector(0,AGESUP); */
                   10421: /*     popeffectif=vector(0,AGESUP); */
                   10422: /*     popcount=vector(0,AGESUP); */
1.126     brouard  10423:     
1.227     brouard  10424: /*     i=1;    */
                   10425: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  10426:     
1.227     brouard  10427: /*     imx=i; */
                   10428: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   10429: /*   } */
1.218     brouard  10430:   
1.227     brouard  10431: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   10432: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   10433: /*       k=k+1; */
                   10434: /*       fprintf(ficrespop,"\n#******"); */
                   10435: /*       for(j=1;j<=cptcoveff;j++) { */
                   10436: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   10437: /*       } */
                   10438: /*       fprintf(ficrespop,"******\n"); */
                   10439: /*       fprintf(ficrespop,"# Age"); */
                   10440: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   10441: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  10442:       
1.227     brouard  10443: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   10444: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  10445:        
1.227     brouard  10446: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   10447: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   10448: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  10449:          
1.227     brouard  10450: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10451: /*       oldm=oldms;savm=savms; */
                   10452: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  10453:          
1.227     brouard  10454: /*       for (h=0; h<=nhstepm; h++){ */
                   10455: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   10456: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   10457: /*         }  */
                   10458: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   10459: /*           kk1=0.;kk2=0; */
                   10460: /*           for(i=1; i<=nlstate;i++) {               */
                   10461: /*             if (mobilav==1)  */
                   10462: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   10463: /*             else { */
                   10464: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   10465: /*             } */
                   10466: /*           } */
                   10467: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   10468: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   10469: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   10470: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   10471: /*           } */
                   10472: /*         } */
                   10473: /*         for(i=1; i<=nlstate;i++){ */
                   10474: /*           kk1=0.; */
                   10475: /*           for(j=1; j<=nlstate;j++){ */
                   10476: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   10477: /*           } */
                   10478: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   10479: /*         } */
1.218     brouard  10480:            
1.227     brouard  10481: /*         if (h==(int)(calagedatem+12*cpt)) */
                   10482: /*           for(j=1; j<=nlstate;j++)  */
                   10483: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   10484: /*       } */
                   10485: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10486: /*     } */
                   10487: /*       } */
1.218     brouard  10488:       
1.227     brouard  10489: /*       /\******\/ */
1.218     brouard  10490:       
1.227     brouard  10491: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   10492: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   10493: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   10494: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   10495: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  10496:          
1.227     brouard  10497: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10498: /*       oldm=oldms;savm=savms; */
                   10499: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   10500: /*       for (h=0; h<=nhstepm; h++){ */
                   10501: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   10502: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   10503: /*         }  */
                   10504: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   10505: /*           kk1=0.;kk2=0; */
                   10506: /*           for(i=1; i<=nlstate;i++) {               */
                   10507: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   10508: /*           } */
                   10509: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   10510: /*         } */
                   10511: /*       } */
                   10512: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10513: /*     } */
                   10514: /*       } */
                   10515: /*     }  */
                   10516: /*   } */
1.218     brouard  10517:   
1.227     brouard  10518: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  10519:   
1.227     brouard  10520: /*   if (popforecast==1) { */
                   10521: /*     free_ivector(popage,0,AGESUP); */
                   10522: /*     free_vector(popeffectif,0,AGESUP); */
                   10523: /*     free_vector(popcount,0,AGESUP); */
                   10524: /*   } */
                   10525: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10526: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10527: /*   fclose(ficrespop); */
                   10528: /* } /\* End of popforecast *\/ */
1.218     brouard  10529:  
1.126     brouard  10530: int fileappend(FILE *fichier, char *optionfich)
                   10531: {
                   10532:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   10533:     printf("Problem with file: %s\n", optionfich);
                   10534:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   10535:     return (0);
                   10536:   }
                   10537:   fflush(fichier);
                   10538:   return (1);
                   10539: }
                   10540: 
                   10541: 
                   10542: /**************** function prwizard **********************/
                   10543: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   10544: {
                   10545: 
                   10546:   /* Wizard to print covariance matrix template */
                   10547: 
1.164     brouard  10548:   char ca[32], cb[32];
                   10549:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  10550:   int numlinepar;
                   10551: 
                   10552:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10553:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10554:   for(i=1; i <=nlstate; i++){
                   10555:     jj=0;
                   10556:     for(j=1; j <=nlstate+ndeath; j++){
                   10557:       if(j==i) continue;
                   10558:       jj++;
                   10559:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   10560:       printf("%1d%1d",i,j);
                   10561:       fprintf(ficparo,"%1d%1d",i,j);
                   10562:       for(k=1; k<=ncovmodel;k++){
                   10563:        /*        printf(" %lf",param[i][j][k]); */
                   10564:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   10565:        printf(" 0.");
                   10566:        fprintf(ficparo," 0.");
                   10567:       }
                   10568:       printf("\n");
                   10569:       fprintf(ficparo,"\n");
                   10570:     }
                   10571:   }
                   10572:   printf("# Scales (for hessian or gradient estimation)\n");
                   10573:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   10574:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   10575:   for(i=1; i <=nlstate; i++){
                   10576:     jj=0;
                   10577:     for(j=1; j <=nlstate+ndeath; j++){
                   10578:       if(j==i) continue;
                   10579:       jj++;
                   10580:       fprintf(ficparo,"%1d%1d",i,j);
                   10581:       printf("%1d%1d",i,j);
                   10582:       fflush(stdout);
                   10583:       for(k=1; k<=ncovmodel;k++){
                   10584:        /*      printf(" %le",delti3[i][j][k]); */
                   10585:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   10586:        printf(" 0.");
                   10587:        fprintf(ficparo," 0.");
                   10588:       }
                   10589:       numlinepar++;
                   10590:       printf("\n");
                   10591:       fprintf(ficparo,"\n");
                   10592:     }
                   10593:   }
                   10594:   printf("# Covariance matrix\n");
                   10595: /* # 121 Var(a12)\n\ */
                   10596: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10597: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   10598: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   10599: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   10600: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   10601: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   10602: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   10603:   fflush(stdout);
                   10604:   fprintf(ficparo,"# Covariance matrix\n");
                   10605:   /* # 121 Var(a12)\n\ */
                   10606:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10607:   /* #   ...\n\ */
                   10608:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   10609:   
                   10610:   for(itimes=1;itimes<=2;itimes++){
                   10611:     jj=0;
                   10612:     for(i=1; i <=nlstate; i++){
                   10613:       for(j=1; j <=nlstate+ndeath; j++){
                   10614:        if(j==i) continue;
                   10615:        for(k=1; k<=ncovmodel;k++){
                   10616:          jj++;
                   10617:          ca[0]= k+'a'-1;ca[1]='\0';
                   10618:          if(itimes==1){
                   10619:            printf("#%1d%1d%d",i,j,k);
                   10620:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   10621:          }else{
                   10622:            printf("%1d%1d%d",i,j,k);
                   10623:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   10624:            /*  printf(" %.5le",matcov[i][j]); */
                   10625:          }
                   10626:          ll=0;
                   10627:          for(li=1;li <=nlstate; li++){
                   10628:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   10629:              if(lj==li) continue;
                   10630:              for(lk=1;lk<=ncovmodel;lk++){
                   10631:                ll++;
                   10632:                if(ll<=jj){
                   10633:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   10634:                  if(ll<jj){
                   10635:                    if(itimes==1){
                   10636:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10637:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10638:                    }else{
                   10639:                      printf(" 0.");
                   10640:                      fprintf(ficparo," 0.");
                   10641:                    }
                   10642:                  }else{
                   10643:                    if(itimes==1){
                   10644:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   10645:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   10646:                    }else{
                   10647:                      printf(" 0.");
                   10648:                      fprintf(ficparo," 0.");
                   10649:                    }
                   10650:                  }
                   10651:                }
                   10652:              } /* end lk */
                   10653:            } /* end lj */
                   10654:          } /* end li */
                   10655:          printf("\n");
                   10656:          fprintf(ficparo,"\n");
                   10657:          numlinepar++;
                   10658:        } /* end k*/
                   10659:       } /*end j */
                   10660:     } /* end i */
                   10661:   } /* end itimes */
                   10662: 
                   10663: } /* end of prwizard */
                   10664: /******************* Gompertz Likelihood ******************************/
                   10665: double gompertz(double x[])
                   10666: { 
1.302     brouard  10667:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
1.126     brouard  10668:   int i,n=0; /* n is the size of the sample */
                   10669: 
1.220     brouard  10670:   for (i=1;i<=imx ; i++) {
1.126     brouard  10671:     sump=sump+weight[i];
                   10672:     /*    sump=sump+1;*/
                   10673:     num=num+1;
                   10674:   }
1.302     brouard  10675:   L=0.0;
                   10676:   /* agegomp=AGEGOMP; */
1.126     brouard  10677:   /* for (i=0; i<=imx; i++) 
                   10678:      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]);*/
                   10679: 
1.302     brouard  10680:   for (i=1;i<=imx ; i++) {
                   10681:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   10682:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   10683:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   10684:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   10685:      * +
                   10686:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   10687:      */
                   10688:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   10689:        if (cens[i] == 1){
                   10690:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   10691:        } else if (cens[i] == 0){
1.126     brouard  10692:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
1.302     brouard  10693:          +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   10694:       } else
                   10695:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
1.126     brouard  10696:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
1.302     brouard  10697:        L=L+A*weight[i];
1.126     brouard  10698:        /*      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  10699:      }
                   10700:   }
1.126     brouard  10701: 
1.302     brouard  10702:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
1.126     brouard  10703:  
                   10704:   return -2*L*num/sump;
                   10705: }
                   10706: 
1.136     brouard  10707: #ifdef GSL
                   10708: /******************* Gompertz_f Likelihood ******************************/
                   10709: double gompertz_f(const gsl_vector *v, void *params)
                   10710: { 
1.302     brouard  10711:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
1.136     brouard  10712:   double *x= (double *) v->data;
                   10713:   int i,n=0; /* n is the size of the sample */
                   10714: 
                   10715:   for (i=0;i<=imx-1 ; i++) {
                   10716:     sump=sump+weight[i];
                   10717:     /*    sump=sump+1;*/
                   10718:     num=num+1;
                   10719:   }
                   10720:  
                   10721:  
                   10722:   /* for (i=0; i<=imx; i++) 
                   10723:      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]);*/
                   10724:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   10725:   for (i=1;i<=imx ; i++)
                   10726:     {
                   10727:       if (cens[i] == 1 && wav[i]>1)
                   10728:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   10729:       
                   10730:       if (cens[i] == 0 && wav[i]>1)
                   10731:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   10732:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   10733:       
                   10734:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   10735:       if (wav[i] > 1 ) { /* ??? */
                   10736:        LL=LL+A*weight[i];
                   10737:        /*      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]);*/
                   10738:       }
                   10739:     }
                   10740: 
                   10741:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   10742:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   10743:  
                   10744:   return -2*LL*num/sump;
                   10745: }
                   10746: #endif
                   10747: 
1.126     brouard  10748: /******************* Printing html file ***********/
1.201     brouard  10749: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  10750:                  int lastpass, int stepm, int weightopt, char model[],\
                   10751:                  int imx,  double p[],double **matcov,double agemortsup){
                   10752:   int i,k;
                   10753: 
                   10754:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   10755:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   10756:   for (i=1;i<=2;i++) 
                   10757:     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  10758:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  10759:   fprintf(fichtm,"</ul>");
                   10760: 
                   10761: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   10762: 
                   10763:  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>");
                   10764: 
                   10765:  for (k=agegomp;k<(agemortsup-2);k++) 
                   10766:    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]);
                   10767: 
                   10768:  
                   10769:   fflush(fichtm);
                   10770: }
                   10771: 
                   10772: /******************* Gnuplot file **************/
1.201     brouard  10773: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  10774: 
                   10775:   char dirfileres[132],optfileres[132];
1.164     brouard  10776: 
1.126     brouard  10777:   int ng;
                   10778: 
                   10779: 
                   10780:   /*#ifdef windows */
                   10781:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   10782:     /*#endif */
                   10783: 
                   10784: 
                   10785:   strcpy(dirfileres,optionfilefiname);
                   10786:   strcpy(optfileres,"vpl");
1.199     brouard  10787:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  10788:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  10789:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  10790:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  10791:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   10792: 
                   10793: } 
                   10794: 
1.136     brouard  10795: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   10796: {
1.126     brouard  10797: 
1.136     brouard  10798:   /*-------- data file ----------*/
                   10799:   FILE *fic;
                   10800:   char dummy[]="                         ";
1.240     brouard  10801:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  10802:   int lstra;
1.136     brouard  10803:   int linei, month, year,iout;
1.302     brouard  10804:   int noffset=0; /* This is the offset if BOM data file */
1.136     brouard  10805:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  10806:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  10807:   char *stratrunc;
1.223     brouard  10808: 
1.349     brouard  10809:   /* DummyV=ivector(-1,NCOVMAX); /\* 1 to 3 *\/ */
                   10810:   /* FixedV=ivector(-1,NCOVMAX); /\* 1 to 3 *\/ */
1.339     brouard  10811:   
                   10812:   ncovcolt=ncovcol+nqv+ntv+nqtv; /* total of covariates in the data, not in the model equation */
                   10813:   
1.136     brouard  10814:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  10815:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10816:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  10817:   }
1.126     brouard  10818: 
1.302     brouard  10819:     /* Is it a BOM UTF-8 Windows file? */
                   10820:   /* First data line */
                   10821:   linei=0;
                   10822:   while(fgets(line, MAXLINE, fic)) {
                   10823:     noffset=0;
                   10824:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   10825:     {
                   10826:       noffset=noffset+3;
                   10827:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   10828:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   10829:       fflush(ficlog); return 1;
                   10830:     }
                   10831:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   10832:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   10833:     {
                   10834:       noffset=noffset+2;
1.304     brouard  10835:       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);
                   10836:       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  10837:       fflush(ficlog); return 1;
                   10838:     }
                   10839:     else if( line[0] == 0 && line[1] == 0)
                   10840:     {
                   10841:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   10842:        noffset=noffset+4;
1.304     brouard  10843:        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);
                   10844:        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  10845:        fflush(ficlog); return 1;
                   10846:       }
                   10847:     } else{
                   10848:       ;/*printf(" Not a BOM file\n");*/
                   10849:     }
                   10850:         /* If line starts with a # it is a comment */
                   10851:     if (line[noffset] == '#') {
                   10852:       linei=linei+1;
                   10853:       break;
                   10854:     }else{
                   10855:       break;
                   10856:     }
                   10857:   }
                   10858:   fclose(fic);
                   10859:   if((fic=fopen(datafile,"r"))==NULL)    {
                   10860:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10861:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   10862:   }
                   10863:   /* Not a Bom file */
                   10864:   
1.136     brouard  10865:   i=1;
                   10866:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   10867:     linei=linei+1;
                   10868:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   10869:       if(line[j] == '\t')
                   10870:        line[j] = ' ';
                   10871:     }
                   10872:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   10873:       ;
                   10874:     };
                   10875:     line[j+1]=0;  /* Trims blanks at end of line */
                   10876:     if(line[0]=='#'){
                   10877:       fprintf(ficlog,"Comment line\n%s\n",line);
                   10878:       printf("Comment line\n%s\n",line);
                   10879:       continue;
                   10880:     }
                   10881:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  10882:     strcpy(line, linetmp);
1.223     brouard  10883:     
                   10884:     /* Loops on waves */
                   10885:     for (j=maxwav;j>=1;j--){
                   10886:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  10887:        cutv(stra, strb, line, ' '); 
                   10888:        if(strb[0]=='.') { /* Missing value */
                   10889:          lval=-1;
                   10890:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
1.341     brouard  10891:          cotvar[j][ncovcol+nqv+ntv+iv][i]=-1; /* For performance reasons */
1.238     brouard  10892:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   10893:            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);
                   10894:            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);
                   10895:            return 1;
                   10896:          }
                   10897:        }else{
                   10898:          errno=0;
                   10899:          /* what_kind_of_number(strb); */
                   10900:          dval=strtod(strb,&endptr); 
                   10901:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   10902:          /* if(strb != endptr && *endptr == '\0') */
                   10903:          /*    dval=dlval; */
                   10904:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10905:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10906:            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);
                   10907:            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);
                   10908:            return 1;
                   10909:          }
                   10910:          cotqvar[j][iv][i]=dval; 
1.341     brouard  10911:          cotvar[j][ncovcol+nqv+ntv+iv][i]=dval; /* because cotvar starts now at first ntv */ 
1.238     brouard  10912:        }
                   10913:        strcpy(line,stra);
1.223     brouard  10914:       }/* end loop ntqv */
1.225     brouard  10915:       
1.223     brouard  10916:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  10917:        cutv(stra, strb, line, ' '); 
                   10918:        if(strb[0]=='.') { /* Missing value */
                   10919:          lval=-1;
                   10920:        }else{
                   10921:          errno=0;
                   10922:          lval=strtol(strb,&endptr,10); 
                   10923:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   10924:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10925:            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);
                   10926:            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);
                   10927:            return 1;
                   10928:          }
                   10929:        }
                   10930:        if(lval <-1 || lval >1){
                   10931:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10932:  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  10933:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10934:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10935:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10936:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10937:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10938:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10939:  Exiting.\n",lval,linei, i,line,iv,j);
1.238     brouard  10940:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10941:  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  10942:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10943:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10944:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10945:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10946:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10947:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10948:  Exiting.\n",lval,linei, i,line,iv,j);fflush(ficlog);
1.238     brouard  10949:          return 1;
                   10950:        }
1.341     brouard  10951:        cotvar[j][ncovcol+nqv+iv][i]=(double)(lval);
1.238     brouard  10952:        strcpy(line,stra);
1.223     brouard  10953:       }/* end loop ntv */
1.225     brouard  10954:       
1.223     brouard  10955:       /* Statuses  at wave */
1.137     brouard  10956:       cutv(stra, strb, line, ' '); 
1.223     brouard  10957:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  10958:        lval=-1;
1.136     brouard  10959:       }else{
1.238     brouard  10960:        errno=0;
                   10961:        lval=strtol(strb,&endptr,10); 
                   10962:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
1.347     brouard  10963:        if( strb[0]=='\0' || (*endptr != '\0' )){
                   10964:          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);
                   10965:          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);
                   10966:          return 1;
                   10967:        }else if( lval==0 || lval > nlstate+ndeath){
1.348     brouard  10968:          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);
                   10969:          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  10970:          return 1;
                   10971:        }
1.136     brouard  10972:       }
1.225     brouard  10973:       
1.136     brouard  10974:       s[j][i]=lval;
1.225     brouard  10975:       
1.223     brouard  10976:       /* Date of Interview */
1.136     brouard  10977:       strcpy(line,stra);
                   10978:       cutv(stra, strb,line,' ');
1.169     brouard  10979:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10980:       }
1.169     brouard  10981:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  10982:        month=99;
                   10983:        year=9999;
1.136     brouard  10984:       }else{
1.225     brouard  10985:        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);
                   10986:        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);
                   10987:        return 1;
1.136     brouard  10988:       }
                   10989:       anint[j][i]= (double) year; 
1.302     brouard  10990:       mint[j][i]= (double)month;
                   10991:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   10992:       /*       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]); */
                   10993:       /*       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]); */
                   10994:       /* } */
1.136     brouard  10995:       strcpy(line,stra);
1.223     brouard  10996:     } /* End loop on waves */
1.225     brouard  10997:     
1.223     brouard  10998:     /* Date of death */
1.136     brouard  10999:     cutv(stra, strb,line,' '); 
1.169     brouard  11000:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  11001:     }
1.169     brouard  11002:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  11003:       month=99;
                   11004:       year=9999;
                   11005:     }else{
1.141     brouard  11006:       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  11007:       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);
                   11008:       return 1;
1.136     brouard  11009:     }
                   11010:     andc[i]=(double) year; 
                   11011:     moisdc[i]=(double) month; 
                   11012:     strcpy(line,stra);
                   11013:     
1.223     brouard  11014:     /* Date of birth */
1.136     brouard  11015:     cutv(stra, strb,line,' '); 
1.169     brouard  11016:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  11017:     }
1.169     brouard  11018:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  11019:       month=99;
                   11020:       year=9999;
                   11021:     }else{
1.141     brouard  11022:       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);
                   11023:       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  11024:       return 1;
1.136     brouard  11025:     }
                   11026:     if (year==9999) {
1.141     brouard  11027:       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);
                   11028:       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  11029:       return 1;
                   11030:       
1.136     brouard  11031:     }
                   11032:     annais[i]=(double)(year);
1.302     brouard  11033:     moisnais[i]=(double)(month);
                   11034:     for (j=1;j<=maxwav;j++){
                   11035:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   11036:        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]);
                   11037:        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]);
                   11038:       }
                   11039:     }
                   11040: 
1.136     brouard  11041:     strcpy(line,stra);
1.225     brouard  11042:     
1.223     brouard  11043:     /* Sample weight */
1.136     brouard  11044:     cutv(stra, strb,line,' '); 
                   11045:     errno=0;
                   11046:     dval=strtod(strb,&endptr); 
                   11047:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  11048:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   11049:       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  11050:       fflush(ficlog);
                   11051:       return 1;
                   11052:     }
                   11053:     weight[i]=dval; 
                   11054:     strcpy(line,stra);
1.225     brouard  11055:     
1.223     brouard  11056:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   11057:       cutv(stra, strb, line, ' '); 
                   11058:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  11059:        lval=-1;
1.311     brouard  11060:        coqvar[iv][i]=NAN; 
                   11061:        covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  11062:       }else{
1.225     brouard  11063:        errno=0;
                   11064:        /* what_kind_of_number(strb); */
                   11065:        dval=strtod(strb,&endptr);
                   11066:        /* if(strb != endptr && *endptr == '\0') */
                   11067:        /*   dval=dlval; */
                   11068:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   11069:        if( strb[0]=='\0' || (*endptr != '\0')){
                   11070:          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);
                   11071:          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);
                   11072:          return 1;
                   11073:        }
                   11074:        coqvar[iv][i]=dval; 
1.226     brouard  11075:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  11076:       }
                   11077:       strcpy(line,stra);
                   11078:     }/* end loop nqv */
1.136     brouard  11079:     
1.223     brouard  11080:     /* Covariate values */
1.136     brouard  11081:     for (j=ncovcol;j>=1;j--){
                   11082:       cutv(stra, strb,line,' '); 
1.223     brouard  11083:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  11084:        lval=-1;
1.136     brouard  11085:       }else{
1.225     brouard  11086:        errno=0;
                   11087:        lval=strtol(strb,&endptr,10); 
                   11088:        if( strb[0]=='\0' || (*endptr != '\0')){
                   11089:          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);
                   11090:          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);
                   11091:          return 1;
                   11092:        }
1.136     brouard  11093:       }
                   11094:       if(lval <-1 || lval >1){
1.225     brouard  11095:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  11096:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   11097:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  11098:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   11099:  build V1=0 V2=0 for the reference value (1),\n                                \
                   11100:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  11101:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  11102:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  11103:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  11104:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  11105:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   11106:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  11107:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   11108:  build V1=0 V2=0 for the reference value (1),\n                                \
                   11109:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  11110:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  11111:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  11112:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  11113:        return 1;
1.136     brouard  11114:       }
                   11115:       covar[j][i]=(double)(lval);
                   11116:       strcpy(line,stra);
                   11117:     }  
                   11118:     lstra=strlen(stra);
1.225     brouard  11119:     
1.136     brouard  11120:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   11121:       stratrunc = &(stra[lstra-9]);
                   11122:       num[i]=atol(stratrunc);
                   11123:     }
                   11124:     else
                   11125:       num[i]=atol(stra);
                   11126:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   11127:       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;}*/
                   11128:     
                   11129:     i=i+1;
                   11130:   } /* End loop reading  data */
1.225     brouard  11131:   
1.136     brouard  11132:   *imax=i-1; /* Number of individuals */
                   11133:   fclose(fic);
1.225     brouard  11134:   
1.136     brouard  11135:   return (0);
1.164     brouard  11136:   /* endread: */
1.225     brouard  11137:   printf("Exiting readdata: ");
                   11138:   fclose(fic);
                   11139:   return (1);
1.223     brouard  11140: }
1.126     brouard  11141: 
1.234     brouard  11142: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  11143:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  11144:   while (*p2 == ' ')
1.234     brouard  11145:     p2++; 
                   11146:   /* while ((*p1++ = *p2++) !=0) */
                   11147:   /*   ; */
                   11148:   /* do */
                   11149:   /*   while (*p2 == ' ') */
                   11150:   /*     p2++; */
                   11151:   /* while (*p1++ == *p2++); */
                   11152:   *stri=p2; 
1.145     brouard  11153: }
                   11154: 
1.330     brouard  11155: int decoderesult( char resultline[], int nres)
1.230     brouard  11156: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   11157: {
1.235     brouard  11158:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  11159:   char resultsav[MAXLINE];
1.330     brouard  11160:   /* int resultmodel[MAXLINE]; */
1.334     brouard  11161:   /* int modelresult[MAXLINE]; */
1.230     brouard  11162:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   11163: 
1.234     brouard  11164:   removefirstspace(&resultline);
1.332     brouard  11165:   printf("decoderesult:%s\n",resultline);
1.230     brouard  11166: 
1.332     brouard  11167:   strcpy(resultsav,resultline);
1.342     brouard  11168:   /* printf("Decoderesult resultsav=\"%s\" resultline=\"%s\"\n", resultsav, resultline); */
1.230     brouard  11169:   if (strlen(resultsav) >1){
1.334     brouard  11170:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' in this resultline */
1.230     brouard  11171:   }
1.353     brouard  11172:   if(j == 0 && cptcovs== 0){ /* Resultline but no =  and no covariate in the model */
1.253     brouard  11173:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   11174:     return (0);
                   11175:   }
1.234     brouard  11176:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
1.353     brouard  11177:     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);
                   11178:     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);
                   11179:     if(j==0)
                   11180:       return 1;
1.234     brouard  11181:   }
1.334     brouard  11182:   for(k=1; k<=j;k++){ /* Loop on any covariate of the RESULT LINE */
1.234     brouard  11183:     if(nbocc(resultsav,'=') >1){
1.318     brouard  11184:       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  11185:       /* 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  11186:       cutl(strc,strd,strb,'=');  /* strb:"V4=1" strc="1" strd="V4" */
1.332     brouard  11187:       /* If a blank, then strc="V4=" and strd='\0' */
                   11188:       if(strc[0]=='\0'){
                   11189:       printf("Error in resultline, probably a blank after the \"%s\", \"result:%s\", stra=\"%s\" resultsav=\"%s\"\n",strb,resultline, stra, resultsav);
                   11190:        fprintf(ficlog,"Error in resultline, probably a blank after the \"V%s=\", resultline=%s\n",strb,resultline);
                   11191:        return 1;
                   11192:       }
1.234     brouard  11193:     }else
                   11194:       cutl(strc,strd,resultsav,'=');
1.318     brouard  11195:     Tvalsel[k]=atof(strc); /* 1 */ /* Tvalsel of k is the float value of the kth covariate appearing in this result line */
1.234     brouard  11196:     
1.230     brouard  11197:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
1.318     brouard  11198:     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  11199:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   11200:     /* cptcovsel++;     */
                   11201:     if (nbocc(stra,'=') >0)
                   11202:       strcpy(resultsav,stra); /* and analyzes it */
                   11203:   }
1.235     brouard  11204:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  11205:   /* 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  11206:   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  11207:     if(Typevar[k1]==0){ /* Single covariate in model */
                   11208:       /* 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.234     brouard  11209:       match=0;
1.318     brouard  11210:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   11211:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  11212:          modelresult[nres][k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.318     brouard  11213:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
1.234     brouard  11214:          break;
                   11215:        }
                   11216:       }
                   11217:       if(match == 0){
1.338     brouard  11218:        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]);
                   11219:        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  11220:        return 1;
1.234     brouard  11221:       }
1.332     brouard  11222:     }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*/
                   11223:       /* We feed resultmodel[k1]=k2; */
                   11224:       match=0;
                   11225:       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 */
                   11226:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  11227:          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  11228:          resultmodel[nres][k1]=k2; /* Added here */
1.342     brouard  11229:          /* printf("Decoderesult first modelresult[k2=%d]=%d (k1) V%d*AGE\n",k2,k1,Tvar[k1]); */
1.332     brouard  11230:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   11231:          break;
                   11232:        }
                   11233:       }
                   11234:       if(match == 0){
1.338     brouard  11235:        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]);
                   11236:        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  11237:       return 1;
                   11238:       }
1.349     brouard  11239:     }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  11240:       /* resultmodel[nres][of such a Vn * Vm product k1] is not unique, so can't exist, we feed Tvard[k1][1] and [2] */ 
                   11241:       match=0;
1.342     brouard  11242:       /* 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  11243:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   11244:        if(Tvardk[k1][1]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   11245:          /* modelresult[k2]=k1; */
1.342     brouard  11246:          /* printf("Decoderesult first Product modelresult[k2=%d]=%d (k1) V%d * \n",k2,k1,Tvarsel[k2]); */
1.332     brouard  11247:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   11248:        }
                   11249:       }
                   11250:       if(match == 0){
1.349     brouard  11251:        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);
                   11252:        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  11253:        return 1;
                   11254:       }
                   11255:       match=0;
                   11256:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   11257:        if(Tvardk[k1][2]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   11258:          /* modelresult[k2]=k1;*/
1.342     brouard  11259:          /* printf("Decoderesult second Product modelresult[k2=%d]=%d (k1) * V%d \n ",k2,k1,Tvarsel[k2]); */
1.332     brouard  11260:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   11261:          break;
                   11262:        }
                   11263:       }
                   11264:       if(match == 0){
1.349     brouard  11265:        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);
                   11266:        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  11267:        return 1;
                   11268:       }
                   11269:     }/* End of testing */
1.333     brouard  11270:   }/* End loop cptcovt */
1.235     brouard  11271:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  11272:   /* Feeds resultmodel[nres][k1]=k2 for single covariate (k1) in the model equation */
1.334     brouard  11273:   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)
                   11274:                           * Loop on resultline variables: result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  11275:     match=0;
1.318     brouard  11276:     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  11277:       if(Typevar[k1]==0){ /* Single only */
1.349     brouard  11278:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4  What if a product?  */
1.330     brouard  11279:          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  11280:          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  11281:          ++match;
                   11282:        }
                   11283:       }
                   11284:     }
                   11285:     if(match == 0){
1.338     brouard  11286:       printf("Error in result line: variable V%d is missing in model; result: %s, model=1+age+%s\n",Tvarsel[k2], resultline, model);
                   11287:       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  11288:       return 1;
1.234     brouard  11289:     }else if(match > 1){
1.338     brouard  11290:       printf("Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
                   11291:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
1.310     brouard  11292:       return 1;
1.234     brouard  11293:     }
                   11294:   }
1.334     brouard  11295:   /* cptcovres=j /\* Number of variables in the resultline is equal to cptcovs and thus useless *\/     */
1.234     brouard  11296:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  11297:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.330     brouard  11298:   /* nres=1st result line: V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   11299:   /* 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*/
                   11300:   /* nres=2nd result line: V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.235     brouard  11301:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   11302:   /*    1 0 0 0 */
                   11303:   /*    2 1 0 0 */
                   11304:   /*    3 0 1 0 */ 
1.330     brouard  11305:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 (nres=2)*/
1.235     brouard  11306:   /*    5 0 0 1 */
1.330     brouard  11307:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 (nres=1)*/
1.235     brouard  11308:   /*    7 0 1 1 */
                   11309:   /*    8 1 1 1 */
1.237     brouard  11310:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   11311:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   11312:   /* V5*age V5 known which value for nres?  */
                   11313:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.334     brouard  11314:   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.
                   11315:                                                   * loop on position k1 in the MODEL LINE */
1.331     brouard  11316:     /* k counting number of combination of single dummies in the equation model */
                   11317:     /* k4 counting single dummies in the equation model */
                   11318:     /* k4q counting single quantitatives in the equation model */
1.344     brouard  11319:     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  11320:        /* 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  11321:       /* 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  11322:       /* Value in the (current nres) resultline of the variable at the k1th position in the model equation resultmodel[nres][k1]= k3 */
1.332     brouard  11323:       /* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline                        */
                   11324:       /*      k3 is the position in the nres result line of the k1th variable of the model equation                                  */
                   11325:       /* Tvarsel[k3]: Name of the variable at the k3th position in the result line.                                                  */
                   11326:       /* Tvalsel[k3]: Value of the variable at the k3th position in the result line.                                                 */
                   11327:       /* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline                   */
1.334     brouard  11328:       /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline                     */
1.332     brouard  11329:       /* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line                                        */
1.330     brouard  11330:       /* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line                                                      */
1.332     brouard  11331:       k3= resultmodel[nres][k1]; /* From position k1 in model get position k3 in result line */
                   11332:       /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   11333:       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  11334:       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  11335:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][Name]=Value; stores the value into the name of the variable. */
1.332     brouard  11336:       /* Tinvresult[nres][4]=1 */
1.334     brouard  11337:       /* Tresult[nres][k4+1]=Tvalsel[k3];/\* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) *\/ */
                   11338:       Tresult[nres][k3]=Tvalsel[k3];/* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) */
                   11339:       /* Tvresult[nres][k4+1]=(int)Tvarsel[k3];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   11340:       Tvresult[nres][k3]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
1.237     brouard  11341:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.334     brouard  11342:       precov[nres][k1]=Tvalsel[k3]; /* Value from resultline of the variable at the k1 position in the model */
1.342     brouard  11343:       /* 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  11344:       k4++;;
1.331     brouard  11345:     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Quantitative and single */
1.330     brouard  11346:       /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 */
1.332     brouard  11347:       /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline                                 */
1.330     brouard  11348:       /* Tqinvresult[nres][Name of a quantitative variable]= value of the variable in the result line                                                      */
1.332     brouard  11349:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 5 =k3q */
                   11350:       k2q=(int)Tvarsel[k3q]; /*  Name of variable at k3q th position in the resultline */
                   11351:       /* Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  11352:       /* Tqresult[nres][k4q+1]=Tvalsel[k3q]; /\* Tqresult[nres][1]=25.1 *\/ */
                   11353:       /* Tvresult[nres][k4q+1]=(int)Tvarsel[k3q];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   11354:       /* Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /\* Tvqresult[nres][1]=5 *\/ */
                   11355:       Tqresult[nres][k3q]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   11356:       Tvresult[nres][k3q]=(int)Tvarsel[k3q];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   11357:       Tvqresult[nres][k3q]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
1.237     brouard  11358:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.330     brouard  11359:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.332     brouard  11360:       precov[nres][k1]=Tvalsel[k3q];
1.342     brouard  11361:       /* 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  11362:       k4q++;;
1.350     brouard  11363:     }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"*/
                   11364:       /* Tvar[k1]; */ /* Age variable */ /* 17 age*V6*V2 ?*/
1.332     brouard  11365:       /* Wrong we want the value of variable name Tvar[k1] */
1.350     brouard  11366:       if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
                   11367:        precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
                   11368:       /* 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]]); */
                   11369:       }else{
                   11370:        k3= resultmodel[nres][k1]; /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   11371:        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)*/
                   11372:        TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][4]=1 */
                   11373:        precov[nres][k1]=Tvalsel[k3];
                   11374:       }
1.342     brouard  11375:       /* 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  11376:     }else if( Dummy[k1]==3 ){ /* For quant with age product */
1.350     brouard  11377:       if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
                   11378:        precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
                   11379:       /* 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]]); */
                   11380:       }else{
                   11381:        k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 25.1=k3q */
                   11382:        k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
                   11383:        TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* TinvDoQresult[nres][5]=25.1 */
                   11384:        precov[nres][k1]=Tvalsel[k3q];
                   11385:       }
1.342     brouard  11386:       /* 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  11387:     }else if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
1.332     brouard  11388:       precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
1.342     brouard  11389:       /* 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  11390:     }else{
1.332     brouard  11391:       printf("Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
                   11392:       fprintf(ficlog,"Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
1.235     brouard  11393:     }
                   11394:   }
1.234     brouard  11395:   
1.334     brouard  11396:   TKresult[nres]=++k; /* Number of combinations of dummies for the nresult and the model =Tvalsel[k3]*pow(2,k4) + 1*/
1.230     brouard  11397:   return (0);
                   11398: }
1.235     brouard  11399: 
1.230     brouard  11400: int decodemodel( char model[], int lastobs)
                   11401:  /**< This routine decodes the model and returns:
1.224     brouard  11402:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   11403:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   11404:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   11405:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   11406:        * - cptcovage number of covariates with age*products =2
                   11407:        * - cptcovs number of simple covariates
1.339     brouard  11408:        * ncovcolt=ncovcol+nqv+ntv+nqtv total of covariates in the data, not in the model equation
1.224     brouard  11409:        * - 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  11410:        *     which is a new column after the 9 (ncovcol+nqv+ntv+nqtv) variables. 
1.319     brouard  11411:        * - if k is a product Vn*Vm, covar[k][i] is filled with correct values for each individual
1.224     brouard  11412:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   11413:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   11414:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   11415:        */
1.319     brouard  11416: /* 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  11417: {
1.238     brouard  11418:   int i, j, k, ks, v;
1.349     brouard  11419:   int n,m;
                   11420:   int  j1, k1, k11, k12, k2, k3, k4;
                   11421:   char modelsav[300];
                   11422:   char stra[300], strb[300], strc[300], strd[300],stre[300],strf[300];
1.187     brouard  11423:   char *strpt;
1.349     brouard  11424:   int  **existcomb;
                   11425:   
                   11426:   existcomb=imatrix(1,NCOVMAX,1,NCOVMAX);
                   11427:   for(i=1;i<=NCOVMAX;i++)
                   11428:     for(j=1;j<=NCOVMAX;j++)
                   11429:       existcomb[i][j]=0;
                   11430:     
1.145     brouard  11431:   /*removespace(model);*/
1.136     brouard  11432:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.349     brouard  11433:     j=0, j1=0, k1=0, k12=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  11434:     if (strstr(model,"AGE") !=0){
1.192     brouard  11435:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   11436:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  11437:       return 1;
                   11438:     }
1.141     brouard  11439:     if (strstr(model,"v") !=0){
1.338     brouard  11440:       printf("Error. 'v' must be in upper case 'V' model=1+age+%s ",model);
                   11441:       fprintf(ficlog,"Error. 'v' must be in upper case model=1+age+%s ",model);fflush(ficlog);
1.141     brouard  11442:       return 1;
                   11443:     }
1.187     brouard  11444:     strcpy(modelsav,model); 
                   11445:     if ((strpt=strstr(model,"age*age")) !=0){
1.338     brouard  11446:       printf(" strpt=%s, model=1+age+%s\n",strpt, model);
1.187     brouard  11447:       if(strpt != model){
1.338     brouard  11448:        printf("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);
1.338     brouard  11451:        fprintf(ficlog,"Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  11452:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  11453:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  11454:        return 1;
1.225     brouard  11455:       }
1.187     brouard  11456:       nagesqr=1;
                   11457:       if (strstr(model,"+age*age") !=0)
1.234     brouard  11458:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  11459:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  11460:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  11461:       else 
1.234     brouard  11462:        substrchaine(modelsav, model, "age*age");
1.187     brouard  11463:     }else
                   11464:       nagesqr=0;
1.349     brouard  11465:     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  11466:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   11467:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.351     brouard  11468:       cptcovs=0; /**<  Number of simple covariates V1 +V1*age +V3 +V3*V4 +age*age => V1 + V3 =4+1-3=2  Wrong */
1.187     brouard  11469:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  11470:                     * cst, age and age*age 
                   11471:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   11472:       /* including age products which are counted in cptcovage.
                   11473:        * but the covariates which are products must be treated 
                   11474:        * separately: ncovn=4- 2=2 (V1+V3). */
1.349     brouard  11475:       cptcovprod=0; /**< Number of products  V1*V2 +v3*age = 2 */
                   11476:       cptcovdageprod=0; /* Number of doouble products with age age*Vn*VM or Vn*age*Vm or Vn*Vm*age */
1.187     brouard  11477:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.349     brouard  11478:       cptcovprodage=0;
                   11479:       /* cptcovprodage=nboccstr(modelsav,"age");*/
1.225     brouard  11480:       
1.187     brouard  11481:       /*   Design
                   11482:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   11483:        *  <          ncovcol=8                >
                   11484:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   11485:        *   k=  1    2      3       4     5       6      7        8
                   11486:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
1.345     brouard  11487:        *  covar[k,i], are for fixed covariates, value of kth covariate if not including age for individual i:
1.224     brouard  11488:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   11489:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  11490:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   11491:        *  Tage[++cptcovage]=k
1.345     brouard  11492:        *       if products, new covar are created after ncovcol + nqv (quanti fixed) with k1
1.187     brouard  11493:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   11494:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   11495:        *  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
                   11496:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   11497:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   11498:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
1.345     brouard  11499:        *  <          ncovcol=8  8 fixed covariate. Additional starts at 9 (V5*V6) and 10(V7*V8)              >
1.187     brouard  11500:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   11501:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
1.345     brouard  11502:        *     Tvard[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   11503:        * p Tvar[1]@12={2,   1,     3,      3,   9,     10,     8,       8}
1.187     brouard  11504:        * p Tprod[1]@2={                         6, 5}
                   11505:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   11506:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   11507:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1.319     brouard  11508:        *How to reorganize? Tvars(orted)
1.187     brouard  11509:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   11510:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   11511:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   11512:        * Struct []
                   11513:        */
1.225     brouard  11514:       
1.187     brouard  11515:       /* This loop fills the array Tvar from the string 'model'.*/
                   11516:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   11517:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   11518:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   11519:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   11520:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   11521:       /*       k=1 Tvar[1]=2 (from V2) */
                   11522:       /*       k=5 Tvar[5] */
                   11523:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  11524:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  11525:       /*       } */
1.198     brouard  11526:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  11527:       /*
                   11528:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  11529:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   11530:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   11531:       }
1.187     brouard  11532:       cptcovage=0;
1.351     brouard  11533: 
                   11534:       /* First loop in order to calculate */
                   11535:       /* for age*VN*Vm
                   11536:        * Provides, Typevar[k], Tage[cptcovage], existcomb[n][m], FixedV[ncovcolt+k12]
                   11537:        * Tprod[k1]=k  Tposprod[k]=k1;    Tvard[k1][1] =m;
                   11538:       */
                   11539:       /* Needs  FixedV[Tvardk[k][1]] */
                   11540:       /* For others:
                   11541:        * Sets  Typevar[k];
                   11542:        * Tvar[k]=ncovcol+nqv+ntv+nqtv+k11;
                   11543:        *       Tposprod[k]=k11;
                   11544:        *       Tprod[k11]=k;
                   11545:        *       Tvardk[k][1] =m;
                   11546:        * Needs FixedV[Tvardk[k][1]] == 0
                   11547:       */
                   11548:       
1.319     brouard  11549:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model line */
                   11550:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' cutl from left to right
                   11551:                                         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" */
                   11552:        if (nbocc(modelsav,'+')==0)
                   11553:          strcpy(strb,modelsav); /* and analyzes it */
1.234     brouard  11554:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   11555:        /*scanf("%d",i);*/
1.349     brouard  11556:        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 */
                   11557:          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  */
                   11558:          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   */
                   11559:            Typevar[k]=3;  /* 3 for age and double product age*Vn*Vm varying of fixed */
                   11560:             if(strstr(strc,"age")!=0) { /* It means that strc=V2*age or age*V2 and thus that strd=Vn */
                   11561:               cutl(stre,strf,strc,'*') ; /* strf=age or Vm, stre=Vm or age. If strc=V6*V2 then strf=V6 and stre=V2 */
                   11562:              strcpy(strc,strb); /* save strb(=age*Vn*Vm) into strc */
                   11563:              /* We want strb=Vn*Vm */
                   11564:               if(strcmp(strf,"age")==0){ /* strf is "age" so that stre=Vm =V2 . */
                   11565:                 strcpy(strb,strd);
                   11566:                 strcat(strb,"*");
                   11567:                 strcat(strb,stre);
                   11568:               }else{  /* strf=Vm  If strf=V6 then stre=V2 */
                   11569:                 strcpy(strb,strf);
                   11570:                 strcat(strb,"*");
                   11571:                 strcat(strb,stre);
                   11572:                 strcpy(strd,strb); /* in order for strd to not be "age"  for next test (will be Vn*Vm */
                   11573:               }
1.351     brouard  11574:              /* 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]]]); */
                   11575:              /* FixedV[Tvar[Tage[k]]]=0; /\* HERY not sure if V7*V4*age Fixed might not exist  yet*\/ */
1.349     brouard  11576:             }else{  /* strc=Vn*Vm (and strd=age) and should be strb=Vn*Vm but want to keep original strb double product  */
                   11577:              strcpy(stre,strb); /* save full b in stre */
                   11578:              strcpy(strb,strc); /* save short c in new short b for next block strb=Vn*Vm*/
                   11579:              strcpy(strf,strc); /* save short c in new short f */
                   11580:               cutl(strc,strd,strf,'*'); /* We get strd=Vn and strc=Vm for next block (strb=Vn*Vm)*/
                   11581:              /* strcpy(strc,stre);*/ /* save full e in c for future */
                   11582:             }
                   11583:             cptcovdageprod++; /* double product with age  Which product is it? */
                   11584:             /* 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 *\/ */
                   11585:             /* cutl(strc,strd,strb,'*'); /\* strd=  V6    or   V2     or    age and  strc=  V2 or    age or    V2 *\/ */
1.234     brouard  11586:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
1.349     brouard  11587:            n=atoi(stre);
1.234     brouard  11588:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
1.349     brouard  11589:            m=atoi(strc);
                   11590:            cptcovage++; /* Counts the number of covariates which include age as a product */
                   11591:            Tage[cptcovage]=k; /* For age*V3*V2 gives the position in model of covariates associated with age Tage[1]=6 HERY too*/
                   11592:            if(existcomb[n][m] == 0){
                   11593:              /*  r /home/brouard/Documents/Recherches/REVES/Zachary/Zach-2022/Feinuo_Sun/Feinuo-threeway/femV12V15_3wayintNBe.imach */
                   11594:              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);
                   11595:              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);
                   11596:              fflush(ficlog);
                   11597:              k1++;  /* The combination Vn*Vm will be in the model so we create it at k1 */
                   11598:              k12++;
                   11599:              existcomb[n][m]=k1;
                   11600:              existcomb[m][n]=k1;
                   11601:              Tvar[k]=ncovcol+nqv+ntv+nqtv+k1;
                   11602:              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*/
                   11603:              Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 Gives the k1 double product  Vn*Vm or age*Vn*Vm at the k position */
                   11604:              Tvard[k1][1] =m; /* m 1 for V1*/
                   11605:              Tvardk[k][1] =m; /* m 1 for V1*/
                   11606:              Tvard[k1][2] =n; /* n 4 for V4*/
                   11607:              Tvardk[k][2] =n; /* n 4 for V4*/
1.351     brouard  11608: /*           Tvar[Tage[cptcovage]]=k1;*/ /* Tvar[6=age*V3*V2]=9 (new fixed covariate) */ /* We don't know about Fixed yet HERE */
1.349     brouard  11609:              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 */
                   11610:                for (i=1; i<=lastobs;i++){/* For fixed product */
                   11611:                  /* Computes the new covariate which is a product of
                   11612:                     covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   11613:                  covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   11614:                }
                   11615:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   11616:                FixedV[ncovcolt+k12]=0; /* We expand Vn*Vm */
                   11617:                k12++;
                   11618:                FixedV[ncovcolt+k12]=0;
                   11619:              }else{ /*End of FixedV */
                   11620:                cptcovprodvage++; /* Counting the number of varying covariate with age */
                   11621:                FixedV[ncovcolt+k12]=1; /* We expand Vn*Vm */
                   11622:                k12++;
                   11623:                FixedV[ncovcolt+k12]=1;
                   11624:              }
                   11625:            }else{  /* k1 Vn*Vm already exists */
                   11626:              k11=existcomb[n][m];
                   11627:              Tposprod[k]=k11; /* OK */
                   11628:              Tvar[k]=Tvar[Tprod[k11]]; /* HERY */
                   11629:              Tvardk[k][1]=m;
                   11630:              Tvardk[k][2]=n;
                   11631:              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 */
                   11632:                /*cptcovage++;*/ /* Counts the number of covariates which include age as a product */
                   11633:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   11634:                /*Tage[cptcovage]=k;*/ /* For age*V3*V2 Tage[1]=V3*V3=9 HERY too*/
                   11635:                Tvar[Tage[cptcovage]]=k1;
                   11636:                FixedV[ncovcolt+k12]=0; /* We expand Vn*Vm */
                   11637:                k12++;
                   11638:                FixedV[ncovcolt+k12]=0;
                   11639:              }else{ /* Already exists but time varying (and age) */
                   11640:                /*cptcovage++;*/ /* Counts the number of covariates which include age as a product */
                   11641:                /*Tage[cptcovage]=k;*/ /* For age*V3*V2 Tage[1]=V3*V3=9 HERY too*/
                   11642:                /* Tvar[Tage[cptcovage]]=k1; */
                   11643:                cptcovprodvage++;
                   11644:                FixedV[ncovcolt+k12]=1; /* We expand Vn*Vm */
                   11645:                k12++;
                   11646:                FixedV[ncovcolt+k12]=1;
                   11647:              }
                   11648:            }
                   11649:            /* Tage[cptcovage]=k;  /\*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   11650:            /* Tvar[k]=k11; /\* HERY *\/ */
                   11651:          } 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 */
                   11652:             cptcovprod++;
                   11653:             if (strcmp(strc,"age")==0) { /**< Model includes age: strb= Vn*age c=age d=Vn*/
                   11654:               /* covar is not filled and then is empty */
                   11655:               cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   11656:               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 */
                   11657:               Typevar[k]=1;  /* 1 for age product */
                   11658:               cptcovage++; /* Counts the number of covariates which include age as a product */
                   11659:               Tage[cptcovage]=k;  /*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   11660:              if( FixedV[Tvar[k]] == 0){
                   11661:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   11662:              }else{
                   11663:                cptcovprodvage++; /* Counting the number of fixedvarying covariate with age */
                   11664:              }
                   11665:               /*printf("stre=%s ", stre);*/
                   11666:             } else if (strcmp(strd,"age")==0) { /* strb= age*Vn c=Vn */
                   11667:               cutl(stre,strb,strc,'V');
                   11668:               Tvar[k]=atoi(stre);
                   11669:               Typevar[k]=1;  /* 1 for age product */
                   11670:               cptcovage++;
                   11671:               Tage[cptcovage]=k;
                   11672:              if( FixedV[Tvar[k]] == 0){
                   11673:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   11674:              }else{
                   11675:                cptcovprodvage++; /* Counting the number of fixedvarying covariate with age */
1.339     brouard  11676:              }
1.349     brouard  11677:             }else{ /*  for product Vn*Vm */
                   11678:              Typevar[k]=2;  /* 2 for product Vn*Vm */
                   11679:              cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   11680:              n=atoi(stre);
                   11681:              cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   11682:              m=atoi(strc);
                   11683:              k1++;
                   11684:              cptcovprodnoage++;
                   11685:              if(existcomb[n][m] != 0 || existcomb[m][n] != 0){
                   11686:                printf("Warning in model combination V%d*V%d already exists in the model in position k1=%d!\n",n,m,existcomb[n][m]);
                   11687:                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]);
                   11688:                fflush(ficlog);
                   11689:                k11=existcomb[n][m];
                   11690:                Tvar[k]=ncovcol+nqv+ntv+nqtv+k11;
                   11691:                Tposprod[k]=k11;
                   11692:                Tprod[k11]=k;
                   11693:                Tvardk[k][1] =m; /* m 1 for V1*/
                   11694:                /* Tvard[k11][1] =m; /\* n 4 for V4*\/ */
                   11695:                Tvardk[k][2] =n; /* n 4 for V4*/                
                   11696:                /* Tvard[k11][2] =n; /\* n 4 for V4*\/ */
                   11697:              }else{ /* combination Vn*Vm doesn't exist we create it (no age)*/
                   11698:                existcomb[n][m]=k1;
                   11699:                existcomb[m][n]=k1;
                   11700:                Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* ncovcolt+k1; For model-covariate k tells which data-covariate to use but
                   11701:                                                    because this model-covariate is a construction we invent a new column
                   11702:                                                    which is after existing variables ncovcol+nqv+ntv+nqtv + k1
                   11703:                                                    If already ncovcol=4 and model= V2 + V1 + V1*V4 + age*V3 + V3*V2
                   11704:                                                    thus after V4 we invent V5 and V6 because age*V3 will be computed in 4
                   11705:                                                    Tvar[3=V1*V4]=4+1=5 Tvar[5=V3*V2]=4 + 2= 6, Tvar[4=age*V3]=3 etc */
                   11706:                /* Please remark that the new variables are model dependent */
                   11707:                /* If we have 4 variable but the model uses only 3, like in
                   11708:                 * model= V1 + age*V1 + V2 + V3 + age*V2 + age*V3 + V1*V2 + V1*V3
                   11709:                 *  k=     1     2      3   4     5        6        7       8
                   11710:                 * Tvar[k]=1     1       2   3     2        3       (5       6) (and not 4 5 because of V4 missing)
                   11711:                 * Tage[kk]    [1]= 2           [2]=5      [3]=6                  kk=1 to cptcovage=3
                   11712:                 * Tvar[Tage[kk]][1]=2          [2]=2      [3]=3
                   11713:                 */
                   11714:                /* We need to feed some variables like TvarVV, but later on next loop because of ncovv (k2) is not correct */
                   11715:                Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 +V6*V2*age  */
                   11716:                Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 */
                   11717:                Tvard[k1][1] =m; /* m 1 for V1*/
                   11718:                Tvardk[k][1] =m; /* m 1 for V1*/
                   11719:                Tvard[k1][2] =n; /* n 4 for V4*/
                   11720:                Tvardk[k][2] =n; /* n 4 for V4*/
                   11721:                k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   11722:                /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   11723:                /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
                   11724:                /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
                   11725:                /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   11726:                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 */
                   11727:                  for (i=1; i<=lastobs;i++){/* For fixed product */
                   11728:                    /* Computes the new covariate which is a product of
                   11729:                       covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   11730:                    covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   11731:                  }
                   11732:                  /* TvarVV[k2]=n; */
                   11733:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11734:                  /* TvarVV[k2+1]=m; */
                   11735:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11736:                }else{ /* not FixedV */
                   11737:                  /* TvarVV[k2]=n; */
                   11738:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11739:                  /* TvarVV[k2+1]=m; */
                   11740:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11741:                }                 
                   11742:              }  /* End of creation of Vn*Vm if not created by age*Vn*Vm earlier  */
                   11743:            } /*  End of product Vn*Vm */
                   11744:           } /* End of age*double product or simple product */
                   11745:        }else { /* not a product */
1.234     brouard  11746:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   11747:          /*  scanf("%d",i);*/
                   11748:          cutl(strd,strc,strb,'V');
                   11749:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   11750:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   11751:          Tvar[k]=atoi(strd);
                   11752:          Typevar[k]=0;  /* 0 for simple covariates */
                   11753:        }
                   11754:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  11755:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  11756:                                  scanf("%d",i);*/
1.187     brouard  11757:       } /* end of loop + on total covariates */
1.351     brouard  11758: 
                   11759:       
1.187     brouard  11760:     } /* end if strlen(modelsave == 0) age*age might exist */
                   11761:   } /* end if strlen(model == 0) */
1.349     brouard  11762:   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  */
                   11763: 
1.136     brouard  11764:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   11765:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  11766:   
1.136     brouard  11767:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  11768:      printf("cptcovprod=%d ", cptcovprod);
                   11769:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   11770:      scanf("%d ",i);*/
                   11771: 
                   11772: 
1.230     brouard  11773: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   11774:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  11775: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   11776:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   11777:    k =           1    2   3     4       5       6      7      8        9
                   11778:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
1.319     brouard  11779:    Typevar[k]=   0    0   0     2       1       0      2      1        0
1.227     brouard  11780:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   11781:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   11782:          Tmodelind[combination of covar]=k;
1.225     brouard  11783: */  
                   11784: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  11785:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  11786:   /* 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  11787:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.318     brouard  11788:   printf("Model=1+age+%s\n\
1.349     brouard  11789: 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  11790: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   11791: 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  11792:   fprintf(ficlog,"Model=1+age+%s\n\
1.349     brouard  11793: 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  11794: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   11795: 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  11796:   for(k=-1;k<=NCOVMAX; k++){ Fixed[k]=0; Dummy[k]=0;}
                   11797:   for(k=1;k<=NCOVMAX; k++){TvarFind[k]=0; TvarVind[k]=0;}
1.351     brouard  11798: 
                   11799: 
                   11800:   /* Second loop for calculating  Fixed[k], Dummy[k]*/
                   11801: 
                   11802:   
1.349     brouard  11803:   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  11804:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  11805:       Fixed[k]= 0;
                   11806:       Dummy[k]= 0;
1.225     brouard  11807:       ncoveff++;
1.232     brouard  11808:       ncovf++;
1.234     brouard  11809:       nsd++;
                   11810:       modell[k].maintype= FTYPE;
                   11811:       TvarsD[nsd]=Tvar[k];
                   11812:       TvarsDind[nsd]=k;
1.330     brouard  11813:       TnsdVar[Tvar[k]]=nsd;
1.234     brouard  11814:       TvarF[ncovf]=Tvar[k];
                   11815:       TvarFind[ncovf]=k;
                   11816:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   11817:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.339     brouard  11818:     /* }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  11819:     }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  11820:       Fixed[k]= 0;
                   11821:       Dummy[k]= 1;
1.230     brouard  11822:       nqfveff++;
1.234     brouard  11823:       modell[k].maintype= FTYPE;
                   11824:       modell[k].subtype= FQ;
                   11825:       nsq++;
1.334     brouard  11826:       TvarsQ[nsq]=Tvar[k]; /* Gives the variable name (extended to products) of first nsq simple quantitative covariates (fixed or time vary see below */
                   11827:       TvarsQind[nsq]=k;    /* Gives the position in the model equation of the first nsq simple quantitative covariates (fixed or time vary) */
1.232     brouard  11828:       ncovf++;
1.234     brouard  11829:       TvarF[ncovf]=Tvar[k];
                   11830:       TvarFind[ncovf]=k;
1.231     brouard  11831:       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  11832:       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  11833:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.339     brouard  11834:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11835:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11836:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11837:       ncovvt++;
                   11838:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11839:       TvarVVind[ncovvt]=k;    /*  TvarVVind[1]=2 (second position in the model equation  */
                   11840: 
1.227     brouard  11841:       Fixed[k]= 1;
                   11842:       Dummy[k]= 0;
1.225     brouard  11843:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  11844:       modell[k].maintype= VTYPE;
                   11845:       modell[k].subtype= VD;
                   11846:       nsd++;
                   11847:       TvarsD[nsd]=Tvar[k];
                   11848:       TvarsDind[nsd]=k;
1.330     brouard  11849:       TnsdVar[Tvar[k]]=nsd; /* To be verified */
1.234     brouard  11850:       ncovv++; /* Only simple time varying variables */
                   11851:       TvarV[ncovv]=Tvar[k];
1.242     brouard  11852:       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  11853:       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 */
                   11854:       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  11855:       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);
                   11856:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  11857:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.339     brouard  11858:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11859:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11860:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11861:       ncovvt++;
                   11862:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11863:       TvarVVind[ncovvt]=k;  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11864:       
1.234     brouard  11865:       Fixed[k]= 1;
                   11866:       Dummy[k]= 1;
                   11867:       nqtveff++;
                   11868:       modell[k].maintype= VTYPE;
                   11869:       modell[k].subtype= VQ;
                   11870:       ncovv++; /* Only simple time varying variables */
                   11871:       nsq++;
1.334     brouard  11872:       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) */
                   11873:       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  11874:       TvarV[ncovv]=Tvar[k];
1.242     brouard  11875:       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  11876:       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 */
                   11877:       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  11878:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   11879:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
1.349     brouard  11880:       /* 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  11881:       /* printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv); */
1.227     brouard  11882:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  11883:       ncova++;
                   11884:       TvarA[ncova]=Tvar[k];
                   11885:       TvarAind[ncova]=k;
1.349     brouard  11886:       /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   11887:       /** 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  11888:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  11889:        Fixed[k]= 2;
                   11890:        Dummy[k]= 2;
                   11891:        modell[k].maintype= ATYPE;
                   11892:        modell[k].subtype= APFD;
1.349     brouard  11893:        ncovta++;
                   11894:        TvarAVVA[ncovta]=Tvar[k]; /*  (2)age*V3 */
                   11895:        TvarAVVAind[ncovta]=k;
1.240     brouard  11896:        /* ncoveff++; */
1.227     brouard  11897:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  11898:        Fixed[k]= 2;
                   11899:        Dummy[k]= 3;
                   11900:        modell[k].maintype= ATYPE;
                   11901:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
1.349     brouard  11902:        ncovta++;
                   11903:        TvarAVVA[ncovta]=Tvar[k]; /*   */
                   11904:        TvarAVVAind[ncovta]=k;
1.240     brouard  11905:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  11906:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  11907:        Fixed[k]= 3;
                   11908:        Dummy[k]= 2;
                   11909:        modell[k].maintype= ATYPE;
                   11910:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
1.349     brouard  11911:        ncovva++;
                   11912:        TvarVVA[ncovva]=Tvar[k]; /*  (1)+age*V6 + (2)age*V7 */
                   11913:        TvarVVAind[ncovva]=k;
                   11914:        ncovta++;
                   11915:        TvarAVVA[ncovta]=Tvar[k]; /*   */
                   11916:        TvarAVVAind[ncovta]=k;
1.240     brouard  11917:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  11918:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  11919:        Fixed[k]= 3;
                   11920:        Dummy[k]= 3;
                   11921:        modell[k].maintype= ATYPE;
                   11922:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
1.349     brouard  11923:        ncovva++;
                   11924:        TvarVVA[ncovva]=Tvar[k]; /*   */
                   11925:        TvarVVAind[ncovva]=k;
                   11926:        ncovta++;
                   11927:        TvarAVVA[ncovta]=Tvar[k]; /*  (1)+age*V6 + (2)age*V7 */
                   11928:        TvarAVVAind[ncovta]=k;
1.240     brouard  11929:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  11930:       }
1.349     brouard  11931:     }else if( Tposprod[k]>0  &&  Typevar[k]==2){  /* Detects if fixed product no age Vm*Vn */
                   11932:       printf("MEMORY ERRORR k=%d  Tposprod[k]=%d, Typevar[k]=%d\n ",k, Tposprod[k], Typevar[k]);
                   11933:       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 */
                   11934:       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]]);
                   11935:        Fixed[k]= 0;
                   11936:        Dummy[k]= 0;
                   11937:        ncoveff++;
                   11938:        ncovf++;
                   11939:        /* ncovv++; */
                   11940:        /* TvarVV[ncovv]=Tvardk[k][1]; */
                   11941:        /* FixedV[ncovcolt+ncovv]=0; /\* or FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11942:        /* ncovv++; */
                   11943:        /* TvarVV[ncovv]=Tvardk[k][2]; */
                   11944:        /* FixedV[ncovcolt+ncovv]=0; /\* or FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11945:        modell[k].maintype= FTYPE;
                   11946:        TvarF[ncovf]=Tvar[k];
                   11947:        /* TnsdVar[Tvar[k]]=nsd; */ /* To be done */
                   11948:        TvarFind[ncovf]=k;
                   11949:        TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   11950:        TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   11951:       }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  */
                   11952:        /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11953:        /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age*/
                   11954:        /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11955:        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 */
                   11956:        ncovvt++;
                   11957:        TvarVV[ncovvt]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
                   11958:        TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   11959:        ncovvt++;
                   11960:        TvarVV[ncovvt]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
                   11961:        TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   11962:        
                   11963:        /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   11964:        /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
                   11965:        
                   11966:        if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   11967:          if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
                   11968:            Fixed[k]= 1;
                   11969:            Dummy[k]= 0;
                   11970:            modell[k].maintype= FTYPE;
                   11971:            modell[k].subtype= FPDD;            /*      Product fixed dummy * fixed dummy */
                   11972:            ncovf++; /* Fixed variables without age */
                   11973:            TvarF[ncovf]=Tvar[k];
                   11974:            TvarFind[ncovf]=k;
                   11975:          }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
                   11976:            Fixed[k]= 0;  /* Fixed product */
                   11977:            Dummy[k]= 1;
                   11978:            modell[k].maintype= FTYPE;
                   11979:            modell[k].subtype= FPDQ;            /*      Product fixed dummy * fixed quantitative */
                   11980:            ncovf++; /* Varying variables without age */
                   11981:            TvarF[ncovf]=Tvar[k];
                   11982:            TvarFind[ncovf]=k;
                   11983:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
                   11984:            Fixed[k]= 1;
                   11985:            Dummy[k]= 0;
                   11986:            modell[k].maintype= VTYPE;
                   11987:            modell[k].subtype= VPDD;            /*      Product fixed dummy * varying dummy */
                   11988:            ncovv++; /* Varying variables without age */
                   11989:            TvarV[ncovv]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
                   11990:            TvarVind[ncovv]=k;/* TvarVind[1]=5 */ 
                   11991:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
                   11992:            Fixed[k]= 1;
                   11993:            Dummy[k]= 1;
                   11994:            modell[k].maintype= VTYPE;
                   11995:            modell[k].subtype= VPDQ;            /*      Product fixed dummy * varying quantitative */
                   11996:            ncovv++; /* Varying variables without age */
                   11997:            TvarV[ncovv]=Tvar[k];
                   11998:            TvarVind[ncovv]=k;
                   11999:          }
                   12000:        }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   12001:          if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
                   12002:            Fixed[k]= 0;  /*  Fixed product */
                   12003:            Dummy[k]= 1;
                   12004:            modell[k].maintype= FTYPE;
                   12005:            modell[k].subtype= FPDQ;            /*      Product fixed quantitative * fixed dummy */
                   12006:            ncovf++; /* Fixed variables without age */
                   12007:            TvarF[ncovf]=Tvar[k];
                   12008:            TvarFind[ncovf]=k;
                   12009:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
                   12010:            Fixed[k]= 1;
                   12011:            Dummy[k]= 1;
                   12012:            modell[k].maintype= VTYPE;
                   12013:            modell[k].subtype= VPDQ;            /*      Product fixed quantitative * varying dummy */
                   12014:            ncovv++; /* Varying variables without age */
                   12015:            TvarV[ncovv]=Tvar[k];
                   12016:            TvarVind[ncovv]=k;
                   12017:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
                   12018:            Fixed[k]= 1;
                   12019:            Dummy[k]= 1;
                   12020:            modell[k].maintype= VTYPE;
                   12021:            modell[k].subtype= VPQQ;            /*      Product fixed quantitative * varying quantitative */
                   12022:            ncovv++; /* Varying variables without age */
                   12023:            TvarV[ncovv]=Tvar[k];
                   12024:            TvarVind[ncovv]=k;
                   12025:            ncovv++; /* Varying variables without age */
                   12026:            TvarV[ncovv]=Tvar[k];
                   12027:            TvarVind[ncovv]=k;
                   12028:          }
                   12029:        }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
                   12030:          if(Tvard[k1][2] <=ncovcol){
                   12031:            Fixed[k]= 1;
                   12032:            Dummy[k]= 1;
                   12033:            modell[k].maintype= VTYPE;
                   12034:            modell[k].subtype= VPDD;            /*      Product time varying dummy * fixed dummy */
                   12035:            ncovv++; /* Varying variables without age */
                   12036:            TvarV[ncovv]=Tvar[k];
                   12037:            TvarVind[ncovv]=k;
                   12038:          }else if(Tvard[k1][2] <=ncovcol+nqv){
                   12039:            Fixed[k]= 1;
                   12040:            Dummy[k]= 1;
                   12041:            modell[k].maintype= VTYPE;
                   12042:            modell[k].subtype= VPDQ;            /*      Product time varying dummy * fixed quantitative */
                   12043:            ncovv++; /* Varying variables without age */
                   12044:            TvarV[ncovv]=Tvar[k];
                   12045:            TvarVind[ncovv]=k;
                   12046:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   12047:            Fixed[k]= 1;
                   12048:            Dummy[k]= 0;
                   12049:            modell[k].maintype= VTYPE;
                   12050:            modell[k].subtype= VPDD;            /*      Product time varying dummy * time varying dummy */
                   12051:            ncovv++; /* Varying variables without age */
                   12052:            TvarV[ncovv]=Tvar[k];
                   12053:            TvarVind[ncovv]=k;
                   12054:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   12055:            Fixed[k]= 1;
                   12056:            Dummy[k]= 1;
                   12057:            modell[k].maintype= VTYPE;
                   12058:            modell[k].subtype= VPDQ;            /*      Product time varying dummy * time varying quantitative */
                   12059:            ncovv++; /* Varying variables without age */
                   12060:            TvarV[ncovv]=Tvar[k];
                   12061:            TvarVind[ncovv]=k;
                   12062:          }
                   12063:        }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
                   12064:          if(Tvard[k1][2] <=ncovcol){
                   12065:            Fixed[k]= 1;
                   12066:            Dummy[k]= 1;
                   12067:            modell[k].maintype= VTYPE;
                   12068:            modell[k].subtype= VPDQ;            /*      Product time varying quantitative * fixed dummy */
                   12069:            ncovv++; /* Varying variables without age */
                   12070:            TvarV[ncovv]=Tvar[k];
                   12071:            TvarVind[ncovv]=k;
                   12072:          }else if(Tvard[k1][2] <=ncovcol+nqv){
                   12073:            Fixed[k]= 1;
                   12074:            Dummy[k]= 1;
                   12075:            modell[k].maintype= VTYPE;
                   12076:            modell[k].subtype= VPQQ;            /*      Product time varying quantitative * fixed quantitative */
                   12077:            ncovv++; /* Varying variables without age */
                   12078:            TvarV[ncovv]=Tvar[k];
                   12079:            TvarVind[ncovv]=k;
                   12080:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   12081:            Fixed[k]= 1;
                   12082:            Dummy[k]= 1;
                   12083:            modell[k].maintype= VTYPE;
                   12084:            modell[k].subtype= VPDQ;            /*      Product time varying quantitative * time varying dummy */
                   12085:            ncovv++; /* Varying variables without age */
                   12086:            TvarV[ncovv]=Tvar[k];
                   12087:            TvarVind[ncovv]=k;
                   12088:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   12089:            Fixed[k]= 1;
                   12090:            Dummy[k]= 1;
                   12091:            modell[k].maintype= VTYPE;
                   12092:            modell[k].subtype= VPQQ;            /*      Product time varying quantitative * time varying quantitative */
                   12093:            ncovv++; /* Varying variables without age */
                   12094:            TvarV[ncovv]=Tvar[k];
                   12095:            TvarVind[ncovv]=k;
                   12096:          }
                   12097:        }else{
                   12098:          printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   12099:          fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   12100:        } /*end k1*/
                   12101:       }
                   12102:     }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  12103:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
1.349     brouard  12104:       /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age*/
                   12105:       /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   12106:       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 */
                   12107:       ncova++;
                   12108:       TvarA[ncova]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
                   12109:       TvarAind[ncova]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   12110:       ncova++;
                   12111:       TvarA[ncova]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
                   12112:       TvarAind[ncova]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
1.339     brouard  12113: 
1.349     brouard  12114:       /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   12115:       /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
                   12116:       if( FixedV[Tvardk[k][1]] == 0 && FixedV[Tvardk[k][2]] == 0){
                   12117:        ncovta++;
                   12118:        TvarAVVA[ncovta]=Tvard[k1][1]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   12119:        TvarAVVAind[ncovta]=k;
                   12120:        ncovta++;
                   12121:        TvarAVVA[ncovta]=Tvard[k1][2]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   12122:        TvarAVVAind[ncovta]=k;
                   12123:       }else{
                   12124:        ncovva++;  /* HERY  reached */
                   12125:        TvarVVA[ncovva]=Tvard[k1][1]; /*  age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4  */
                   12126:        TvarVVAind[ncovva]=k;
                   12127:        ncovva++;
                   12128:        TvarVVA[ncovva]=Tvard[k1][2]; /*   */
                   12129:        TvarVVAind[ncovva]=k;
                   12130:        ncovta++;
                   12131:        TvarAVVA[ncovta]=Tvard[k1][1]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   12132:        TvarAVVAind[ncovta]=k;
                   12133:        ncovta++;
                   12134:        TvarAVVA[ncovta]=Tvard[k1][2]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   12135:        TvarAVVAind[ncovta]=k;
                   12136:       }
1.339     brouard  12137:       if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   12138:        if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
1.349     brouard  12139:          Fixed[k]= 2;
                   12140:          Dummy[k]= 2;
1.240     brouard  12141:          modell[k].maintype= FTYPE;
                   12142:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
1.349     brouard  12143:          /* TvarF[ncova]=Tvar[k];   /\* Problem to solve *\/ */
                   12144:          /* TvarFind[ncova]=k; */
1.339     brouard  12145:        }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
1.349     brouard  12146:          Fixed[k]= 2;  /* Fixed product */
                   12147:          Dummy[k]= 3;
1.240     brouard  12148:          modell[k].maintype= FTYPE;
                   12149:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
1.349     brouard  12150:          /* TvarF[ncova]=Tvar[k]; */
                   12151:          /* TvarFind[ncova]=k; */
1.339     brouard  12152:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
1.349     brouard  12153:          Fixed[k]= 3;
                   12154:          Dummy[k]= 2;
1.240     brouard  12155:          modell[k].maintype= VTYPE;
                   12156:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
1.349     brouard  12157:          TvarV[ncova]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
                   12158:          TvarVind[ncova]=k;/* TvarVind[1]=5 */ 
1.339     brouard  12159:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
1.349     brouard  12160:          Fixed[k]= 3;
                   12161:          Dummy[k]= 3;
1.240     brouard  12162:          modell[k].maintype= VTYPE;
                   12163:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
1.349     brouard  12164:          /* ncovv++; /\* Varying variables without age *\/ */
                   12165:          /* TvarV[ncovv]=Tvar[k]; */
                   12166:          /* TvarVind[ncovv]=k; */
1.240     brouard  12167:        }
1.339     brouard  12168:       }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   12169:        if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
1.349     brouard  12170:          Fixed[k]= 2;  /*  Fixed product */
                   12171:          Dummy[k]= 2;
1.240     brouard  12172:          modell[k].maintype= FTYPE;
                   12173:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
1.349     brouard  12174:          /* ncova++; /\* Fixed variables with age *\/ */
                   12175:          /* TvarF[ncovf]=Tvar[k]; */
                   12176:          /* TvarFind[ncovf]=k; */
1.339     brouard  12177:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
1.349     brouard  12178:          Fixed[k]= 2;
                   12179:          Dummy[k]= 3;
1.240     brouard  12180:          modell[k].maintype= VTYPE;
                   12181:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
1.349     brouard  12182:          /* ncova++; /\* Varying variables with age *\/ */
                   12183:          /* TvarV[ncova]=Tvar[k]; */
                   12184:          /* TvarVind[ncova]=k; */
1.339     brouard  12185:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
1.349     brouard  12186:          Fixed[k]= 3;
                   12187:          Dummy[k]= 2;
1.240     brouard  12188:          modell[k].maintype= VTYPE;
                   12189:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
1.349     brouard  12190:          ncova++; /* Varying variables without age */
                   12191:          TvarV[ncova]=Tvar[k];
                   12192:          TvarVind[ncova]=k;
                   12193:          /* ncova++; /\* Varying variables without age *\/ */
                   12194:          /* TvarV[ncova]=Tvar[k]; */
                   12195:          /* TvarVind[ncova]=k; */
1.240     brouard  12196:        }
1.339     brouard  12197:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
1.240     brouard  12198:        if(Tvard[k1][2] <=ncovcol){
1.349     brouard  12199:          Fixed[k]= 2;
                   12200:          Dummy[k]= 2;
1.240     brouard  12201:          modell[k].maintype= VTYPE;
                   12202:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
1.349     brouard  12203:          /* ncova++; /\* Varying variables with age *\/ */
                   12204:          /* TvarV[ncova]=Tvar[k]; */
                   12205:          /* TvarVind[ncova]=k; */
1.240     brouard  12206:        }else if(Tvard[k1][2] <=ncovcol+nqv){
1.349     brouard  12207:          Fixed[k]= 2;
                   12208:          Dummy[k]= 3;
1.240     brouard  12209:          modell[k].maintype= VTYPE;
                   12210:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
1.349     brouard  12211:          /* ncova++; /\* Varying variables with age *\/ */
                   12212:          /* TvarV[ncova]=Tvar[k]; */
                   12213:          /* TvarVind[ncova]=k; */
1.240     brouard  12214:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
1.349     brouard  12215:          Fixed[k]= 3;
                   12216:          Dummy[k]= 2;
1.240     brouard  12217:          modell[k].maintype= VTYPE;
                   12218:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
1.349     brouard  12219:          /* ncova++; /\* Varying variables with age *\/ */
                   12220:          /* TvarV[ncova]=Tvar[k]; */
                   12221:          /* TvarVind[ncova]=k; */
1.240     brouard  12222:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
1.349     brouard  12223:          Fixed[k]= 3;
                   12224:          Dummy[k]= 3;
1.240     brouard  12225:          modell[k].maintype= VTYPE;
                   12226:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
1.349     brouard  12227:          /* ncova++; /\* Varying variables with age *\/ */
                   12228:          /* TvarV[ncova]=Tvar[k]; */
                   12229:          /* TvarVind[ncova]=k; */
1.240     brouard  12230:        }
1.339     brouard  12231:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
1.240     brouard  12232:        if(Tvard[k1][2] <=ncovcol){
1.349     brouard  12233:          Fixed[k]= 2;
                   12234:          Dummy[k]= 2;
1.240     brouard  12235:          modell[k].maintype= VTYPE;
                   12236:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
1.349     brouard  12237:          /* ncova++; /\* Varying variables with age *\/ */
                   12238:          /* TvarV[ncova]=Tvar[k]; */
                   12239:          /* TvarVind[ncova]=k; */
1.240     brouard  12240:        }else if(Tvard[k1][2] <=ncovcol+nqv){
1.349     brouard  12241:          Fixed[k]= 2;
                   12242:          Dummy[k]= 3;
1.240     brouard  12243:          modell[k].maintype= VTYPE;
                   12244:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
1.349     brouard  12245:          /* ncova++; /\* Varying variables with age *\/ */
                   12246:          /* TvarV[ncova]=Tvar[k]; */
                   12247:          /* TvarVind[ncova]=k; */
1.240     brouard  12248:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
1.349     brouard  12249:          Fixed[k]= 3;
                   12250:          Dummy[k]= 2;
1.240     brouard  12251:          modell[k].maintype= VTYPE;
                   12252:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
1.349     brouard  12253:          /* ncova++; /\* Varying variables with age *\/ */
                   12254:          /* TvarV[ncova]=Tvar[k]; */
                   12255:          /* TvarVind[ncova]=k; */
1.240     brouard  12256:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
1.349     brouard  12257:          Fixed[k]= 3;
                   12258:          Dummy[k]= 3;
1.240     brouard  12259:          modell[k].maintype= VTYPE;
                   12260:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
1.349     brouard  12261:          /* ncova++; /\* Varying variables with age *\/ */
                   12262:          /* TvarV[ncova]=Tvar[k]; */
                   12263:          /* TvarVind[ncova]=k; */
1.240     brouard  12264:        }
1.227     brouard  12265:       }else{
1.240     brouard  12266:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   12267:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   12268:       } /*end k1*/
1.349     brouard  12269:     } else{
1.226     brouard  12270:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   12271:       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  12272:     }
1.342     brouard  12273:     /* 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]); */
                   12274:     /* printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype); */
1.227     brouard  12275:     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]);
                   12276:   }
1.349     brouard  12277:   ncovvta=ncovva;
1.227     brouard  12278:   /* Searching for doublons in the model */
                   12279:   for(k1=1; k1<= cptcovt;k1++){
                   12280:     for(k2=1; k2 <k1;k2++){
1.285     brouard  12281:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   12282:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  12283:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   12284:          if(Tvar[k1]==Tvar[k2]){
1.338     brouard  12285:            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]);
                   12286:            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  12287:            return(1);
                   12288:          }
                   12289:        }else if (Typevar[k1] ==2){
                   12290:          k3=Tposprod[k1];
                   12291:          k4=Tposprod[k2];
                   12292:          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  12293:            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]]);
                   12294:            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  12295:            return(1);
                   12296:          }
                   12297:        }
1.227     brouard  12298:       }
                   12299:     }
1.225     brouard  12300:   }
                   12301:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   12302:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  12303:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   12304:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.349     brouard  12305: 
                   12306:   free_imatrix(existcomb,1,NCOVMAX,1,NCOVMAX);
1.137     brouard  12307:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  12308:   /*endread:*/
1.225     brouard  12309:   printf("Exiting decodemodel: ");
                   12310:   return (1);
1.136     brouard  12311: }
                   12312: 
1.169     brouard  12313: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  12314: {/* Check ages at death */
1.136     brouard  12315:   int i, m;
1.218     brouard  12316:   int firstone=0;
                   12317:   
1.136     brouard  12318:   for (i=1; i<=imx; i++) {
                   12319:     for(m=2; (m<= maxwav); m++) {
                   12320:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   12321:        anint[m][i]=9999;
1.216     brouard  12322:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   12323:          s[m][i]=-1;
1.136     brouard  12324:       }
                   12325:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  12326:        *nberr = *nberr + 1;
1.218     brouard  12327:        if(firstone == 0){
                   12328:          firstone=1;
1.260     brouard  12329:        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  12330:        }
1.262     brouard  12331:        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  12332:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  12333:       }
                   12334:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  12335:        (*nberr)++;
1.259     brouard  12336:        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  12337:        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  12338:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  12339:       }
                   12340:     }
                   12341:   }
                   12342: 
                   12343:   for (i=1; i<=imx; i++)  {
                   12344:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   12345:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  12346:       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  12347:        if (s[m][i] >= nlstate+1) {
1.169     brouard  12348:          if(agedc[i]>0){
                   12349:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  12350:              agev[m][i]=agedc[i];
1.214     brouard  12351:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  12352:            }else {
1.136     brouard  12353:              if ((int)andc[i]!=9999){
                   12354:                nbwarn++;
                   12355:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   12356:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   12357:                agev[m][i]=-1;
                   12358:              }
                   12359:            }
1.169     brouard  12360:          } /* agedc > 0 */
1.214     brouard  12361:        } /* end if */
1.136     brouard  12362:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   12363:                                 years but with the precision of a month */
                   12364:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   12365:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   12366:            agev[m][i]=1;
                   12367:          else if(agev[m][i] < *agemin){ 
                   12368:            *agemin=agev[m][i];
                   12369:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   12370:          }
                   12371:          else if(agev[m][i] >*agemax){
                   12372:            *agemax=agev[m][i];
1.156     brouard  12373:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  12374:          }
                   12375:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   12376:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  12377:        } /* en if 9*/
1.136     brouard  12378:        else { /* =9 */
1.214     brouard  12379:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  12380:          agev[m][i]=1;
                   12381:          s[m][i]=-1;
                   12382:        }
                   12383:       }
1.214     brouard  12384:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  12385:        agev[m][i]=1;
1.214     brouard  12386:       else{
                   12387:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   12388:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   12389:        agev[m][i]=0;
                   12390:       }
                   12391:     } /* End for lastpass */
                   12392:   }
1.136     brouard  12393:     
                   12394:   for (i=1; i<=imx; i++)  {
                   12395:     for(m=firstpass; (m<=lastpass); m++){
                   12396:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  12397:        (*nberr)++;
1.136     brouard  12398:        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);     
                   12399:        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);     
                   12400:        return 1;
                   12401:       }
                   12402:     }
                   12403:   }
                   12404: 
                   12405:   /*for (i=1; i<=imx; i++){
                   12406:   for (m=firstpass; (m<lastpass); m++){
                   12407:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   12408: }
                   12409: 
                   12410: }*/
                   12411: 
                   12412: 
1.139     brouard  12413:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   12414:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  12415: 
                   12416:   return (0);
1.164     brouard  12417:  /* endread:*/
1.136     brouard  12418:     printf("Exiting calandcheckages: ");
                   12419:     return (1);
                   12420: }
                   12421: 
1.172     brouard  12422: #if defined(_MSC_VER)
                   12423: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   12424: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   12425: //#include "stdafx.h"
                   12426: //#include <stdio.h>
                   12427: //#include <tchar.h>
                   12428: //#include <windows.h>
                   12429: //#include <iostream>
                   12430: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   12431: 
                   12432: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   12433: 
                   12434: BOOL IsWow64()
                   12435: {
                   12436:        BOOL bIsWow64 = FALSE;
                   12437: 
                   12438:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   12439:        //  (HANDLE, PBOOL);
                   12440: 
                   12441:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   12442: 
                   12443:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   12444:        const char funcName[] = "IsWow64Process";
                   12445:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   12446:                GetProcAddress(module, funcName);
                   12447: 
                   12448:        if (NULL != fnIsWow64Process)
                   12449:        {
                   12450:                if (!fnIsWow64Process(GetCurrentProcess(),
                   12451:                        &bIsWow64))
                   12452:                        //throw std::exception("Unknown error");
                   12453:                        printf("Unknown error\n");
                   12454:        }
                   12455:        return bIsWow64 != FALSE;
                   12456: }
                   12457: #endif
1.177     brouard  12458: 
1.191     brouard  12459: void syscompilerinfo(int logged)
1.292     brouard  12460: {
                   12461: #include <stdint.h>
                   12462: 
                   12463:   /* #include "syscompilerinfo.h"*/
1.185     brouard  12464:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   12465:    /* /GS /W3 /Gy
                   12466:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   12467:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   12468:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  12469:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   12470:    */ 
                   12471:    /* 64 bits */
1.185     brouard  12472:    /*
                   12473:      /GS /W3 /Gy
                   12474:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   12475:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   12476:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   12477:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   12478:    /* Optimization are useless and O3 is slower than O2 */
                   12479:    /*
                   12480:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   12481:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   12482:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   12483:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   12484:    */
1.186     brouard  12485:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  12486:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   12487:       /PDB:"visual studio
                   12488:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   12489:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   12490:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   12491:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   12492:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   12493:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   12494:       uiAccess='false'"
                   12495:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   12496:       /NOLOGO /TLBID:1
                   12497:    */
1.292     brouard  12498: 
                   12499: 
1.177     brouard  12500: #if defined __INTEL_COMPILER
1.178     brouard  12501: #if defined(__GNUC__)
                   12502:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   12503: #endif
1.177     brouard  12504: #elif defined(__GNUC__) 
1.179     brouard  12505: #ifndef  __APPLE__
1.174     brouard  12506: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  12507: #endif
1.177     brouard  12508:    struct utsname sysInfo;
1.178     brouard  12509:    int cross = CROSS;
                   12510:    if (cross){
                   12511:           printf("Cross-");
1.191     brouard  12512:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  12513:    }
1.174     brouard  12514: #endif
                   12515: 
1.191     brouard  12516:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  12517: #if defined(__clang__)
1.191     brouard  12518:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  12519: #endif
                   12520: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  12521:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  12522: #endif
                   12523: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  12524:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  12525: #endif
                   12526: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  12527:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  12528: #endif
                   12529: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  12530:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  12531: #endif
                   12532: #if defined(_MSC_VER)
1.191     brouard  12533:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  12534: #endif
                   12535: #if defined(__PGI)
1.191     brouard  12536:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  12537: #endif
                   12538: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  12539:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  12540: #endif
1.191     brouard  12541:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  12542:    
1.167     brouard  12543: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   12544: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   12545:     // Windows (x64 and x86)
1.191     brouard  12546:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  12547: #elif __unix__ // all unices, not all compilers
                   12548:     // Unix
1.191     brouard  12549:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  12550: #elif __linux__
                   12551:     // linux
1.191     brouard  12552:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  12553: #elif __APPLE__
1.174     brouard  12554:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  12555:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  12556: #endif
                   12557: 
                   12558: /*  __MINGW32__          */
                   12559: /*  __CYGWIN__  */
                   12560: /* __MINGW64__  */
                   12561: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   12562: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   12563: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   12564: /* _WIN64  // Defined for applications for Win64. */
                   12565: /* _M_X64 // Defined for compilations that target x64 processors. */
                   12566: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  12567: 
1.167     brouard  12568: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  12569:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  12570: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  12571:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  12572: #else
1.191     brouard  12573:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  12574: #endif
                   12575: 
1.169     brouard  12576: #if defined(__GNUC__)
                   12577: # if defined(__GNUC_PATCHLEVEL__)
                   12578: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   12579:                             + __GNUC_MINOR__ * 100 \
                   12580:                             + __GNUC_PATCHLEVEL__)
                   12581: # else
                   12582: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   12583:                             + __GNUC_MINOR__ * 100)
                   12584: # endif
1.174     brouard  12585:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  12586:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  12587: 
                   12588:    if (uname(&sysInfo) != -1) {
                   12589:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  12590:         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  12591:    }
                   12592:    else
                   12593:       perror("uname() error");
1.179     brouard  12594:    //#ifndef __INTEL_COMPILER 
                   12595: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  12596:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  12597:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  12598: #endif
1.169     brouard  12599: #endif
1.172     brouard  12600: 
1.286     brouard  12601:    //   void main ()
1.172     brouard  12602:    //   {
1.169     brouard  12603: #if defined(_MSC_VER)
1.174     brouard  12604:    if (IsWow64()){
1.191     brouard  12605:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   12606:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  12607:    }
                   12608:    else{
1.191     brouard  12609:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   12610:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  12611:    }
1.172     brouard  12612:    //     printf("\nPress Enter to continue...");
                   12613:    //     getchar();
                   12614:    //   }
                   12615: 
1.169     brouard  12616: #endif
                   12617:    
1.167     brouard  12618: 
1.219     brouard  12619: }
1.136     brouard  12620: 
1.219     brouard  12621: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  12622:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.332     brouard  12623:   /* Computes the prevalence limit for each combination of the dummy covariates */
1.235     brouard  12624:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  12625:   /* double ftolpl = 1.e-10; */
1.180     brouard  12626:   double age, agebase, agelim;
1.203     brouard  12627:   double tot;
1.180     brouard  12628: 
1.202     brouard  12629:   strcpy(filerespl,"PL_");
                   12630:   strcat(filerespl,fileresu);
                   12631:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  12632:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   12633:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  12634:   }
1.288     brouard  12635:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   12636:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  12637:   pstamp(ficrespl);
1.288     brouard  12638:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  12639:   fprintf(ficrespl,"#Age ");
                   12640:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   12641:   fprintf(ficrespl,"\n");
1.180     brouard  12642:   
1.219     brouard  12643:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  12644: 
1.219     brouard  12645:   agebase=ageminpar;
                   12646:   agelim=agemaxpar;
1.180     brouard  12647: 
1.227     brouard  12648:   /* i1=pow(2,ncoveff); */
1.234     brouard  12649:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  12650:   if (cptcovn < 1){i1=1;}
1.180     brouard  12651: 
1.337     brouard  12652:   /* for(k=1; k<=i1;k++){ /\* For each combination k of dummy covariates in the model *\/ */
1.238     brouard  12653:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  12654:       k=TKresult[nres];
1.338     brouard  12655:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12656:       /* if(i1 != 1 && TKresult[nres]!= k) /\* We found the combination k corresponding to the resultline value of dummies *\/ */
                   12657:       /*       continue; */
1.235     brouard  12658: 
1.238     brouard  12659:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12660:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   12661:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   12662:       /* k=k+1; */
                   12663:       /* to clean */
1.332     brouard  12664:       /*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*/
1.238     brouard  12665:       fprintf(ficrespl,"#******");
                   12666:       printf("#******");
                   12667:       fprintf(ficlog,"#******");
1.337     brouard  12668:       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  12669:        /* fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Here problem for varying dummy*\/ */
1.337     brouard  12670:        /* printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12671:        /* fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12672:        fprintf(ficrespl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12673:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12674:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12675:       }
                   12676:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   12677:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12678:       /*       fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12679:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12680:       /* } */
1.238     brouard  12681:       fprintf(ficrespl,"******\n");
                   12682:       printf("******\n");
                   12683:       fprintf(ficlog,"******\n");
                   12684:       if(invalidvarcomb[k]){
                   12685:        printf("\nCombination (%d) ignored because no case \n",k); 
                   12686:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   12687:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   12688:        continue;
                   12689:       }
1.219     brouard  12690: 
1.238     brouard  12691:       fprintf(ficrespl,"#Age ");
1.337     brouard  12692:       /* for(j=1;j<=cptcoveff;j++) { */
                   12693:       /*       fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12694:       /* } */
                   12695:       for(j=1;j<=cptcovs;j++) { /* New the quanti variable is added */
                   12696:        fprintf(ficrespl,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12697:       }
                   12698:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   12699:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  12700:     
1.238     brouard  12701:       for (age=agebase; age<=agelim; age++){
                   12702:        /* for (age=agebase; age<=agebase; age++){ */
1.337     brouard  12703:        /**< Computes the prevalence limit in each live state at age x and for covariate combination (k and) nres */
                   12704:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres); /* Nicely done */
1.238     brouard  12705:        fprintf(ficrespl,"%.0f ",age );
1.337     brouard  12706:        /* for(j=1;j<=cptcoveff;j++) */
                   12707:        /*   fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12708:        for(j=1;j<=cptcovs;j++)
                   12709:          fprintf(ficrespl,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12710:        tot=0.;
                   12711:        for(i=1; i<=nlstate;i++){
                   12712:          tot +=  prlim[i][i];
                   12713:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   12714:        }
                   12715:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   12716:       } /* Age */
                   12717:       /* was end of cptcod */
1.337     brouard  12718:     } /* nres */
                   12719:   /* } /\* for each combination *\/ */
1.219     brouard  12720:   return 0;
1.180     brouard  12721: }
                   12722: 
1.218     brouard  12723: 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  12724:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  12725:        
                   12726:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   12727:    * at any age between ageminpar and agemaxpar
                   12728:         */
1.235     brouard  12729:   int i, j, k, i1, nres=0 ;
1.217     brouard  12730:   /* double ftolpl = 1.e-10; */
                   12731:   double age, agebase, agelim;
                   12732:   double tot;
1.218     brouard  12733:   /* double ***mobaverage; */
                   12734:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  12735: 
                   12736:   strcpy(fileresplb,"PLB_");
                   12737:   strcat(fileresplb,fileresu);
                   12738:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  12739:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   12740:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  12741:   }
1.288     brouard  12742:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   12743:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  12744:   pstamp(ficresplb);
1.288     brouard  12745:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  12746:   fprintf(ficresplb,"#Age ");
                   12747:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   12748:   fprintf(ficresplb,"\n");
                   12749:   
1.218     brouard  12750:   
                   12751:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   12752:   
                   12753:   agebase=ageminpar;
                   12754:   agelim=agemaxpar;
                   12755:   
                   12756:   
1.227     brouard  12757:   i1=pow(2,cptcoveff);
1.218     brouard  12758:   if (cptcovn < 1){i1=1;}
1.227     brouard  12759:   
1.238     brouard  12760:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.338     brouard  12761:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   12762:       k=TKresult[nres];
                   12763:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   12764:      /* if(i1 != 1 && TKresult[nres]!= k) */
                   12765:      /*        continue; */
                   12766:      /* /\*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*\/ */
1.238     brouard  12767:       fprintf(ficresplb,"#******");
                   12768:       printf("#******");
                   12769:       fprintf(ficlog,"#******");
1.338     brouard  12770:       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) */
                   12771:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12772:        fprintf(ficresplb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12773:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12774:       }
1.338     brouard  12775:       /* for(j=1;j<=cptcoveff ;j++) {/\* all covariates *\/ */
                   12776:       /*       fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12777:       /*       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12778:       /*       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12779:       /* } */
                   12780:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   12781:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12782:       /*       fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12783:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12784:       /* } */
1.238     brouard  12785:       fprintf(ficresplb,"******\n");
                   12786:       printf("******\n");
                   12787:       fprintf(ficlog,"******\n");
                   12788:       if(invalidvarcomb[k]){
                   12789:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   12790:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   12791:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   12792:        continue;
                   12793:       }
1.218     brouard  12794:     
1.238     brouard  12795:       fprintf(ficresplb,"#Age ");
1.338     brouard  12796:       for(j=1;j<=cptcovs;j++) {
                   12797:        fprintf(ficresplb,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12798:       }
                   12799:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   12800:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  12801:     
                   12802:     
1.238     brouard  12803:       for (age=agebase; age<=agelim; age++){
                   12804:        /* for (age=agebase; age<=agebase; age++){ */
                   12805:        if(mobilavproj > 0){
                   12806:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   12807:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  12808:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  12809:        }else if (mobilavproj == 0){
                   12810:          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);
                   12811:          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);
                   12812:          exit(1);
                   12813:        }else{
                   12814:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  12815:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  12816:          /* printf("TOTOT\n"); */
                   12817:           /* exit(1); */
1.238     brouard  12818:        }
                   12819:        fprintf(ficresplb,"%.0f ",age );
1.338     brouard  12820:        for(j=1;j<=cptcovs;j++)
                   12821:          fprintf(ficresplb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12822:        tot=0.;
                   12823:        for(i=1; i<=nlstate;i++){
                   12824:          tot +=  bprlim[i][i];
                   12825:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   12826:        }
                   12827:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   12828:       } /* Age */
                   12829:       /* was end of cptcod */
1.255     brouard  12830:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.338     brouard  12831:     /* } /\* end of any combination *\/ */
1.238     brouard  12832:   } /* end of nres */  
1.218     brouard  12833:   /* hBijx(p, bage, fage); */
                   12834:   /* fclose(ficrespijb); */
                   12835:   
                   12836:   return 0;
1.217     brouard  12837: }
1.218     brouard  12838:  
1.180     brouard  12839: int hPijx(double *p, int bage, int fage){
                   12840:     /*------------- h Pij x at various ages ------------*/
1.336     brouard  12841:   /* to be optimized with precov */
1.180     brouard  12842:   int stepsize;
                   12843:   int agelim;
                   12844:   int hstepm;
                   12845:   int nhstepm;
1.235     brouard  12846:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  12847: 
                   12848:   double agedeb;
                   12849:   double ***p3mat;
                   12850: 
1.337     brouard  12851:   strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
                   12852:   if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   12853:     printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   12854:     fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   12855:   }
                   12856:   printf("Computing pij: result on file '%s' \n", filerespij);
                   12857:   fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   12858:   
                   12859:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   12860:   /*if (stepm<=24) stepsize=2;*/
                   12861:   
                   12862:   agelim=AGESUP;
                   12863:   hstepm=stepsize*YEARM; /* Every year of age */
                   12864:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   12865:   
                   12866:   /* hstepm=1;   aff par mois*/
                   12867:   pstamp(ficrespij);
                   12868:   fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   12869:   i1= pow(2,cptcoveff);
                   12870:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12871:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   12872:   /*   k=k+1;  */
                   12873:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   12874:     k=TKresult[nres];
1.338     brouard  12875:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12876:     /* for(k=1; k<=i1;k++){ */
                   12877:     /* if(i1 != 1 && TKresult[nres]!= k) */
                   12878:     /*         continue; */
                   12879:     fprintf(ficrespij,"\n#****** ");
                   12880:     for(j=1;j<=cptcovs;j++){
                   12881:       fprintf(ficrespij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12882:       /* fprintf(ficrespij,"@wV%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12883:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   12884:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12885:       /*       fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12886:     }
                   12887:     fprintf(ficrespij,"******\n");
                   12888:     
                   12889:     for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   12890:       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   12891:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   12892:       
                   12893:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   12894:       
                   12895:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12896:       oldm=oldms;savm=savms;
                   12897:       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
                   12898:       fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   12899:       for(i=1; i<=nlstate;i++)
                   12900:        for(j=1; j<=nlstate+ndeath;j++)
                   12901:          fprintf(ficrespij," %1d-%1d",i,j);
                   12902:       fprintf(ficrespij,"\n");
                   12903:       for (h=0; h<=nhstepm; h++){
                   12904:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   12905:        fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.183     brouard  12906:        for(i=1; i<=nlstate;i++)
                   12907:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  12908:            fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.183     brouard  12909:        fprintf(ficrespij,"\n");
                   12910:       }
1.337     brouard  12911:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12912:       fprintf(ficrespij,"\n");
1.180     brouard  12913:     }
1.337     brouard  12914:   }
                   12915:   /*}*/
                   12916:   return 0;
1.180     brouard  12917: }
1.218     brouard  12918:  
                   12919:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  12920:     /*------------- h Bij x at various ages ------------*/
1.336     brouard  12921:     /* To be optimized with precov */
1.217     brouard  12922:   int stepsize;
1.218     brouard  12923:   /* int agelim; */
                   12924:        int ageminl;
1.217     brouard  12925:   int hstepm;
                   12926:   int nhstepm;
1.238     brouard  12927:   int h, i, i1, j, k, nres;
1.218     brouard  12928:        
1.217     brouard  12929:   double agedeb;
                   12930:   double ***p3mat;
1.218     brouard  12931:        
                   12932:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   12933:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   12934:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   12935:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   12936:   }
                   12937:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   12938:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   12939:   
                   12940:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   12941:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  12942:   
1.218     brouard  12943:   /* agelim=AGESUP; */
1.289     brouard  12944:   ageminl=AGEINF; /* was 30 */
1.218     brouard  12945:   hstepm=stepsize*YEARM; /* Every year of age */
                   12946:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   12947:   
                   12948:   /* hstepm=1;   aff par mois*/
                   12949:   pstamp(ficrespijb);
1.255     brouard  12950:   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  12951:   i1= pow(2,cptcoveff);
1.218     brouard  12952:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12953:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   12954:   /*   k=k+1;  */
1.238     brouard  12955:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  12956:     k=TKresult[nres];
1.338     brouard  12957:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12958:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   12959:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   12960:     /*         continue; */
                   12961:     fprintf(ficrespijb,"\n#****** ");
                   12962:     for(j=1;j<=cptcovs;j++){
1.338     brouard  12963:       fprintf(ficrespijb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.337     brouard  12964:       /* for(j=1;j<=cptcoveff;j++) */
                   12965:       /*       fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12966:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   12967:       /*       fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12968:     }
                   12969:     fprintf(ficrespijb,"******\n");
                   12970:     if(invalidvarcomb[k]){  /* Is it necessary here? */
                   12971:       fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   12972:       continue;
                   12973:     }
                   12974:     
                   12975:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   12976:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   12977:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   12978:       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 */
                   12979:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
                   12980:       
                   12981:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   12982:       
                   12983:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   12984:       /* and memory limitations if stepm is small */
                   12985:       
                   12986:       /* oldm=oldms;savm=savms; */
                   12987:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   12988:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);/* Bug valgrind */
                   12989:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
                   12990:       fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
                   12991:       for(i=1; i<=nlstate;i++)
                   12992:        for(j=1; j<=nlstate+ndeath;j++)
                   12993:          fprintf(ficrespijb," %1d-%1d",i,j);
                   12994:       fprintf(ficrespijb,"\n");
                   12995:       for (h=0; h<=nhstepm; h++){
                   12996:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   12997:        fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   12998:        /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
1.217     brouard  12999:        for(i=1; i<=nlstate;i++)
                   13000:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  13001:            fprintf(ficrespijb," %.5f", p3mat[i][j][h]);/* Bug valgrind */
1.217     brouard  13002:        fprintf(ficrespijb,"\n");
1.337     brouard  13003:       }
                   13004:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   13005:       fprintf(ficrespijb,"\n");
                   13006:     } /* end age deb */
                   13007:     /* } /\* end combination *\/ */
1.238     brouard  13008:   } /* end nres */
1.218     brouard  13009:   return 0;
                   13010:  } /*  hBijx */
1.217     brouard  13011: 
1.180     brouard  13012: 
1.136     brouard  13013: /***********************************************/
                   13014: /**************** Main Program *****************/
                   13015: /***********************************************/
                   13016: 
                   13017: int main(int argc, char *argv[])
                   13018: {
                   13019: #ifdef GSL
                   13020:   const gsl_multimin_fminimizer_type *T;
                   13021:   size_t iteri = 0, it;
                   13022:   int rval = GSL_CONTINUE;
                   13023:   int status = GSL_SUCCESS;
                   13024:   double ssval;
                   13025: #endif
                   13026:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  13027:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   13028:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  13029:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  13030:   int jj, ll, li, lj, lk;
1.136     brouard  13031:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  13032:   int num_filled;
1.136     brouard  13033:   int itimes;
                   13034:   int NDIM=2;
                   13035:   int vpopbased=0;
1.235     brouard  13036:   int nres=0;
1.258     brouard  13037:   int endishere=0;
1.277     brouard  13038:   int noffset=0;
1.274     brouard  13039:   int ncurrv=0; /* Temporary variable */
                   13040:   
1.164     brouard  13041:   char ca[32], cb[32];
1.136     brouard  13042:   /*  FILE *fichtm; *//* Html File */
                   13043:   /* FILE *ficgp;*/ /*Gnuplot File */
                   13044:   struct stat info;
1.191     brouard  13045:   double agedeb=0.;
1.194     brouard  13046: 
                   13047:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  13048:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  13049: 
1.165     brouard  13050:   double fret;
1.191     brouard  13051:   double dum=0.; /* Dummy variable */
1.136     brouard  13052:   double ***p3mat;
1.218     brouard  13053:   /* double ***mobaverage; */
1.319     brouard  13054:   double wald;
1.164     brouard  13055: 
1.351     brouard  13056:   char line[MAXLINE], linetmp[MAXLINE];
1.197     brouard  13057:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   13058: 
1.234     brouard  13059:   char  modeltemp[MAXLINE];
1.332     brouard  13060:   char resultline[MAXLINE], resultlineori[MAXLINE];
1.230     brouard  13061:   
1.136     brouard  13062:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  13063:   char *tok, *val; /* pathtot */
1.334     brouard  13064:   /* int firstobs=1, lastobs=10; /\* nobs = lastobs-firstobs declared globally ;*\/ */
1.195     brouard  13065:   int c,  h , cpt, c2;
1.191     brouard  13066:   int jl=0;
                   13067:   int i1, j1, jk, stepsize=0;
1.194     brouard  13068:   int count=0;
                   13069: 
1.164     brouard  13070:   int *tab; 
1.136     brouard  13071:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  13072:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   13073:   /* double anprojf, mprojf, jprojf; */
                   13074:   /* double jintmean,mintmean,aintmean;   */
                   13075:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   13076:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   13077:   double yrfproj= 10.0; /* Number of years of forward projections */
                   13078:   double yrbproj= 10.0; /* Number of years of backward projections */
                   13079:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  13080:   int mobilav=0,popforecast=0;
1.191     brouard  13081:   int hstepm=0, nhstepm=0;
1.136     brouard  13082:   int agemortsup;
                   13083:   float  sumlpop=0.;
                   13084:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   13085:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   13086: 
1.191     brouard  13087:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  13088:   double ftolpl=FTOL;
                   13089:   double **prlim;
1.217     brouard  13090:   double **bprlim;
1.317     brouard  13091:   double ***param; /* Matrix of parameters, param[i][j][k] param=ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel) 
                   13092:                     state of origin, state of destination including death, for each covariate: constante, age, and V1 V2 etc. */
1.251     brouard  13093:   double ***paramstart; /* Matrix of starting parameter values */
                   13094:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  13095:   double **matcov; /* Matrix of covariance */
1.203     brouard  13096:   double **hess; /* Hessian matrix */
1.136     brouard  13097:   double ***delti3; /* Scale */
                   13098:   double *delti; /* Scale */
                   13099:   double ***eij, ***vareij;
                   13100:   double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  13101: 
1.136     brouard  13102:   double *epj, vepp;
1.164     brouard  13103: 
1.273     brouard  13104:   double dateprev1, dateprev2;
1.296     brouard  13105:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   13106:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   13107: 
1.217     brouard  13108: 
1.136     brouard  13109:   double **ximort;
1.145     brouard  13110:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  13111:   int *dcwave;
                   13112: 
1.164     brouard  13113:   char z[1]="c";
1.136     brouard  13114: 
                   13115:   /*char  *strt;*/
                   13116:   char strtend[80];
1.126     brouard  13117: 
1.164     brouard  13118: 
1.126     brouard  13119: /*   setlocale (LC_ALL, ""); */
                   13120: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   13121: /*   textdomain (PACKAGE); */
                   13122: /*   setlocale (LC_CTYPE, ""); */
                   13123: /*   setlocale (LC_MESSAGES, ""); */
                   13124: 
                   13125:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  13126:   rstart_time = time(NULL);  
                   13127:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   13128:   start_time = *localtime(&rstart_time);
1.126     brouard  13129:   curr_time=start_time;
1.157     brouard  13130:   /*tml = *localtime(&start_time.tm_sec);*/
                   13131:   /* strcpy(strstart,asctime(&tml)); */
                   13132:   strcpy(strstart,asctime(&start_time));
1.126     brouard  13133: 
                   13134: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  13135: /*  tp.tm_sec = tp.tm_sec +86400; */
                   13136: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  13137: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   13138: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   13139: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  13140: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  13141: /*   strt=asctime(&tmg); */
                   13142: /*   printf("Time(after) =%s",strstart);  */
                   13143: /*  (void) time (&time_value);
                   13144: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   13145: *  tm = *localtime(&time_value);
                   13146: *  strstart=asctime(&tm);
                   13147: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   13148: */
                   13149: 
                   13150:   nberr=0; /* Number of errors and warnings */
                   13151:   nbwarn=0;
1.184     brouard  13152: #ifdef WIN32
                   13153:   _getcwd(pathcd, size);
                   13154: #else
1.126     brouard  13155:   getcwd(pathcd, size);
1.184     brouard  13156: #endif
1.191     brouard  13157:   syscompilerinfo(0);
1.196     brouard  13158:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  13159:   if(argc <=1){
                   13160:     printf("\nEnter the parameter file name: ");
1.205     brouard  13161:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   13162:       printf("ERROR Empty parameter file name\n");
                   13163:       goto end;
                   13164:     }
1.126     brouard  13165:     i=strlen(pathr);
                   13166:     if(pathr[i-1]=='\n')
                   13167:       pathr[i-1]='\0';
1.156     brouard  13168:     i=strlen(pathr);
1.205     brouard  13169:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  13170:       pathr[i-1]='\0';
1.205     brouard  13171:     }
                   13172:     i=strlen(pathr);
                   13173:     if( i==0 ){
                   13174:       printf("ERROR Empty parameter file name\n");
                   13175:       goto end;
                   13176:     }
                   13177:     for (tok = pathr; tok != NULL; ){
1.126     brouard  13178:       printf("Pathr |%s|\n",pathr);
                   13179:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   13180:       printf("val= |%s| pathr=%s\n",val,pathr);
                   13181:       strcpy (pathtot, val);
                   13182:       if(pathr[0] == '\0') break; /* Dirty */
                   13183:     }
                   13184:   }
1.281     brouard  13185:   else if (argc<=2){
                   13186:     strcpy(pathtot,argv[1]);
                   13187:   }
1.126     brouard  13188:   else{
                   13189:     strcpy(pathtot,argv[1]);
1.281     brouard  13190:     strcpy(z,argv[2]);
                   13191:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  13192:   }
                   13193:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   13194:   /*cygwin_split_path(pathtot,path,optionfile);
                   13195:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   13196:   /* cutv(path,optionfile,pathtot,'\\');*/
                   13197: 
                   13198:   /* Split argv[0], imach program to get pathimach */
                   13199:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   13200:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   13201:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   13202:  /*   strcpy(pathimach,argv[0]); */
                   13203:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   13204:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   13205:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  13206: #ifdef WIN32
                   13207:   _chdir(path); /* Can be a relative path */
                   13208:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   13209: #else
1.126     brouard  13210:   chdir(path); /* Can be a relative path */
1.184     brouard  13211:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   13212: #endif
                   13213:   printf("Current directory %s!\n",pathcd);
1.126     brouard  13214:   strcpy(command,"mkdir ");
                   13215:   strcat(command,optionfilefiname);
                   13216:   if((outcmd=system(command)) != 0){
1.169     brouard  13217:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  13218:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   13219:     /* fclose(ficlog); */
                   13220: /*     exit(1); */
                   13221:   }
                   13222: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   13223: /*     perror("mkdir"); */
                   13224: /*   } */
                   13225: 
                   13226:   /*-------- arguments in the command line --------*/
                   13227: 
1.186     brouard  13228:   /* Main Log file */
1.126     brouard  13229:   strcat(filelog, optionfilefiname);
                   13230:   strcat(filelog,".log");    /* */
                   13231:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   13232:     printf("Problem with logfile %s\n",filelog);
                   13233:     goto end;
                   13234:   }
                   13235:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  13236:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  13237:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   13238:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   13239:  path=%s \n\
                   13240:  optionfile=%s\n\
                   13241:  optionfilext=%s\n\
1.156     brouard  13242:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  13243: 
1.197     brouard  13244:   syscompilerinfo(1);
1.167     brouard  13245: 
1.126     brouard  13246:   printf("Local time (at start):%s",strstart);
                   13247:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   13248:   fflush(ficlog);
                   13249: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  13250: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  13251: 
                   13252:   /* */
                   13253:   strcpy(fileres,"r");
                   13254:   strcat(fileres, optionfilefiname);
1.201     brouard  13255:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  13256:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  13257:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  13258: 
1.186     brouard  13259:   /* Main ---------arguments file --------*/
1.126     brouard  13260: 
                   13261:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  13262:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   13263:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  13264:     fflush(ficlog);
1.149     brouard  13265:     /* goto end; */
                   13266:     exit(70); 
1.126     brouard  13267:   }
                   13268: 
                   13269:   strcpy(filereso,"o");
1.201     brouard  13270:   strcat(filereso,fileresu);
1.126     brouard  13271:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   13272:     printf("Problem with Output resultfile: %s\n", filereso);
                   13273:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   13274:     fflush(ficlog);
                   13275:     goto end;
                   13276:   }
1.278     brouard  13277:       /*-------- Rewriting parameter file ----------*/
                   13278:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   13279:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   13280:   strcat(rfileres,".");    /* */
                   13281:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   13282:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   13283:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   13284:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   13285:     fflush(ficlog);
                   13286:     goto end;
                   13287:   }
                   13288:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  13289: 
1.278     brouard  13290:                                      
1.126     brouard  13291:   /* Reads comments: lines beginning with '#' */
                   13292:   numlinepar=0;
1.277     brouard  13293:   /* Is it a BOM UTF-8 Windows file? */
                   13294:   /* First parameter line */
1.197     brouard  13295:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  13296:     noffset=0;
                   13297:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   13298:     {
                   13299:       noffset=noffset+3;
                   13300:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   13301:     }
1.302     brouard  13302: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   13303:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
1.277     brouard  13304:     {
                   13305:       noffset=noffset+2;
                   13306:       printf("# File is an UTF16BE BOM file\n");
                   13307:     }
                   13308:     else if( line[0] == 0 && line[1] == 0)
                   13309:     {
                   13310:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   13311:        noffset=noffset+4;
                   13312:        printf("# File is an UTF16BE BOM file\n");
                   13313:       }
                   13314:     } else{
                   13315:       ;/*printf(" Not a BOM file\n");*/
                   13316:     }
                   13317:   
1.197     brouard  13318:     /* If line starts with a # it is a comment */
1.277     brouard  13319:     if (line[noffset] == '#') {
1.197     brouard  13320:       numlinepar++;
                   13321:       fputs(line,stdout);
                   13322:       fputs(line,ficparo);
1.278     brouard  13323:       fputs(line,ficres);
1.197     brouard  13324:       fputs(line,ficlog);
                   13325:       continue;
                   13326:     }else
                   13327:       break;
                   13328:   }
                   13329:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   13330:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   13331:     if (num_filled != 5) {
                   13332:       printf("Should be 5 parameters\n");
1.283     brouard  13333:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  13334:     }
1.126     brouard  13335:     numlinepar++;
1.197     brouard  13336:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  13337:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   13338:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   13339:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  13340:   }
                   13341:   /* Second parameter line */
                   13342:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  13343:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   13344:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  13345:     if (line[0] == '#') {
                   13346:       numlinepar++;
1.283     brouard  13347:       printf("%s",line);
                   13348:       fprintf(ficres,"%s",line);
                   13349:       fprintf(ficparo,"%s",line);
                   13350:       fprintf(ficlog,"%s",line);
1.197     brouard  13351:       continue;
                   13352:     }else
                   13353:       break;
                   13354:   }
1.223     brouard  13355:   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", \
                   13356:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   13357:     if (num_filled != 11) {
                   13358:       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  13359:       printf("but line=%s\n",line);
1.283     brouard  13360:       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");
                   13361:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  13362:     }
1.286     brouard  13363:     if( lastpass > maxwav){
                   13364:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   13365:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   13366:       fflush(ficlog);
                   13367:       goto end;
                   13368:     }
                   13369:       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  13370:     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  13371:     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  13372:     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  13373:   }
1.203     brouard  13374:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  13375:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  13376:   /* Third parameter line */
                   13377:   while(fgets(line, MAXLINE, ficpar)) {
                   13378:     /* If line starts with a # it is a comment */
                   13379:     if (line[0] == '#') {
                   13380:       numlinepar++;
1.283     brouard  13381:       printf("%s",line);
                   13382:       fprintf(ficres,"%s",line);
                   13383:       fprintf(ficparo,"%s",line);
                   13384:       fprintf(ficlog,"%s",line);
1.197     brouard  13385:       continue;
                   13386:     }else
                   13387:       break;
                   13388:   }
1.351     brouard  13389:   if((num_filled=sscanf(line,"model=%[^.\n]", model)) !=EOF){ /* Every character after model but dot and  return */
                   13390:     if (num_filled != 1){
                   13391:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   13392:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   13393:       model[0]='\0';
                   13394:       goto end;
                   13395:     }else{
                   13396:       trimbtab(linetmp,line); /* Trims multiple blanks in line */
                   13397:       strcpy(line, linetmp);
                   13398:     }
                   13399:   }
                   13400:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){ /* Every character after 1+age but dot and  return */
1.279     brouard  13401:     if (num_filled != 1){
1.302     brouard  13402:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   13403:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
1.197     brouard  13404:       model[0]='\0';
                   13405:       goto end;
                   13406:     }
                   13407:     else{
                   13408:       if (model[0]=='+'){
                   13409:        for(i=1; i<=strlen(model);i++)
                   13410:          modeltemp[i-1]=model[i];
1.201     brouard  13411:        strcpy(model,modeltemp); 
1.197     brouard  13412:       }
                   13413:     }
1.338     brouard  13414:     /* printf(" model=1+age%s modeltemp= %s, model=1+age+%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  13415:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  13416:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   13417:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   13418:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  13419:   }
                   13420:   /* 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); */
                   13421:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   13422:   /* 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  13423:   /* 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); */
                   13424:   /* 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  13425:   fflush(ficlog);
1.190     brouard  13426:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   13427:   if(model[0]=='#'){
1.279     brouard  13428:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   13429:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   13430:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  13431:     if(mle != -1){
1.279     brouard  13432:       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  13433:       exit(1);
                   13434:     }
                   13435:   }
1.126     brouard  13436:   while((c=getc(ficpar))=='#' && c!= EOF){
                   13437:     ungetc(c,ficpar);
                   13438:     fgets(line, MAXLINE, ficpar);
                   13439:     numlinepar++;
1.195     brouard  13440:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   13441:       z[0]=line[1];
1.342     brouard  13442:     }else if(line[1]=='d'){ /* For debugging individual values of covariates in ficresilk */
1.343     brouard  13443:       debugILK=1;printf("DebugILK\n");
1.195     brouard  13444:     }
                   13445:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  13446:     fputs(line, stdout);
                   13447:     //puts(line);
1.126     brouard  13448:     fputs(line,ficparo);
                   13449:     fputs(line,ficlog);
                   13450:   }
                   13451:   ungetc(c,ficpar);
                   13452: 
                   13453:    
1.290     brouard  13454:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   13455:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   13456:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
1.341     brouard  13457:   /* if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /\**< Time varying covariate (dummy and quantitative)*\/ */
                   13458:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);  /**< Might be better */
1.136     brouard  13459:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   13460:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   13461:      v1+v2*age+v2*v3 makes cptcovn = 3
                   13462:   */
                   13463:   if (strlen(model)>1) 
1.187     brouard  13464:     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  13465:   else
1.187     brouard  13466:     ncovmodel=2; /* Constant and age */
1.133     brouard  13467:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   13468:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  13469:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   13470:     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);
                   13471:     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);
                   13472:     fflush(stdout);
                   13473:     fclose (ficlog);
                   13474:     goto end;
                   13475:   }
1.126     brouard  13476:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   13477:   delti=delti3[1][1];
                   13478:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   13479:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  13480: /* We could also provide initial parameters values giving by simple logistic regression 
                   13481:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   13482:       /* for(i=1;i<nlstate;i++){ */
                   13483:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   13484:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   13485:       /* } */
1.126     brouard  13486:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  13487:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   13488:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  13489:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   13490:     fclose (ficparo);
                   13491:     fclose (ficlog);
                   13492:     goto end;
                   13493:     exit(0);
1.220     brouard  13494:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  13495:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  13496:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   13497:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  13498:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   13499:     matcov=matrix(1,npar,1,npar);
1.203     brouard  13500:     hess=matrix(1,npar,1,npar);
1.220     brouard  13501:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  13502:     /* Read guessed parameters */
1.126     brouard  13503:     /* Reads comments: lines beginning with '#' */
                   13504:     while((c=getc(ficpar))=='#' && c!= EOF){
                   13505:       ungetc(c,ficpar);
                   13506:       fgets(line, MAXLINE, ficpar);
                   13507:       numlinepar++;
1.141     brouard  13508:       fputs(line,stdout);
1.126     brouard  13509:       fputs(line,ficparo);
                   13510:       fputs(line,ficlog);
                   13511:     }
                   13512:     ungetc(c,ficpar);
                   13513:     
                   13514:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  13515:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  13516:     for(i=1; i <=nlstate; i++){
1.234     brouard  13517:       j=0;
1.126     brouard  13518:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  13519:        if(jj==i) continue;
                   13520:        j++;
1.292     brouard  13521:        while((c=getc(ficpar))=='#' && c!= EOF){
                   13522:          ungetc(c,ficpar);
                   13523:          fgets(line, MAXLINE, ficpar);
                   13524:          numlinepar++;
                   13525:          fputs(line,stdout);
                   13526:          fputs(line,ficparo);
                   13527:          fputs(line,ficlog);
                   13528:        }
                   13529:        ungetc(c,ficpar);
1.234     brouard  13530:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   13531:        if ((i1 != i) || (j1 != jj)){
                   13532:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  13533: It might be a problem of design; if ncovcol and the model are correct\n \
                   13534: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  13535:          exit(1);
                   13536:        }
                   13537:        fprintf(ficparo,"%1d%1d",i1,j1);
                   13538:        if(mle==1)
                   13539:          printf("%1d%1d",i,jj);
                   13540:        fprintf(ficlog,"%1d%1d",i,jj);
                   13541:        for(k=1; k<=ncovmodel;k++){
                   13542:          fscanf(ficpar," %lf",&param[i][j][k]);
                   13543:          if(mle==1){
                   13544:            printf(" %lf",param[i][j][k]);
                   13545:            fprintf(ficlog," %lf",param[i][j][k]);
                   13546:          }
                   13547:          else
                   13548:            fprintf(ficlog," %lf",param[i][j][k]);
                   13549:          fprintf(ficparo," %lf",param[i][j][k]);
                   13550:        }
                   13551:        fscanf(ficpar,"\n");
                   13552:        numlinepar++;
                   13553:        if(mle==1)
                   13554:          printf("\n");
                   13555:        fprintf(ficlog,"\n");
                   13556:        fprintf(ficparo,"\n");
1.126     brouard  13557:       }
                   13558:     }  
                   13559:     fflush(ficlog);
1.234     brouard  13560:     
1.251     brouard  13561:     /* Reads parameters values */
1.126     brouard  13562:     p=param[1][1];
1.251     brouard  13563:     pstart=paramstart[1][1];
1.126     brouard  13564:     
                   13565:     /* Reads comments: lines beginning with '#' */
                   13566:     while((c=getc(ficpar))=='#' && c!= EOF){
                   13567:       ungetc(c,ficpar);
                   13568:       fgets(line, MAXLINE, ficpar);
                   13569:       numlinepar++;
1.141     brouard  13570:       fputs(line,stdout);
1.126     brouard  13571:       fputs(line,ficparo);
                   13572:       fputs(line,ficlog);
                   13573:     }
                   13574:     ungetc(c,ficpar);
                   13575: 
                   13576:     for(i=1; i <=nlstate; i++){
                   13577:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  13578:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   13579:        if ( (i1-i) * (j1-j) != 0){
                   13580:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   13581:          exit(1);
                   13582:        }
                   13583:        printf("%1d%1d",i,j);
                   13584:        fprintf(ficparo,"%1d%1d",i1,j1);
                   13585:        fprintf(ficlog,"%1d%1d",i1,j1);
                   13586:        for(k=1; k<=ncovmodel;k++){
                   13587:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   13588:          printf(" %le",delti3[i][j][k]);
                   13589:          fprintf(ficparo," %le",delti3[i][j][k]);
                   13590:          fprintf(ficlog," %le",delti3[i][j][k]);
                   13591:        }
                   13592:        fscanf(ficpar,"\n");
                   13593:        numlinepar++;
                   13594:        printf("\n");
                   13595:        fprintf(ficparo,"\n");
                   13596:        fprintf(ficlog,"\n");
1.126     brouard  13597:       }
                   13598:     }
                   13599:     fflush(ficlog);
1.234     brouard  13600:     
1.145     brouard  13601:     /* Reads covariance matrix */
1.126     brouard  13602:     delti=delti3[1][1];
1.220     brouard  13603:                
                   13604:                
1.126     brouard  13605:     /* 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  13606:                
1.126     brouard  13607:     /* Reads comments: lines beginning with '#' */
                   13608:     while((c=getc(ficpar))=='#' && c!= EOF){
                   13609:       ungetc(c,ficpar);
                   13610:       fgets(line, MAXLINE, ficpar);
                   13611:       numlinepar++;
1.141     brouard  13612:       fputs(line,stdout);
1.126     brouard  13613:       fputs(line,ficparo);
                   13614:       fputs(line,ficlog);
                   13615:     }
                   13616:     ungetc(c,ficpar);
1.220     brouard  13617:                
1.126     brouard  13618:     matcov=matrix(1,npar,1,npar);
1.203     brouard  13619:     hess=matrix(1,npar,1,npar);
1.131     brouard  13620:     for(i=1; i <=npar; i++)
                   13621:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  13622:                
1.194     brouard  13623:     /* Scans npar lines */
1.126     brouard  13624:     for(i=1; i <=npar; i++){
1.226     brouard  13625:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  13626:       if(count != 3){
1.226     brouard  13627:        printf("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:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  13631: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   13632: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  13633:        exit(1);
1.220     brouard  13634:       }else{
1.226     brouard  13635:        if(mle==1)
                   13636:          printf("%1d%1d%d",i1,j1,jk);
                   13637:       }
                   13638:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   13639:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  13640:       for(j=1; j <=i; j++){
1.226     brouard  13641:        fscanf(ficpar," %le",&matcov[i][j]);
                   13642:        if(mle==1){
                   13643:          printf(" %.5le",matcov[i][j]);
                   13644:        }
                   13645:        fprintf(ficlog," %.5le",matcov[i][j]);
                   13646:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  13647:       }
                   13648:       fscanf(ficpar,"\n");
                   13649:       numlinepar++;
                   13650:       if(mle==1)
1.220     brouard  13651:                                printf("\n");
1.126     brouard  13652:       fprintf(ficlog,"\n");
                   13653:       fprintf(ficparo,"\n");
                   13654:     }
1.194     brouard  13655:     /* End of read covariance matrix npar lines */
1.126     brouard  13656:     for(i=1; i <=npar; i++)
                   13657:       for(j=i+1;j<=npar;j++)
1.226     brouard  13658:        matcov[i][j]=matcov[j][i];
1.126     brouard  13659:     
                   13660:     if(mle==1)
                   13661:       printf("\n");
                   13662:     fprintf(ficlog,"\n");
                   13663:     
                   13664:     fflush(ficlog);
                   13665:     
                   13666:   }    /* End of mle != -3 */
1.218     brouard  13667:   
1.186     brouard  13668:   /*  Main data
                   13669:    */
1.290     brouard  13670:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   13671:   /* num=lvector(1,n); */
                   13672:   /* moisnais=vector(1,n); */
                   13673:   /* annais=vector(1,n); */
                   13674:   /* moisdc=vector(1,n); */
                   13675:   /* andc=vector(1,n); */
                   13676:   /* weight=vector(1,n); */
                   13677:   /* agedc=vector(1,n); */
                   13678:   /* cod=ivector(1,n); */
                   13679:   /* for(i=1;i<=n;i++){ */
                   13680:   num=lvector(firstobs,lastobs);
                   13681:   moisnais=vector(firstobs,lastobs);
                   13682:   annais=vector(firstobs,lastobs);
                   13683:   moisdc=vector(firstobs,lastobs);
                   13684:   andc=vector(firstobs,lastobs);
                   13685:   weight=vector(firstobs,lastobs);
                   13686:   agedc=vector(firstobs,lastobs);
                   13687:   cod=ivector(firstobs,lastobs);
                   13688:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  13689:     num[i]=0;
                   13690:     moisnais[i]=0;
                   13691:     annais[i]=0;
                   13692:     moisdc[i]=0;
                   13693:     andc[i]=0;
                   13694:     agedc[i]=0;
                   13695:     cod[i]=0;
                   13696:     weight[i]=1.0; /* Equal weights, 1 by default */
                   13697:   }
1.290     brouard  13698:   mint=matrix(1,maxwav,firstobs,lastobs);
                   13699:   anint=matrix(1,maxwav,firstobs,lastobs);
1.325     brouard  13700:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */
1.336     brouard  13701:   /* printf("BUG ncovmodel=%d NCOVMAX=%d 2**ncovmodel=%f BUG\n",ncovmodel,NCOVMAX,pow(2,ncovmodel)); */
1.126     brouard  13702:   tab=ivector(1,NCOVMAX);
1.144     brouard  13703:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  13704:   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  13705: 
1.136     brouard  13706:   /* Reads data from file datafile */
                   13707:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   13708:     goto end;
                   13709: 
                   13710:   /* Calculation of the number of parameters from char model */
1.234     brouard  13711:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  13712:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   13713:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   13714:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   13715:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  13716:   */
                   13717:   
                   13718:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   13719:   TvarsDind=ivector(1,NCOVMAX); /*  */
1.330     brouard  13720:   TnsdVar=ivector(1,NCOVMAX); /*  */
1.335     brouard  13721:     /* for(i=1; i<=NCOVMAX;i++) TnsdVar[i]=3; */
1.234     brouard  13722:   TvarsD=ivector(1,NCOVMAX); /*  */
                   13723:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   13724:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  13725:   TvarF=ivector(1,NCOVMAX); /*  */
                   13726:   TvarFind=ivector(1,NCOVMAX); /*  */
                   13727:   TvarV=ivector(1,NCOVMAX); /*  */
                   13728:   TvarVind=ivector(1,NCOVMAX); /*  */
                   13729:   TvarA=ivector(1,NCOVMAX); /*  */
                   13730:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  13731:   TvarFD=ivector(1,NCOVMAX); /*  */
                   13732:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   13733:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   13734:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   13735:   TvarVD=ivector(1,NCOVMAX); /*  */
                   13736:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   13737:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   13738:   TvarVQind=ivector(1,NCOVMAX); /*  */
1.339     brouard  13739:   TvarVV=ivector(1,NCOVMAX); /*  */
                   13740:   TvarVVind=ivector(1,NCOVMAX); /*  */
1.349     brouard  13741:   TvarVVA=ivector(1,NCOVMAX); /*  */
                   13742:   TvarVVAind=ivector(1,NCOVMAX); /*  */
                   13743:   TvarAVVA=ivector(1,NCOVMAX); /*  */
                   13744:   TvarAVVAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  13745: 
1.230     brouard  13746:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  13747:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  13748:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   13749:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   13750:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.349     brouard  13751:   DummyV=ivector(-1,NCOVMAX); /* 1 to 3 */
                   13752:   FixedV=ivector(-1,NCOVMAX); /* 1 to 3 */
                   13753: 
1.137     brouard  13754:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   13755:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   13756:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   13757:   */
                   13758:   /* For model-covariate k tells which data-covariate to use but
                   13759:     because this model-covariate is a construction we invent a new column
                   13760:     ncovcol + k1
                   13761:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   13762:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  13763:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   13764:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  13765:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   13766:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  13767:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  13768:   */
1.145     brouard  13769:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   13770:   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  13771:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   13772:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.351     brouard  13773:   Tvardk=imatrix(0,NCOVMAX,1,2);
1.145     brouard  13774:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  13775:                         4 covariates (3 plus signs)
                   13776:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
1.328     brouard  13777:                           */  
                   13778:   for(i=1;i<NCOVMAX;i++)
                   13779:     Tage[i]=0;
1.230     brouard  13780:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  13781:                                * individual dummy, fixed or varying:
                   13782:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   13783:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  13784:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   13785:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   13786:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   13787:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   13788:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  13789:                                * individual quantitative, fixed or varying:
                   13790:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   13791:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   13792:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.349     brouard  13793: 
                   13794: /* Probably useless zeroes */
                   13795:   for(i=1;i<NCOVMAX;i++){
                   13796:     DummyV[i]=0;
                   13797:     FixedV[i]=0;
                   13798:   }
                   13799: 
                   13800:   for(i=1; i <=ncovcol;i++){
                   13801:     DummyV[i]=0;
                   13802:     FixedV[i]=0;
                   13803:   }
                   13804:   for(i=ncovcol+1; i <=ncovcol+nqv;i++){
                   13805:     DummyV[i]=1;
                   13806:     FixedV[i]=0;
                   13807:   }
                   13808:   for(i=ncovcol+nqv+1; i <=ncovcol+nqv+ntv;i++){
                   13809:     DummyV[i]=0;
                   13810:     FixedV[i]=1;
                   13811:   }
                   13812:   for(i=ncovcol+nqv+ntv+1; i <=ncovcol+nqv+ntv+nqtv;i++){
                   13813:     DummyV[i]=1;
                   13814:     FixedV[i]=1;
                   13815:   }
                   13816:   for(i=1; i <=ncovcol+nqv+ntv+nqtv;i++){
                   13817:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",i,i,DummyV[i],i,FixedV[i]);
                   13818:     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]);
                   13819:   }
                   13820: 
                   13821: 
                   13822: 
1.186     brouard  13823: /* Main decodemodel */
                   13824: 
1.187     brouard  13825: 
1.223     brouard  13826:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  13827:     goto end;
                   13828: 
1.137     brouard  13829:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   13830:     nbwarn++;
                   13831:     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); 
                   13832:     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); 
                   13833:   }
1.136     brouard  13834:     /*  if(mle==1){*/
1.137     brouard  13835:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   13836:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  13837:   }
                   13838: 
                   13839:     /*-calculation of age at interview from date of interview and age at death -*/
                   13840:   agev=matrix(1,maxwav,1,imx);
                   13841: 
                   13842:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   13843:     goto end;
                   13844: 
1.126     brouard  13845: 
1.136     brouard  13846:   agegomp=(int)agemin;
1.290     brouard  13847:   free_vector(moisnais,firstobs,lastobs);
                   13848:   free_vector(annais,firstobs,lastobs);
1.126     brouard  13849:   /* free_matrix(mint,1,maxwav,1,n);
                   13850:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  13851:   /* free_vector(moisdc,1,n); */
                   13852:   /* free_vector(andc,1,n); */
1.145     brouard  13853:   /* */
                   13854:   
1.126     brouard  13855:   wav=ivector(1,imx);
1.214     brouard  13856:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13857:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13858:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13859:   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.*/
                   13860:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   13861:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  13862:    
                   13863:   /* Concatenates waves */
1.214     brouard  13864:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   13865:      Death is a valid wave (if date is known).
                   13866:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   13867:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   13868:      and mw[mi+1][i]. dh depends on stepm.
                   13869:   */
                   13870: 
1.126     brouard  13871:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  13872:   /* Concatenates waves */
1.145     brouard  13873:  
1.290     brouard  13874:   free_vector(moisdc,firstobs,lastobs);
                   13875:   free_vector(andc,firstobs,lastobs);
1.215     brouard  13876: 
1.126     brouard  13877:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   13878:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   13879:   ncodemax[1]=1;
1.145     brouard  13880:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  13881:   cptcoveff=0;
1.220     brouard  13882:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
1.335     brouard  13883:     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  13884:   }
                   13885:   
                   13886:   ncovcombmax=pow(2,cptcoveff);
1.338     brouard  13887:   invalidvarcomb=ivector(0, ncovcombmax); 
                   13888:   for(i=0;i<ncovcombmax;i++)
1.227     brouard  13889:     invalidvarcomb[i]=0;
                   13890:   
1.211     brouard  13891:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  13892:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  13893:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  13894:   
1.200     brouard  13895:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  13896:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  13897:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  13898:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   13899:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   13900:    * (currently 0 or 1) in the data.
                   13901:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   13902:    * corresponding modality (h,j).
                   13903:    */
                   13904: 
1.145     brouard  13905:   h=0;
                   13906:   /*if (cptcovn > 0) */
1.126     brouard  13907:   m=pow(2,cptcoveff);
                   13908:  
1.144     brouard  13909:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  13910:           * For k=4 covariates, h goes from 1 to m=2**k
                   13911:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   13912:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.329     brouard  13913:           *     h\k   1     2     3     4   *  h-1\k-1  4  3  2  1          
                   13914:           *______________________________   *______________________
                   13915:           *     1 i=1 1 i=1 1 i=1 1 i=1 1   *     0     0  0  0  0 
                   13916:           *     2     2     1     1     1   *     1     0  0  0  1 
                   13917:           *     3 i=2 1     2     1     1   *     2     0  0  1  0 
                   13918:           *     4     2     2     1     1   *     3     0  0  1  1 
                   13919:           *     5 i=3 1 i=2 1     2     1   *     4     0  1  0  0 
                   13920:           *     6     2     1     2     1   *     5     0  1  0  1 
                   13921:           *     7 i=4 1     2     2     1   *     6     0  1  1  0 
                   13922:           *     8     2     2     2     1   *     7     0  1  1  1 
                   13923:           *     9 i=5 1 i=3 1 i=2 1     2   *     8     1  0  0  0 
                   13924:           *    10     2     1     1     2   *     9     1  0  0  1 
                   13925:           *    11 i=6 1     2     1     2   *    10     1  0  1  0 
                   13926:           *    12     2     2     1     2   *    11     1  0  1  1 
                   13927:           *    13 i=7 1 i=4 1     2     2   *    12     1  1  0  0  
                   13928:           *    14     2     1     2     2   *    13     1  1  0  1 
                   13929:           *    15 i=8 1     2     2     2   *    14     1  1  1  0 
                   13930:           *    16     2     2     2     2   *    15     1  1  1  1          
                   13931:           */                                     
1.212     brouard  13932:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  13933:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   13934:      * and the value of each covariate?
                   13935:      * V1=1, V2=1, V3=2, V4=1 ?
                   13936:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   13937:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   13938:      * In order to get the real value in the data, we use nbcode
                   13939:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   13940:      * We are keeping this crazy system in order to be able (in the future?) 
                   13941:      * to have more than 2 values (0 or 1) for a covariate.
                   13942:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   13943:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   13944:      *              bbbbbbbb
                   13945:      *              76543210     
                   13946:      *   h-1        00000101 (6-1=5)
1.219     brouard  13947:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  13948:      *           &
                   13949:      *     1        00000001 (1)
1.219     brouard  13950:      *              00000000        = 1 & ((h-1) >> (k-1))
                   13951:      *          +1= 00000001 =1 
1.211     brouard  13952:      *
                   13953:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   13954:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   13955:      *    >>k'            11
                   13956:      *          &   00000001
                   13957:      *            = 00000001
                   13958:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   13959:      * Reverse h=6 and m=16?
                   13960:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   13961:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   13962:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   13963:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   13964:      * V3=decodtabm(14,3,2**4)=2
                   13965:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   13966:      *(h-1) >> (j-1)    0011 =13 >> 2
                   13967:      *          &1 000000001
                   13968:      *           = 000000001
                   13969:      *         +1= 000000010 =2
                   13970:      *                  2211
                   13971:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   13972:      *                  V3=2
1.220     brouard  13973:                 * codtabm and decodtabm are identical
1.211     brouard  13974:      */
                   13975: 
1.145     brouard  13976: 
                   13977:  free_ivector(Ndum,-1,NCOVMAX);
                   13978: 
                   13979: 
1.126     brouard  13980:     
1.186     brouard  13981:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  13982:   strcpy(optionfilegnuplot,optionfilefiname);
                   13983:   if(mle==-3)
1.201     brouard  13984:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  13985:   strcat(optionfilegnuplot,".gp");
                   13986: 
                   13987:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   13988:     printf("Problem with file %s",optionfilegnuplot);
                   13989:   }
                   13990:   else{
1.204     brouard  13991:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  13992:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  13993:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   13994:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  13995:   }
                   13996:   /*  fclose(ficgp);*/
1.186     brouard  13997: 
                   13998: 
                   13999:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  14000: 
                   14001:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   14002:   if(mle==-3)
1.201     brouard  14003:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  14004:   strcat(optionfilehtm,".htm");
                   14005:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  14006:     printf("Problem with %s \n",optionfilehtm);
                   14007:     exit(0);
1.126     brouard  14008:   }
                   14009: 
                   14010:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   14011:   strcat(optionfilehtmcov,"-cov.htm");
                   14012:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   14013:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   14014:   }
                   14015:   else{
                   14016:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   14017: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  14018: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  14019:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   14020:   }
                   14021: 
1.335     brouard  14022:   fprintf(fichtm,"<html><head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n\
                   14023: <title>IMaCh %s</title></head>\n\
                   14024:  <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n\
                   14025: <font size=\"3\">Sponsored by Copyright (C)  2002-2015 <a href=http://www.ined.fr>INED</a>\
                   14026: -EUROREVES-Institut de longévité-2013-2022-Japan Society for the Promotion of Sciences 日本学術振興会 \
                   14027: (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - \
                   14028: <a href=https://software.intel.com/en-us>Intel Software 2015-2018</a></font><br> \n", optionfilehtm);
                   14029:   
                   14030:   fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  14031: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  14032: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.337     brouard  14033: 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  14034: \n\
                   14035: <hr  size=\"2\" color=\"#EC5E5E\">\
                   14036:  <ul><li><h4>Parameter files</h4>\n\
                   14037:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   14038:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   14039:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   14040:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   14041:  - Date and time at start: %s</ul>\n",\
1.335     brouard  14042:          version,fullversion,optionfilehtm,optionfilehtm,title,datafile,datafile,firstpass,lastpass,stepm, weightopt, model, \
1.126     brouard  14043:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   14044:          fileres,fileres,\
                   14045:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   14046:   fflush(fichtm);
                   14047: 
                   14048:   strcpy(pathr,path);
                   14049:   strcat(pathr,optionfilefiname);
1.184     brouard  14050: #ifdef WIN32
                   14051:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   14052: #else
1.126     brouard  14053:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  14054: #endif
                   14055:          
1.126     brouard  14056:   
1.220     brouard  14057:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   14058:                 and for any valid combination of covariates
1.126     brouard  14059:      and prints on file fileres'p'. */
1.251     brouard  14060:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  14061:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  14062: 
                   14063:   fprintf(fichtm,"\n");
1.286     brouard  14064:   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  14065:          ftol, stepm);
                   14066:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   14067:   ncurrv=1;
                   14068:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   14069:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   14070:   ncurrv=i;
                   14071:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  14072:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  14073:   ncurrv=i;
                   14074:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  14075:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  14076:   ncurrv=i;
                   14077:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   14078:   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", \
                   14079:           nlstate, ndeath, maxwav, mle, weightopt);
                   14080: 
                   14081:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   14082: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   14083: 
                   14084:   
1.317     brouard  14085:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Number of (used) observations=%d <br>\n\
1.126     brouard  14086: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   14087: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  14088:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  14089:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  14090:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   14091:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   14092:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   14093:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  14094: 
1.126     brouard  14095:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   14096:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   14097:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   14098: 
                   14099:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  14100:   /* For mortality only */
1.126     brouard  14101:   if (mle==-3){
1.136     brouard  14102:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  14103:     for(i=1;i<=NDIM;i++)
                   14104:       for(j=1;j<=NDIM;j++)
                   14105:        ximort[i][j]=0.;
1.186     brouard  14106:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  14107:     cens=ivector(firstobs,lastobs);
                   14108:     ageexmed=vector(firstobs,lastobs);
                   14109:     agecens=vector(firstobs,lastobs);
                   14110:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  14111:                
1.126     brouard  14112:     for (i=1; i<=imx; i++){
                   14113:       dcwave[i]=-1;
                   14114:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  14115:        if (s[m][i]>nlstate) {
                   14116:          dcwave[i]=m;
                   14117:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   14118:          break;
                   14119:        }
1.126     brouard  14120:     }
1.226     brouard  14121:     
1.126     brouard  14122:     for (i=1; i<=imx; i++) {
                   14123:       if (wav[i]>0){
1.226     brouard  14124:        ageexmed[i]=agev[mw[1][i]][i];
                   14125:        j=wav[i];
                   14126:        agecens[i]=1.; 
                   14127:        
                   14128:        if (ageexmed[i]> 1 && wav[i] > 0){
                   14129:          agecens[i]=agev[mw[j][i]][i];
                   14130:          cens[i]= 1;
                   14131:        }else if (ageexmed[i]< 1) 
                   14132:          cens[i]= -1;
                   14133:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   14134:          cens[i]=0 ;
1.126     brouard  14135:       }
                   14136:       else cens[i]=-1;
                   14137:     }
                   14138:     
                   14139:     for (i=1;i<=NDIM;i++) {
                   14140:       for (j=1;j<=NDIM;j++)
1.226     brouard  14141:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  14142:     }
                   14143:     
1.302     brouard  14144:     p[1]=0.0268; p[NDIM]=0.083;
                   14145:     /* printf("%lf %lf", p[1], p[2]); */
1.126     brouard  14146:     
                   14147:     
1.136     brouard  14148: #ifdef GSL
                   14149:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  14150: #else
1.126     brouard  14151:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  14152: #endif
1.201     brouard  14153:     strcpy(filerespow,"POW-MORT_"); 
                   14154:     strcat(filerespow,fileresu);
1.126     brouard  14155:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   14156:       printf("Problem with resultfile: %s\n", filerespow);
                   14157:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   14158:     }
1.136     brouard  14159: #ifdef GSL
                   14160:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  14161: #else
1.126     brouard  14162:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  14163: #endif
1.126     brouard  14164:     /*  for (i=1;i<=nlstate;i++)
                   14165:        for(j=1;j<=nlstate+ndeath;j++)
                   14166:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   14167:     */
                   14168:     fprintf(ficrespow,"\n");
1.136     brouard  14169: #ifdef GSL
                   14170:     /* gsl starts here */ 
                   14171:     T = gsl_multimin_fminimizer_nmsimplex;
                   14172:     gsl_multimin_fminimizer *sfm = NULL;
                   14173:     gsl_vector *ss, *x;
                   14174:     gsl_multimin_function minex_func;
                   14175: 
                   14176:     /* Initial vertex size vector */
                   14177:     ss = gsl_vector_alloc (NDIM);
                   14178:     
                   14179:     if (ss == NULL){
                   14180:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   14181:     }
                   14182:     /* Set all step sizes to 1 */
                   14183:     gsl_vector_set_all (ss, 0.001);
                   14184: 
                   14185:     /* Starting point */
1.126     brouard  14186:     
1.136     brouard  14187:     x = gsl_vector_alloc (NDIM);
                   14188:     
                   14189:     if (x == NULL){
                   14190:       gsl_vector_free(ss);
                   14191:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   14192:     }
                   14193:   
                   14194:     /* Initialize method and iterate */
                   14195:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  14196:     /*     gsl_vector_set(x, 0, 0.0268); */
                   14197:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  14198:     gsl_vector_set(x, 0, p[1]);
                   14199:     gsl_vector_set(x, 1, p[2]);
                   14200: 
                   14201:     minex_func.f = &gompertz_f;
                   14202:     minex_func.n = NDIM;
                   14203:     minex_func.params = (void *)&p; /* ??? */
                   14204:     
                   14205:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   14206:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   14207:     
                   14208:     printf("Iterations beginning .....\n\n");
                   14209:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   14210: 
                   14211:     iteri=0;
                   14212:     while (rval == GSL_CONTINUE){
                   14213:       iteri++;
                   14214:       status = gsl_multimin_fminimizer_iterate(sfm);
                   14215:       
                   14216:       if (status) printf("error: %s\n", gsl_strerror (status));
                   14217:       fflush(0);
                   14218:       
                   14219:       if (status) 
                   14220:         break;
                   14221:       
                   14222:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   14223:       ssval = gsl_multimin_fminimizer_size (sfm);
                   14224:       
                   14225:       if (rval == GSL_SUCCESS)
                   14226:         printf ("converged to a local maximum at\n");
                   14227:       
                   14228:       printf("%5d ", iteri);
                   14229:       for (it = 0; it < NDIM; it++){
                   14230:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   14231:       }
                   14232:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   14233:     }
                   14234:     
                   14235:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   14236:     
                   14237:     gsl_vector_free(x); /* initial values */
                   14238:     gsl_vector_free(ss); /* inital step size */
                   14239:     for (it=0; it<NDIM; it++){
                   14240:       p[it+1]=gsl_vector_get(sfm->x,it);
                   14241:       fprintf(ficrespow," %.12lf", p[it]);
                   14242:     }
                   14243:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   14244: #endif
                   14245: #ifdef POWELL
                   14246:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   14247: #endif  
1.126     brouard  14248:     fclose(ficrespow);
                   14249:     
1.203     brouard  14250:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  14251: 
                   14252:     for(i=1; i <=NDIM; i++)
                   14253:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  14254:                                matcov[i][j]=matcov[j][i];
1.126     brouard  14255:     
                   14256:     printf("\nCovariance matrix\n ");
1.203     brouard  14257:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  14258:     for(i=1; i <=NDIM; i++) {
                   14259:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  14260:                                printf("%f ",matcov[i][j]);
                   14261:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  14262:       }
1.203     brouard  14263:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  14264:     }
                   14265:     
                   14266:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  14267:     for (i=1;i<=NDIM;i++) {
1.126     brouard  14268:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  14269:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   14270:     }
1.302     brouard  14271:     lsurv=vector(agegomp,AGESUP);
                   14272:     lpop=vector(agegomp,AGESUP);
                   14273:     tpop=vector(agegomp,AGESUP);
1.126     brouard  14274:     lsurv[agegomp]=100000;
                   14275:     
                   14276:     for (k=agegomp;k<=AGESUP;k++) {
                   14277:       agemortsup=k;
                   14278:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   14279:     }
                   14280:     
                   14281:     for (k=agegomp;k<agemortsup;k++)
                   14282:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   14283:     
                   14284:     for (k=agegomp;k<agemortsup;k++){
                   14285:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   14286:       sumlpop=sumlpop+lpop[k];
                   14287:     }
                   14288:     
                   14289:     tpop[agegomp]=sumlpop;
                   14290:     for (k=agegomp;k<(agemortsup-3);k++){
                   14291:       /*  tpop[k+1]=2;*/
                   14292:       tpop[k+1]=tpop[k]-lpop[k];
                   14293:     }
                   14294:     
                   14295:     
                   14296:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   14297:     for (k=agegomp;k<(agemortsup-2);k++) 
                   14298:       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]);
                   14299:     
                   14300:     
                   14301:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  14302:                ageminpar=50;
                   14303:                agemaxpar=100;
1.194     brouard  14304:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   14305:        printf("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);
                   14308:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   14309: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14310: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  14311:     }else{
                   14312:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   14313:                        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  14314:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  14315:                }
1.201     brouard  14316:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  14317:                     stepm, weightopt,\
                   14318:                     model,imx,p,matcov,agemortsup);
                   14319:     
1.302     brouard  14320:     free_vector(lsurv,agegomp,AGESUP);
                   14321:     free_vector(lpop,agegomp,AGESUP);
                   14322:     free_vector(tpop,agegomp,AGESUP);
1.220     brouard  14323:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  14324:     free_ivector(dcwave,firstobs,lastobs);
                   14325:     free_vector(agecens,firstobs,lastobs);
                   14326:     free_vector(ageexmed,firstobs,lastobs);
                   14327:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  14328: #ifdef GSL
1.136     brouard  14329: #endif
1.186     brouard  14330:   } /* Endof if mle==-3 mortality only */
1.205     brouard  14331:   /* Standard  */
                   14332:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   14333:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   14334:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  14335:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  14336:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   14337:     for (k=1; k<=npar;k++)
                   14338:       printf(" %d %8.5f",k,p[k]);
                   14339:     printf("\n");
1.205     brouard  14340:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   14341:       /* mlikeli uses func not funcone */
1.247     brouard  14342:       /* for(i=1;i<nlstate;i++){ */
                   14343:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   14344:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   14345:       /* } */
1.205     brouard  14346:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   14347:     }
                   14348:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   14349:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   14350:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   14351:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   14352:     }
                   14353:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  14354:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   14355:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
1.335     brouard  14356:           /* exit(0); */
1.126     brouard  14357:     for (k=1; k<=npar;k++)
                   14358:       printf(" %d %8.5f",k,p[k]);
                   14359:     printf("\n");
                   14360:     
                   14361:     /*--------- results files --------------*/
1.283     brouard  14362:     /* 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  14363:     
                   14364:     
                   14365:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  14366:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); /* Printing model equation */
1.126     brouard  14367:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  14368: 
                   14369:     printf("#model=  1      +     age ");
                   14370:     fprintf(ficres,"#model=  1      +     age ");
                   14371:     fprintf(ficlog,"#model=  1      +     age ");
                   14372:     fprintf(fichtm,"\n<ul><li> model=1+age+%s\n \
                   14373: </ul>", model);
                   14374: 
                   14375:     fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">\n");
                   14376:     fprintf(fichtm, "<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   14377:     if(nagesqr==1){
                   14378:       printf("  + age*age  ");
                   14379:       fprintf(ficres,"  + age*age  ");
                   14380:       fprintf(ficlog,"  + age*age  ");
                   14381:       fprintf(fichtm, "<th>+ age*age</th>");
                   14382:     }
                   14383:     for(j=1;j <=ncovmodel-2;j++){
                   14384:       if(Typevar[j]==0) {
                   14385:        printf("  +      V%d  ",Tvar[j]);
                   14386:        fprintf(ficres,"  +      V%d  ",Tvar[j]);
                   14387:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   14388:        fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   14389:       }else if(Typevar[j]==1) {
                   14390:        printf("  +    V%d*age ",Tvar[j]);
                   14391:        fprintf(ficres,"  +    V%d*age ",Tvar[j]);
                   14392:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   14393:        fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   14394:       }else if(Typevar[j]==2) {
                   14395:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14396:        fprintf(ficres,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14397:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14398:        fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  14399:       }else if(Typevar[j]==3) { /* TO VERIFY */
                   14400:        printf("  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14401:        fprintf(ficres,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14402:        fprintf(ficlog,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14403:        fprintf(fichtm, "<th>+  V%d*V%d*age</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.319     brouard  14404:       }
                   14405:     }
                   14406:     printf("\n");
                   14407:     fprintf(ficres,"\n");
                   14408:     fprintf(ficlog,"\n");
                   14409:     fprintf(fichtm, "</tr>");
                   14410:     fprintf(fichtm, "\n");
                   14411:     
                   14412:     
1.126     brouard  14413:     for(i=1,jk=1; i <=nlstate; i++){
                   14414:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  14415:        if (k != i) {
1.319     brouard  14416:          fprintf(fichtm, "<tr>");
1.225     brouard  14417:          printf("%d%d ",i,k);
                   14418:          fprintf(ficlog,"%d%d ",i,k);
                   14419:          fprintf(ficres,"%1d%1d ",i,k);
1.319     brouard  14420:          fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  14421:          for(j=1; j <=ncovmodel; j++){
                   14422:            printf("%12.7f ",p[jk]);
                   14423:            fprintf(ficlog,"%12.7f ",p[jk]);
                   14424:            fprintf(ficres,"%12.7f ",p[jk]);
1.319     brouard  14425:            fprintf(fichtm, "<td>%12.7f</td>",p[jk]);
1.225     brouard  14426:            jk++; 
                   14427:          }
                   14428:          printf("\n");
                   14429:          fprintf(ficlog,"\n");
                   14430:          fprintf(ficres,"\n");
1.319     brouard  14431:          fprintf(fichtm, "</tr>\n");
1.225     brouard  14432:        }
1.126     brouard  14433:       }
                   14434:     }
1.319     brouard  14435:     /* fprintf(fichtm,"</tr>\n"); */
                   14436:     fprintf(fichtm,"</table>\n");
                   14437:     fprintf(fichtm, "\n");
                   14438: 
1.203     brouard  14439:     if(mle != 0){
                   14440:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  14441:       ftolhess=ftol; /* Usually correct */
1.203     brouard  14442:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   14443:       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");
                   14444:       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  14445:       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  14446:       fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">");
                   14447:       fprintf(fichtm, "\n<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   14448:       if(nagesqr==1){
                   14449:        printf("  + age*age  ");
                   14450:        fprintf(ficres,"  + age*age  ");
                   14451:        fprintf(ficlog,"  + age*age  ");
                   14452:        fprintf(fichtm, "<th>+ age*age</th>");
                   14453:       }
                   14454:       for(j=1;j <=ncovmodel-2;j++){
                   14455:        if(Typevar[j]==0) {
                   14456:          printf("  +      V%d  ",Tvar[j]);
                   14457:          fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   14458:        }else if(Typevar[j]==1) {
                   14459:          printf("  +    V%d*age ",Tvar[j]);
                   14460:          fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   14461:        }else if(Typevar[j]==2) {
                   14462:          fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  14463:        }else if(Typevar[j]==3) { /* TO VERIFY */
                   14464:          fprintf(fichtm, "<th>+  V%d*V%d*age</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.319     brouard  14465:        }
                   14466:       }
                   14467:       fprintf(fichtm, "</tr>\n");
                   14468:  
1.203     brouard  14469:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  14470:        for(k=1; k <=(nlstate+ndeath); k++){
                   14471:          if (k != i) {
1.319     brouard  14472:            fprintf(fichtm, "<tr valign=top>");
1.225     brouard  14473:            printf("%d%d ",i,k);
                   14474:            fprintf(ficlog,"%d%d ",i,k);
1.319     brouard  14475:            fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  14476:            for(j=1; j <=ncovmodel; j++){
1.319     brouard  14477:              wald=p[jk]/sqrt(matcov[jk][jk]);
1.324     brouard  14478:              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]));
                   14479:              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  14480:              if(fabs(wald) > 1.96){
1.321     brouard  14481:                fprintf(fichtm, "<td><b>%12.7f</b></br> (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
1.319     brouard  14482:              }else{
                   14483:                fprintf(fichtm, "<td>%12.7f (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
                   14484:              }
1.324     brouard  14485:              fprintf(fichtm,"W=%8.3f</br>",wald);
1.319     brouard  14486:              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  14487:              jk++; 
                   14488:            }
                   14489:            printf("\n");
                   14490:            fprintf(ficlog,"\n");
1.319     brouard  14491:            fprintf(fichtm, "</tr>\n");
1.225     brouard  14492:          }
                   14493:        }
1.193     brouard  14494:       }
1.203     brouard  14495:     } /* end of hesscov and Wald tests */
1.319     brouard  14496:     fprintf(fichtm,"</table>\n");
1.225     brouard  14497:     
1.203     brouard  14498:     /*  */
1.126     brouard  14499:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   14500:     printf("# Scales (for hessian or gradient estimation)\n");
                   14501:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   14502:     for(i=1,jk=1; i <=nlstate; i++){
                   14503:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  14504:        if (j!=i) {
                   14505:          fprintf(ficres,"%1d%1d",i,j);
                   14506:          printf("%1d%1d",i,j);
                   14507:          fprintf(ficlog,"%1d%1d",i,j);
                   14508:          for(k=1; k<=ncovmodel;k++){
                   14509:            printf(" %.5e",delti[jk]);
                   14510:            fprintf(ficlog," %.5e",delti[jk]);
                   14511:            fprintf(ficres," %.5e",delti[jk]);
                   14512:            jk++;
                   14513:          }
                   14514:          printf("\n");
                   14515:          fprintf(ficlog,"\n");
                   14516:          fprintf(ficres,"\n");
                   14517:        }
1.126     brouard  14518:       }
                   14519:     }
                   14520:     
                   14521:     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  14522:     if(mle >= 1) /* Too big for the screen */
1.126     brouard  14523:       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");
                   14524:     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");
                   14525:     /* # 121 Var(a12)\n\ */
                   14526:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   14527:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   14528:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   14529:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   14530:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   14531:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   14532:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   14533:     
                   14534:     
                   14535:     /* Just to have a covariance matrix which will be more understandable
                   14536:        even is we still don't want to manage dictionary of variables
                   14537:     */
                   14538:     for(itimes=1;itimes<=2;itimes++){
                   14539:       jj=0;
                   14540:       for(i=1; i <=nlstate; i++){
1.225     brouard  14541:        for(j=1; j <=nlstate+ndeath; j++){
                   14542:          if(j==i) continue;
                   14543:          for(k=1; k<=ncovmodel;k++){
                   14544:            jj++;
                   14545:            ca[0]= k+'a'-1;ca[1]='\0';
                   14546:            if(itimes==1){
                   14547:              if(mle>=1)
                   14548:                printf("#%1d%1d%d",i,j,k);
                   14549:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   14550:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   14551:            }else{
                   14552:              if(mle>=1)
                   14553:                printf("%1d%1d%d",i,j,k);
                   14554:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   14555:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   14556:            }
                   14557:            ll=0;
                   14558:            for(li=1;li <=nlstate; li++){
                   14559:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   14560:                if(lj==li) continue;
                   14561:                for(lk=1;lk<=ncovmodel;lk++){
                   14562:                  ll++;
                   14563:                  if(ll<=jj){
                   14564:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   14565:                    if(ll<jj){
                   14566:                      if(itimes==1){
                   14567:                        if(mle>=1)
                   14568:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   14569:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   14570:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   14571:                      }else{
                   14572:                        if(mle>=1)
                   14573:                          printf(" %.5e",matcov[jj][ll]); 
                   14574:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   14575:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   14576:                      }
                   14577:                    }else{
                   14578:                      if(itimes==1){
                   14579:                        if(mle>=1)
                   14580:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   14581:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   14582:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   14583:                      }else{
                   14584:                        if(mle>=1)
                   14585:                          printf(" %.7e",matcov[jj][ll]); 
                   14586:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   14587:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   14588:                      }
                   14589:                    }
                   14590:                  }
                   14591:                } /* end lk */
                   14592:              } /* end lj */
                   14593:            } /* end li */
                   14594:            if(mle>=1)
                   14595:              printf("\n");
                   14596:            fprintf(ficlog,"\n");
                   14597:            fprintf(ficres,"\n");
                   14598:            numlinepar++;
                   14599:          } /* end k*/
                   14600:        } /*end j */
1.126     brouard  14601:       } /* end i */
                   14602:     } /* end itimes */
                   14603:     
                   14604:     fflush(ficlog);
                   14605:     fflush(ficres);
1.225     brouard  14606:     while(fgets(line, MAXLINE, ficpar)) {
                   14607:       /* If line starts with a # it is a comment */
                   14608:       if (line[0] == '#') {
                   14609:        numlinepar++;
                   14610:        fputs(line,stdout);
                   14611:        fputs(line,ficparo);
                   14612:        fputs(line,ficlog);
1.299     brouard  14613:        fputs(line,ficres);
1.225     brouard  14614:        continue;
                   14615:       }else
                   14616:        break;
                   14617:     }
                   14618:     
1.209     brouard  14619:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   14620:     /*   ungetc(c,ficpar); */
                   14621:     /*   fgets(line, MAXLINE, ficpar); */
                   14622:     /*   fputs(line,stdout); */
                   14623:     /*   fputs(line,ficparo); */
                   14624:     /* } */
                   14625:     /* ungetc(c,ficpar); */
1.126     brouard  14626:     
                   14627:     estepm=0;
1.209     brouard  14628:     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  14629:       
                   14630:       if (num_filled != 6) {
                   14631:        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);
                   14632:        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);
                   14633:        goto end;
                   14634:       }
                   14635:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   14636:     }
                   14637:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   14638:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   14639:     
1.209     brouard  14640:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  14641:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   14642:     if (fage <= 2) {
                   14643:       bage = ageminpar;
                   14644:       fage = agemaxpar;
                   14645:     }
                   14646:     
                   14647:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  14648:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   14649:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  14650:                
1.186     brouard  14651:     /* Other stuffs, more or less useful */    
1.254     brouard  14652:     while(fgets(line, MAXLINE, ficpar)) {
                   14653:       /* If line starts with a # it is a comment */
                   14654:       if (line[0] == '#') {
                   14655:        numlinepar++;
                   14656:        fputs(line,stdout);
                   14657:        fputs(line,ficparo);
                   14658:        fputs(line,ficlog);
1.299     brouard  14659:        fputs(line,ficres);
1.254     brouard  14660:        continue;
                   14661:       }else
                   14662:        break;
                   14663:     }
                   14664: 
                   14665:     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){
                   14666:       
                   14667:       if (num_filled != 7) {
                   14668:        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);
                   14669:        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);
                   14670:        goto end;
                   14671:       }
                   14672:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   14673:       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);
                   14674:       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);
                   14675:       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  14676:     }
1.254     brouard  14677: 
                   14678:     while(fgets(line, MAXLINE, ficpar)) {
                   14679:       /* If line starts with a # it is a comment */
                   14680:       if (line[0] == '#') {
                   14681:        numlinepar++;
                   14682:        fputs(line,stdout);
                   14683:        fputs(line,ficparo);
                   14684:        fputs(line,ficlog);
1.299     brouard  14685:        fputs(line,ficres);
1.254     brouard  14686:        continue;
                   14687:       }else
                   14688:        break;
1.126     brouard  14689:     }
                   14690:     
                   14691:     
                   14692:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   14693:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   14694:     
1.254     brouard  14695:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   14696:       if (num_filled != 1) {
                   14697:        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);
                   14698:        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);
                   14699:        goto end;
                   14700:       }
                   14701:       printf("pop_based=%d\n",popbased);
                   14702:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   14703:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   14704:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   14705:     }
                   14706:      
1.258     brouard  14707:     /* Results */
1.332     brouard  14708:     /* Value of covariate in each resultine will be compututed (if product) and sorted according to model rank */
                   14709:     /* It is precov[] because we need the varying age in order to compute the real cov[] of the model equation */  
                   14710:     precov=matrix(1,MAXRESULTLINESPONE,1,NCOVMAX+1);
1.307     brouard  14711:     endishere=0;
1.258     brouard  14712:     nresult=0;
1.308     brouard  14713:     parameterline=0;
1.258     brouard  14714:     do{
                   14715:       if(!fgets(line, MAXLINE, ficpar)){
                   14716:        endishere=1;
1.308     brouard  14717:        parameterline=15;
1.258     brouard  14718:       }else if (line[0] == '#') {
                   14719:        /* If line starts with a # it is a comment */
1.254     brouard  14720:        numlinepar++;
                   14721:        fputs(line,stdout);
                   14722:        fputs(line,ficparo);
                   14723:        fputs(line,ficlog);
1.299     brouard  14724:        fputs(line,ficres);
1.254     brouard  14725:        continue;
1.258     brouard  14726:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   14727:        parameterline=11;
1.296     brouard  14728:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  14729:        parameterline=12;
1.307     brouard  14730:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
1.258     brouard  14731:        parameterline=13;
1.307     brouard  14732:       }
1.258     brouard  14733:       else{
                   14734:        parameterline=14;
1.254     brouard  14735:       }
1.308     brouard  14736:       switch (parameterline){ /* =0 only if only comments */
1.258     brouard  14737:       case 11:
1.296     brouard  14738:        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)){
                   14739:                  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  14740:          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);
                   14741:          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);
                   14742:          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);
                   14743:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  14744:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   14745:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  14746:           prvforecast = 1;
                   14747:        } 
                   14748:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.313     brouard  14749:          printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   14750:          fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   14751:          fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  14752:           prvforecast = 2;
                   14753:        }
                   14754:        else {
                   14755:          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);
                   14756:          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);
                   14757:          goto end;
1.258     brouard  14758:        }
1.254     brouard  14759:        break;
1.258     brouard  14760:       case 12:
1.296     brouard  14761:        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)){
                   14762:           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);
                   14763:          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);
                   14764:          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);
                   14765:          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);
                   14766:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  14767:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   14768:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  14769:           prvbackcast = 1;
                   14770:        } 
                   14771:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.313     brouard  14772:          printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   14773:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   14774:          fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  14775:           prvbackcast = 2;
                   14776:        }
                   14777:        else {
                   14778:          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);
                   14779:          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);
                   14780:          goto end;
1.258     brouard  14781:        }
1.230     brouard  14782:        break;
1.258     brouard  14783:       case 13:
1.332     brouard  14784:        num_filled=sscanf(line,"result:%[^\n]\n",resultlineori);
1.307     brouard  14785:        nresult++; /* Sum of resultlines */
1.342     brouard  14786:        /* printf("Result %d: result:%s\n",nresult, resultlineori); */
1.332     brouard  14787:        /* removefirstspace(&resultlineori); */
                   14788:        
                   14789:        if(strstr(resultlineori,"v") !=0){
                   14790:          printf("Error. 'v' must be in upper case 'V' result: %s ",resultlineori);
                   14791:          fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultlineori);fflush(ficlog);
                   14792:          return 1;
                   14793:        }
                   14794:        trimbb(resultline, resultlineori); /* Suppressing double blank in the resultline */
1.342     brouard  14795:        /* printf("Decoderesult resultline=\"%s\" resultlineori=\"%s\"\n", resultline, resultlineori); */
1.318     brouard  14796:        if(nresult > MAXRESULTLINESPONE-1){
                   14797:          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);
                   14798:          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  14799:          goto end;
                   14800:        }
1.332     brouard  14801:        
1.310     brouard  14802:        if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.314     brouard  14803:          fprintf(ficparo,"result: %s\n",resultline);
                   14804:          fprintf(ficres,"result: %s\n",resultline);
                   14805:          fprintf(ficlog,"result: %s\n",resultline);
1.310     brouard  14806:        } else
                   14807:          goto end;
1.307     brouard  14808:        break;
                   14809:       case 14:
                   14810:        printf("Error: Unknown command '%s'\n",line);
                   14811:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
1.314     brouard  14812:        if(line[0] == ' ' || line[0] == '\n'){
                   14813:          printf("It should not be an empty line '%s'\n",line);
                   14814:          fprintf(ficlog,"It should not be an empty line '%s'\n",line);
                   14815:        }         
1.307     brouard  14816:        if(ncovmodel >=2 && nresult==0 ){
                   14817:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   14818:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  14819:        }
1.307     brouard  14820:        /* goto end; */
                   14821:        break;
1.308     brouard  14822:       case 15:
                   14823:        printf("End of resultlines.\n");
                   14824:        fprintf(ficlog,"End of resultlines.\n");
                   14825:        break;
                   14826:       default: /* parameterline =0 */
1.307     brouard  14827:        nresult=1;
                   14828:        decoderesult(".",nresult ); /* No covariate */
1.258     brouard  14829:       } /* End switch parameterline */
                   14830:     }while(endishere==0); /* End do */
1.126     brouard  14831:     
1.230     brouard  14832:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  14833:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  14834:     
                   14835:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  14836:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  14837:       printf("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.230     brouard  14840:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  14841: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14842: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  14843:     }else{
1.270     brouard  14844:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  14845:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   14846:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   14847:       if(prvforecast==1){
                   14848:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   14849:         jprojd=jproj1;
                   14850:         mprojd=mproj1;
                   14851:         anprojd=anproj1;
                   14852:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   14853:         jprojf=jproj2;
                   14854:         mprojf=mproj2;
                   14855:         anprojf=anproj2;
                   14856:       } else if(prvforecast == 2){
                   14857:         dateprojd=dateintmean;
                   14858:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   14859:         dateprojf=dateintmean+yrfproj;
                   14860:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   14861:       }
                   14862:       if(prvbackcast==1){
                   14863:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   14864:         jbackd=jback1;
                   14865:         mbackd=mback1;
                   14866:         anbackd=anback1;
                   14867:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   14868:         jbackf=jback2;
                   14869:         mbackf=mback2;
                   14870:         anbackf=anback2;
                   14871:       } else if(prvbackcast == 2){
                   14872:         datebackd=dateintmean;
                   14873:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   14874:         datebackf=dateintmean-yrbproj;
                   14875:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   14876:       }
                   14877:       
1.350     brouard  14878:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);/* HERE valgrind Tvard*/
1.220     brouard  14879:     }
                   14880:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  14881:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   14882:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  14883:                
1.225     brouard  14884:     /*------------ free_vector  -------------*/
                   14885:     /*  chdir(path); */
1.220     brouard  14886:                
1.215     brouard  14887:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   14888:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   14889:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   14890:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  14891:     free_lvector(num,firstobs,lastobs);
                   14892:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  14893:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   14894:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   14895:     fclose(ficparo);
                   14896:     fclose(ficres);
1.220     brouard  14897:                
                   14898:                
1.186     brouard  14899:     /* Other results (useful)*/
1.220     brouard  14900:                
                   14901:                
1.126     brouard  14902:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  14903:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   14904:     prlim=matrix(1,nlstate,1,nlstate);
1.332     brouard  14905:     /* Computes the prevalence limit for each combination k of the dummy covariates by calling prevalim(k) */
1.209     brouard  14906:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  14907:     fclose(ficrespl);
                   14908: 
                   14909:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  14910:     /*#include "hpijx.h"*/
1.332     brouard  14911:     /** 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?*/
                   14912:     /* calls hpxij with combination k */
1.180     brouard  14913:     hPijx(p, bage, fage);
1.145     brouard  14914:     fclose(ficrespij);
1.227     brouard  14915:     
1.220     brouard  14916:     /* ncovcombmax=  pow(2,cptcoveff); */
1.332     brouard  14917:     /*-------------- Variance of one-step probabilities for a combination ij or for nres ?---*/
1.145     brouard  14918:     k=1;
1.126     brouard  14919:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  14920:     
1.269     brouard  14921:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   14922:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   14923:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  14924:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  14925:        for(k=1;k<=ncovcombmax;k++)
                   14926:          probs[i][j][k]=0.;
1.269     brouard  14927:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   14928:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  14929:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  14930:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   14931:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  14932:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  14933:          for(k=1;k<=ncovcombmax;k++)
                   14934:            mobaverages[i][j][k]=0.;
1.219     brouard  14935:       mobaverage=mobaverages;
                   14936:       if (mobilav!=0) {
1.235     brouard  14937:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  14938:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  14939:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   14940:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   14941:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   14942:        }
1.269     brouard  14943:       } else if (mobilavproj !=0) {
1.235     brouard  14944:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  14945:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  14946:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   14947:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   14948:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   14949:        }
1.269     brouard  14950:       }else{
                   14951:        printf("Internal error moving average\n");
                   14952:        fflush(stdout);
                   14953:        exit(1);
1.219     brouard  14954:       }
                   14955:     }/* end if moving average */
1.227     brouard  14956:     
1.126     brouard  14957:     /*---------- Forecasting ------------------*/
1.296     brouard  14958:     if(prevfcast==1){ 
                   14959:       /*   /\*    if(stepm ==1){*\/ */
                   14960:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   14961:       /*This done previously after freqsummary.*/
                   14962:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   14963:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   14964:       
                   14965:       /* } else if (prvforecast==2){ */
                   14966:       /*   /\*    if(stepm ==1){*\/ */
                   14967:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   14968:       /* } */
                   14969:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   14970:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  14971:     }
1.269     brouard  14972: 
1.296     brouard  14973:     /* Prevbcasting */
                   14974:     if(prevbcast==1){
1.219     brouard  14975:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   14976:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   14977:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   14978: 
                   14979:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   14980: 
                   14981:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  14982: 
1.219     brouard  14983:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   14984:       fclose(ficresplb);
                   14985: 
1.222     brouard  14986:       hBijx(p, bage, fage, mobaverage);
                   14987:       fclose(ficrespijb);
1.219     brouard  14988: 
1.296     brouard  14989:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   14990:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   14991:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   14992:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   14993:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   14994:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   14995: 
                   14996:       
1.269     brouard  14997:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  14998: 
                   14999:       
1.269     brouard  15000:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  15001:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   15002:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   15003:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  15004:     }    /* end  Prevbcasting */
1.268     brouard  15005:  
1.186     brouard  15006:  
                   15007:     /* ------ Other prevalence ratios------------ */
1.126     brouard  15008: 
1.215     brouard  15009:     free_ivector(wav,1,imx);
                   15010:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   15011:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   15012:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  15013:                
                   15014:                
1.127     brouard  15015:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  15016:                
1.201     brouard  15017:     strcpy(filerese,"E_");
                   15018:     strcat(filerese,fileresu);
1.126     brouard  15019:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   15020:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   15021:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   15022:     }
1.208     brouard  15023:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   15024:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  15025: 
                   15026:     pstamp(ficreseij);
1.219     brouard  15027:                
1.351     brouard  15028:     /* i1=pow(2,cptcoveff); /\* Number of combination of dummy covariates *\/ */
                   15029:     /* if (cptcovn < 1){i1=1;} */
1.235     brouard  15030:     
1.351     brouard  15031:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   15032:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   15033:       /* if(i1 != 1 && TKresult[nres]!= k) */
                   15034:       /*       continue; */
1.219     brouard  15035:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  15036:       printf("\n#****** ");
1.351     brouard  15037:       for(j=1;j<=cptcovs;j++){
                   15038:       /* for(j=1;j<=cptcoveff;j++) { */
                   15039:        /* fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15040:        fprintf(ficreseij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   15041:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   15042:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.235     brouard  15043:       }
                   15044:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.337     brouard  15045:        printf(" V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]); /* TvarsQ[j] gives the name of the jth quantitative (fixed or time v) */
                   15046:        fprintf(ficreseij,"V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]);
1.219     brouard  15047:       }
                   15048:       fprintf(ficreseij,"******\n");
1.235     brouard  15049:       printf("******\n");
1.219     brouard  15050:       
                   15051:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   15052:       oldm=oldms;savm=savms;
1.330     brouard  15053:       /* 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  15054:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  15055:       
1.219     brouard  15056:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  15057:     }
                   15058:     fclose(ficreseij);
1.208     brouard  15059:     printf("done evsij\n");fflush(stdout);
                   15060:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  15061: 
1.218     brouard  15062:                
1.227     brouard  15063:     /*---------- State-specific expectancies and variances ------------*/
1.336     brouard  15064:     /* Should be moved in a function */                
1.201     brouard  15065:     strcpy(filerest,"T_");
                   15066:     strcat(filerest,fileresu);
1.127     brouard  15067:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   15068:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   15069:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   15070:     }
1.208     brouard  15071:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   15072:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  15073:     strcpy(fileresstde,"STDE_");
                   15074:     strcat(fileresstde,fileresu);
1.126     brouard  15075:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  15076:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   15077:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  15078:     }
1.227     brouard  15079:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   15080:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  15081: 
1.201     brouard  15082:     strcpy(filerescve,"CVE_");
                   15083:     strcat(filerescve,fileresu);
1.126     brouard  15084:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  15085:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   15086:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  15087:     }
1.227     brouard  15088:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   15089:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  15090: 
1.201     brouard  15091:     strcpy(fileresv,"V_");
                   15092:     strcat(fileresv,fileresu);
1.126     brouard  15093:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   15094:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   15095:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   15096:     }
1.227     brouard  15097:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   15098:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  15099: 
1.235     brouard  15100:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   15101:     if (cptcovn < 1){i1=1;}
                   15102:     
1.334     brouard  15103:     for(nres=1; nres <= nresult; nres++) /* For each resultline, find the combination and output results according to the values of dummies and then quanti.  */
                   15104:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying. For each nres and each value at position k
                   15105:                          * we know Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline
                   15106:                          * Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline 
                   15107:                          * and Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
                   15108:       /* */
                   15109:       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  15110:        continue;
1.350     brouard  15111:       printf("\n# model %s \n#****** Result for:", model);  /* HERE model is empty */
1.321     brouard  15112:       fprintf(ficrest,"\n# model %s \n#****** Result for:", model);
                   15113:       fprintf(ficlog,"\n# model %s \n#****** Result for:", model);
1.334     brouard  15114:       /* It might not be a good idea to mix dummies and quantitative */
                   15115:       /* 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 *\/ */
                   15116:       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 */
                   15117:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* Output by variables in the resultline *\/ */
                   15118:        /* Tvaraff[j] is the name of the dummy variable in position j in the equation model:
                   15119:         * Tvaraff[1]@9={4, 3, 0, 0, 0, 0, 0, 0, 0}, in model=V5+V4+V3+V4*V3+V5*age
                   15120:         * (V5 is quanti) V4 and V3 are dummies
                   15121:         * TnsdVar[4] is the position 1 and TnsdVar[3]=2 in codtabm(k,l)(V4  V3)=V4  V3
                   15122:         *                                                              l=1 l=2
                   15123:         *                                                           k=1  1   1   0   0
                   15124:         *                                                           k=2  2   1   1   0
                   15125:         *                                                           k=3 [1] [2]  0   1
                   15126:         *                                                           k=4  2   2   1   1
                   15127:         * If nres=1 result: V3=1 V4=0 then k=3 and outputs
                   15128:         * If nres=2 result: V4=1 V3=0 then k=2 and outputs
                   15129:         * nres=1 =>k=3 j=1 V4= nbcode[4][codtabm(3,1)=1)=0; j=2  V3= nbcode[3][codtabm(3,2)=2]=1
                   15130:         * nres=2 =>k=2 j=1 V4= nbcode[4][codtabm(2,1)=2)=1; j=2  V3= nbcode[3][codtabm(2,2)=1]=0
                   15131:         */
                   15132:        /* Tvresult[nres][j] Name of the variable at position j in this resultline */
                   15133:        /* Tresult[nres][j] Value of this variable at position j could be a float if quantitative  */
                   15134: /* We give up with the combinations!! */
1.342     brouard  15135:        /* if(debugILK) */
                   15136:        /*   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  15137: 
                   15138:        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  15139:          /* 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] */
                   15140:          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  */
                   15141:          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  */
                   15142:          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  15143:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   15144:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   15145:          }else{
                   15146:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   15147:          }
                   15148:          /* fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15149:          /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15150:        }else if(Dummy[modelresult[nres][j]]==1){ /* Quanti variable */
                   15151:          /* For each selected (single) quantitative value */
1.337     brouard  15152:          printf(" V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   15153:          fprintf(ficlog," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   15154:          fprintf(ficrest," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
1.334     brouard  15155:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   15156:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   15157:          }else{
                   15158:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   15159:          }
                   15160:        }else{
                   15161:          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 */
                   15162:          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 */
                   15163:          exit(1);
                   15164:        }
1.335     brouard  15165:       } /* End loop for each variable in the resultline */
1.334     brouard  15166:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   15167:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /\* Wrong j is not in the equation model *\/ */
                   15168:       /*       fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   15169:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   15170:       /* }      */
1.208     brouard  15171:       fprintf(ficrest,"******\n");
1.227     brouard  15172:       fprintf(ficlog,"******\n");
                   15173:       printf("******\n");
1.208     brouard  15174:       
                   15175:       fprintf(ficresstdeij,"\n#****** ");
                   15176:       fprintf(ficrescveij,"\n#****** ");
1.337     brouard  15177:       /* It could have been: for(j=1;j<=cptcoveff;j++) {printf("V=%d=%lg",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);} */
                   15178:       /* But it won't be sorted and depends on how the resultline is ordered */
1.225     brouard  15179:       for(j=1;j<=cptcoveff;j++) {
1.334     brouard  15180:        fprintf(ficresstdeij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   15181:        /* fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15182:        /* fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15183:       }
                   15184:       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  15185:        fprintf(ficresstdeij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
                   15186:        fprintf(ficrescveij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
1.235     brouard  15187:       }        
1.208     brouard  15188:       fprintf(ficresstdeij,"******\n");
                   15189:       fprintf(ficrescveij,"******\n");
                   15190:       
                   15191:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  15192:       /* pstamp(ficresvij); */
1.225     brouard  15193:       for(j=1;j<=cptcoveff;j++) 
1.335     brouard  15194:        fprintf(ficresvij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   15195:        /* fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[TnsdVar[Tvaraff[j]]])]); */
1.235     brouard  15196:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  15197:        /* fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]); /\* To solve *\/ */
1.337     brouard  15198:        fprintf(ficresvij," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /* Solved */
1.235     brouard  15199:       }        
1.208     brouard  15200:       fprintf(ficresvij,"******\n");
                   15201:       
                   15202:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   15203:       oldm=oldms;savm=savms;
1.235     brouard  15204:       printf(" cvevsij ");
                   15205:       fprintf(ficlog, " cvevsij ");
                   15206:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  15207:       printf(" end cvevsij \n ");
                   15208:       fprintf(ficlog, " end cvevsij \n ");
                   15209:       
                   15210:       /*
                   15211:        */
                   15212:       /* goto endfree; */
                   15213:       
                   15214:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   15215:       pstamp(ficrest);
                   15216:       
1.269     brouard  15217:       epj=vector(1,nlstate+1);
1.208     brouard  15218:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  15219:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   15220:        cptcod= 0; /* To be deleted */
                   15221:        printf("varevsij vpopbased=%d \n",vpopbased);
                   15222:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  15223:        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  15224:        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 ");
                   15225:        if(vpopbased==1)
                   15226:          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);
                   15227:        else
1.288     brouard  15228:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
1.335     brouard  15229:        fprintf(ficrest,"# Age popbased mobilav e.. (std) "); /* Adding covariate values? */
1.227     brouard  15230:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   15231:        fprintf(ficrest,"\n");
                   15232:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  15233:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   15234:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  15235:        for(age=bage; age <=fage ;age++){
1.235     brouard  15236:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  15237:          if (vpopbased==1) {
                   15238:            if(mobilav ==0){
                   15239:              for(i=1; i<=nlstate;i++)
                   15240:                prlim[i][i]=probs[(int)age][i][k];
                   15241:            }else{ /* mobilav */ 
                   15242:              for(i=1; i<=nlstate;i++)
                   15243:                prlim[i][i]=mobaverage[(int)age][i][k];
                   15244:            }
                   15245:          }
1.219     brouard  15246:          
1.227     brouard  15247:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   15248:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   15249:          /* printf(" age %4.0f ",age); */
                   15250:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   15251:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   15252:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   15253:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   15254:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   15255:            }
                   15256:            epj[nlstate+1] +=epj[j];
                   15257:          }
                   15258:          /* printf(" age %4.0f \n",age); */
1.219     brouard  15259:          
1.227     brouard  15260:          for(i=1, vepp=0.;i <=nlstate;i++)
                   15261:            for(j=1;j <=nlstate;j++)
                   15262:              vepp += vareij[i][j][(int)age];
                   15263:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   15264:          for(j=1;j <=nlstate;j++){
                   15265:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   15266:          }
                   15267:          fprintf(ficrest,"\n");
                   15268:        }
1.208     brouard  15269:       } /* End vpopbased */
1.269     brouard  15270:       free_vector(epj,1,nlstate+1);
1.208     brouard  15271:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   15272:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  15273:       printf("done selection\n");fflush(stdout);
                   15274:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  15275:       
1.335     brouard  15276:     } /* End k selection or end covariate selection for nres */
1.227     brouard  15277: 
                   15278:     printf("done State-specific expectancies\n");fflush(stdout);
                   15279:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   15280: 
1.335     brouard  15281:     /* variance-covariance of forward period prevalence */
1.269     brouard  15282:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  15283: 
1.227     brouard  15284:     
1.290     brouard  15285:     free_vector(weight,firstobs,lastobs);
1.351     brouard  15286:     free_imatrix(Tvardk,0,NCOVMAX,1,2);
1.227     brouard  15287:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  15288:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   15289:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   15290:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   15291:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  15292:     free_ivector(tab,1,NCOVMAX);
                   15293:     fclose(ficresstdeij);
                   15294:     fclose(ficrescveij);
                   15295:     fclose(ficresvij);
                   15296:     fclose(ficrest);
                   15297:     fclose(ficpar);
                   15298:     
                   15299:     
1.126     brouard  15300:     /*---------- End : free ----------------*/
1.219     brouard  15301:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  15302:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   15303:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  15304:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   15305:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  15306:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  15307:   /* endfree:*/
                   15308:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   15309:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   15310:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.341     brouard  15311:   /* if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs); */
                   15312:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);
1.290     brouard  15313:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   15314:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   15315:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  15316:   free_matrix(matcov,1,npar,1,npar);
                   15317:   free_matrix(hess,1,npar,1,npar);
                   15318:   /*free_vector(delti,1,npar);*/
                   15319:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   15320:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  15321:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  15322:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   15323:   
                   15324:   free_ivector(ncodemax,1,NCOVMAX);
                   15325:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   15326:   free_ivector(Dummy,-1,NCOVMAX);
                   15327:   free_ivector(Fixed,-1,NCOVMAX);
1.349     brouard  15328:   free_ivector(DummyV,-1,NCOVMAX);
                   15329:   free_ivector(FixedV,-1,NCOVMAX);
1.227     brouard  15330:   free_ivector(Typevar,-1,NCOVMAX);
                   15331:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  15332:   free_ivector(TvarsQ,1,NCOVMAX);
                   15333:   free_ivector(TvarsQind,1,NCOVMAX);
                   15334:   free_ivector(TvarsD,1,NCOVMAX);
1.330     brouard  15335:   free_ivector(TnsdVar,1,NCOVMAX);
1.234     brouard  15336:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  15337:   free_ivector(TvarFD,1,NCOVMAX);
                   15338:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  15339:   free_ivector(TvarF,1,NCOVMAX);
                   15340:   free_ivector(TvarFind,1,NCOVMAX);
                   15341:   free_ivector(TvarV,1,NCOVMAX);
                   15342:   free_ivector(TvarVind,1,NCOVMAX);
                   15343:   free_ivector(TvarA,1,NCOVMAX);
                   15344:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  15345:   free_ivector(TvarFQ,1,NCOVMAX);
                   15346:   free_ivector(TvarFQind,1,NCOVMAX);
                   15347:   free_ivector(TvarVD,1,NCOVMAX);
                   15348:   free_ivector(TvarVDind,1,NCOVMAX);
                   15349:   free_ivector(TvarVQ,1,NCOVMAX);
                   15350:   free_ivector(TvarVQind,1,NCOVMAX);
1.349     brouard  15351:   free_ivector(TvarAVVA,1,NCOVMAX);
                   15352:   free_ivector(TvarAVVAind,1,NCOVMAX);
                   15353:   free_ivector(TvarVVA,1,NCOVMAX);
                   15354:   free_ivector(TvarVVAind,1,NCOVMAX);
1.339     brouard  15355:   free_ivector(TvarVV,1,NCOVMAX);
                   15356:   free_ivector(TvarVVind,1,NCOVMAX);
                   15357:   
1.230     brouard  15358:   free_ivector(Tvarsel,1,NCOVMAX);
                   15359:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  15360:   free_ivector(Tposprod,1,NCOVMAX);
                   15361:   free_ivector(Tprod,1,NCOVMAX);
                   15362:   free_ivector(Tvaraff,1,NCOVMAX);
1.338     brouard  15363:   free_ivector(invalidvarcomb,0,ncovcombmax);
1.227     brouard  15364:   free_ivector(Tage,1,NCOVMAX);
                   15365:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  15366:   free_ivector(TmodelInvind,1,NCOVMAX);
                   15367:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.332     brouard  15368: 
                   15369:   free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /* Could be elsewhere ?*/
                   15370: 
1.227     brouard  15371:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   15372:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  15373:   fflush(fichtm);
                   15374:   fflush(ficgp);
                   15375:   
1.227     brouard  15376:   
1.126     brouard  15377:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  15378:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   15379:     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  15380:   }else{
                   15381:     printf("End of Imach\n");
                   15382:     fprintf(ficlog,"End of Imach\n");
                   15383:   }
                   15384:   printf("See log file on %s\n",filelog);
                   15385:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  15386:   /*(void) gettimeofday(&end_time,&tzp);*/
                   15387:   rend_time = time(NULL);  
                   15388:   end_time = *localtime(&rend_time);
                   15389:   /* tml = *localtime(&end_time.tm_sec); */
                   15390:   strcpy(strtend,asctime(&end_time));
1.126     brouard  15391:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   15392:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  15393:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  15394:   
1.157     brouard  15395:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   15396:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   15397:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  15398:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   15399: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   15400:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   15401:   fclose(fichtm);
                   15402:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   15403:   fclose(fichtmcov);
                   15404:   fclose(ficgp);
                   15405:   fclose(ficlog);
                   15406:   /*------ End -----------*/
1.227     brouard  15407:   
1.281     brouard  15408: 
                   15409: /* Executes gnuplot */
1.227     brouard  15410:   
                   15411:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  15412: #ifdef WIN32
1.227     brouard  15413:   if (_chdir(pathcd) != 0)
                   15414:     printf("Can't move to directory %s!\n",path);
                   15415:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  15416: #else
1.227     brouard  15417:     if(chdir(pathcd) != 0)
                   15418:       printf("Can't move to directory %s!\n", path);
                   15419:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  15420: #endif 
1.126     brouard  15421:     printf("Current directory %s!\n",pathcd);
                   15422:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   15423:   sprintf(plotcmd,"gnuplot");
1.157     brouard  15424: #ifdef _WIN32
1.126     brouard  15425:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   15426: #endif
                   15427:   if(!stat(plotcmd,&info)){
1.158     brouard  15428:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  15429:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  15430:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  15431:     }else
                   15432:       strcpy(pplotcmd,plotcmd);
1.157     brouard  15433: #ifdef __unix
1.126     brouard  15434:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   15435:     if(!stat(plotcmd,&info)){
1.158     brouard  15436:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  15437:     }else
                   15438:       strcpy(pplotcmd,plotcmd);
                   15439: #endif
                   15440:   }else
                   15441:     strcpy(pplotcmd,plotcmd);
                   15442:   
                   15443:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  15444:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  15445:   strcpy(pplotcmd,plotcmd);
1.227     brouard  15446:   
1.126     brouard  15447:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  15448:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  15449:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  15450:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  15451:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  15452:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  15453:       strcpy(plotcmd,pplotcmd);
                   15454:     }
1.126     brouard  15455:   }
1.158     brouard  15456:   printf(" Successful, please wait...");
1.126     brouard  15457:   while (z[0] != 'q') {
                   15458:     /* chdir(path); */
1.154     brouard  15459:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  15460:     scanf("%s",z);
                   15461: /*     if (z[0] == 'c') system("./imach"); */
                   15462:     if (z[0] == 'e') {
1.158     brouard  15463: #ifdef __APPLE__
1.152     brouard  15464:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  15465: #elif __linux
                   15466:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  15467: #else
1.152     brouard  15468:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  15469: #endif
                   15470:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   15471:       system(pplotcmd);
1.126     brouard  15472:     }
                   15473:     else if (z[0] == 'g') system(plotcmd);
                   15474:     else if (z[0] == 'q') exit(0);
                   15475:   }
1.227     brouard  15476: end:
1.126     brouard  15477:   while (z[0] != 'q') {
1.195     brouard  15478:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  15479:     scanf("%s",z);
                   15480:   }
1.283     brouard  15481:   printf("End\n");
1.282     brouard  15482:   exit(0);
1.126     brouard  15483: }

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