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

1.340   ! brouard     1: /* $Id: imach.c,v 1.339 2022/09/09 17:55:22 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.340   ! brouard     4:   Revision 1.339  2022/09/09 17:55:22  brouard
        !             5:   Summary: version 0.99r37
        !             6: 
        !             7:   * imach.c (Module): Many improvements for fixing products of fixed
        !             8:   timevarying as well as fixed * fixed, and test with quantitative
        !             9:   covariate.
        !            10: 
1.339     brouard    11:   Revision 1.338  2022/09/04 17:40:33  brouard
                     12:   Summary: 0.99r36
                     13: 
                     14:   * imach.c (Module): Now the easy runs i.e. without result or
                     15:   model=1+age only did not work. The defautl combination should be 1
                     16:   and not 0 because everything hasn't been tranformed yet.
                     17: 
1.338     brouard    18:   Revision 1.337  2022/09/02 14:26:02  brouard
                     19:   Summary: version 0.99r35
                     20: 
                     21:   * src/imach.c: Version 0.99r35 because it outputs same results with
                     22:   1+age+V1+V1*age for females and 1+age for females only
                     23:   (education=1 noweight)
                     24: 
1.337     brouard    25:   Revision 1.336  2022/08/31 09:52:36  brouard
                     26:   *** empty log message ***
                     27: 
1.336     brouard    28:   Revision 1.335  2022/08/31 08:23:16  brouard
                     29:   Summary: improvements...
                     30: 
1.335     brouard    31:   Revision 1.334  2022/08/25 09:08:41  brouard
                     32:   Summary: In progress for quantitative
                     33: 
1.334     brouard    34:   Revision 1.333  2022/08/21 09:10:30  brouard
                     35:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                     36:   reassigning covariates: my first idea was that people will always
                     37:   use the first covariate V1 into the model but in fact they are
                     38:   producing data with many covariates and can use an equation model
                     39:   with some of the covariate; it means that in a model V2+V3 instead
                     40:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                     41:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                     42:   the equation model is restricted to two variables only (V2, V3)
                     43:   and the combination for V2 should be codtabm(k,1) instead of
                     44:   (codtabm(k,2), and the code should be
                     45:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                     46:   made. All of these should be simplified once a day like we did in
                     47:   hpxij() for example by using precov[nres] which is computed in
                     48:   decoderesult for each nres of each resultline. Loop should be done
                     49:   on the equation model globally by distinguishing only product with
                     50:   age (which are changing with age) and no more on type of
                     51:   covariates, single dummies, single covariates.
                     52: 
1.333     brouard    53:   Revision 1.332  2022/08/21 09:06:25  brouard
                     54:   Summary: Version 0.99r33
                     55: 
                     56:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                     57:   reassigning covariates: my first idea was that people will always
                     58:   use the first covariate V1 into the model but in fact they are
                     59:   producing data with many covariates and can use an equation model
                     60:   with some of the covariate; it means that in a model V2+V3 instead
                     61:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                     62:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                     63:   the equation model is restricted to two variables only (V2, V3)
                     64:   and the combination for V2 should be codtabm(k,1) instead of
                     65:   (codtabm(k,2), and the code should be
                     66:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                     67:   made. All of these should be simplified once a day like we did in
                     68:   hpxij() for example by using precov[nres] which is computed in
                     69:   decoderesult for each nres of each resultline. Loop should be done
                     70:   on the equation model globally by distinguishing only product with
                     71:   age (which are changing with age) and no more on type of
                     72:   covariates, single dummies, single covariates.
                     73: 
1.332     brouard    74:   Revision 1.331  2022/08/07 05:40:09  brouard
                     75:   *** empty log message ***
                     76: 
1.331     brouard    77:   Revision 1.330  2022/08/06 07:18:25  brouard
                     78:   Summary: last 0.99r31
                     79: 
                     80:   *  imach.c (Module): Version of imach using partly decoderesult to rebuild xpxij function
                     81: 
1.330     brouard    82:   Revision 1.329  2022/08/03 17:29:54  brouard
                     83:   *  imach.c (Module): Many errors in graphs fixed with Vn*age covariates.
                     84: 
1.329     brouard    85:   Revision 1.328  2022/07/27 17:40:48  brouard
                     86:   Summary: valgrind bug fixed by initializing to zero DummyV as well as Tage
                     87: 
1.328     brouard    88:   Revision 1.327  2022/07/27 14:47:35  brouard
                     89:   Summary: Still a problem for one-step probabilities in case of quantitative variables
                     90: 
1.327     brouard    91:   Revision 1.326  2022/07/26 17:33:55  brouard
                     92:   Summary: some test with nres=1
                     93: 
1.326     brouard    94:   Revision 1.325  2022/07/25 14:27:23  brouard
                     95:   Summary: r30
                     96: 
                     97:   * imach.c (Module): Error cptcovn instead of nsd in bmij (was
                     98:   coredumped, revealed by Feiuno, thank you.
                     99: 
1.325     brouard   100:   Revision 1.324  2022/07/23 17:44:26  brouard
                    101:   *** empty log message ***
                    102: 
1.324     brouard   103:   Revision 1.323  2022/07/22 12:30:08  brouard
                    104:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    105: 
1.323     brouard   106:   Revision 1.322  2022/07/22 12:27:48  brouard
                    107:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    108: 
1.322     brouard   109:   Revision 1.321  2022/07/22 12:04:24  brouard
                    110:   Summary: r28
                    111: 
                    112:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    113: 
1.321     brouard   114:   Revision 1.320  2022/06/02 05:10:11  brouard
                    115:   *** empty log message ***
                    116: 
1.320     brouard   117:   Revision 1.319  2022/06/02 04:45:11  brouard
                    118:   * imach.c (Module): Adding the Wald tests from the log to the main
                    119:   htm for better display of the maximum likelihood estimators.
                    120: 
1.319     brouard   121:   Revision 1.318  2022/05/24 08:10:59  brouard
                    122:   * imach.c (Module): Some attempts to find a bug of wrong estimates
                    123:   of confidencce intervals with product in the equation modelC
                    124: 
1.318     brouard   125:   Revision 1.317  2022/05/15 15:06:23  brouard
                    126:   * imach.c (Module):  Some minor improvements
                    127: 
1.317     brouard   128:   Revision 1.316  2022/05/11 15:11:31  brouard
                    129:   Summary: r27
                    130: 
1.316     brouard   131:   Revision 1.315  2022/05/11 15:06:32  brouard
                    132:   *** empty log message ***
                    133: 
1.315     brouard   134:   Revision 1.314  2022/04/13 17:43:09  brouard
                    135:   * imach.c (Module): Adding link to text data files
                    136: 
1.314     brouard   137:   Revision 1.313  2022/04/11 15:57:42  brouard
                    138:   * imach.c (Module): Error in rewriting the 'r' file with yearsfproj or yearsbproj fixed
                    139: 
1.313     brouard   140:   Revision 1.312  2022/04/05 21:24:39  brouard
                    141:   *** empty log message ***
                    142: 
1.312     brouard   143:   Revision 1.311  2022/04/05 21:03:51  brouard
                    144:   Summary: Fixed quantitative covariates
                    145: 
                    146:          Fixed covariates (dummy or quantitative)
                    147:        with missing values have never been allowed but are ERRORS and
                    148:        program quits. Standard deviations of fixed covariates were
                    149:        wrongly computed. Mean and standard deviations of time varying
                    150:        covariates are still not computed.
                    151: 
1.311     brouard   152:   Revision 1.310  2022/03/17 08:45:53  brouard
                    153:   Summary: 99r25
                    154: 
                    155:   Improving detection of errors: result lines should be compatible with
                    156:   the model.
                    157: 
1.310     brouard   158:   Revision 1.309  2021/05/20 12:39:14  brouard
                    159:   Summary: Version 0.99r24
                    160: 
1.309     brouard   161:   Revision 1.308  2021/03/31 13:11:57  brouard
                    162:   Summary: Version 0.99r23
                    163: 
                    164: 
                    165:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
                    166: 
1.308     brouard   167:   Revision 1.307  2021/03/08 18:11:32  brouard
                    168:   Summary: 0.99r22 fixed bug on result:
                    169: 
1.307     brouard   170:   Revision 1.306  2021/02/20 15:44:02  brouard
                    171:   Summary: Version 0.99r21
                    172: 
                    173:   * imach.c (Module): Fix bug on quitting after result lines!
                    174:   (Module): Version 0.99r21
                    175: 
1.306     brouard   176:   Revision 1.305  2021/02/20 15:28:30  brouard
                    177:   * imach.c (Module): Fix bug on quitting after result lines!
                    178: 
1.305     brouard   179:   Revision 1.304  2021/02/12 11:34:20  brouard
                    180:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
                    181: 
1.304     brouard   182:   Revision 1.303  2021/02/11 19:50:15  brouard
                    183:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
                    184: 
1.303     brouard   185:   Revision 1.302  2020/02/22 21:00:05  brouard
                    186:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
                    187:   and life table from the data without any state)
                    188: 
1.302     brouard   189:   Revision 1.301  2019/06/04 13:51:20  brouard
                    190:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                    191: 
1.301     brouard   192:   Revision 1.300  2019/05/22 19:09:45  brouard
                    193:   Summary: version 0.99r19 of May 2019
                    194: 
1.300     brouard   195:   Revision 1.299  2019/05/22 18:37:08  brouard
                    196:   Summary: Cleaned 0.99r19
                    197: 
1.299     brouard   198:   Revision 1.298  2019/05/22 18:19:56  brouard
                    199:   *** empty log message ***
                    200: 
1.298     brouard   201:   Revision 1.297  2019/05/22 17:56:10  brouard
                    202:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                    203: 
1.297     brouard   204:   Revision 1.296  2019/05/20 13:03:18  brouard
                    205:   Summary: Projection syntax simplified
                    206: 
                    207: 
                    208:   We can now start projections, forward or backward, from the mean date
                    209:   of inteviews up to or down to a number of years of projection:
                    210:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                    211:   or
                    212:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                    213:   or
                    214:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                    215:   or
                    216:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                    217: 
1.296     brouard   218:   Revision 1.295  2019/05/18 09:52:50  brouard
                    219:   Summary: doxygen tex bug
                    220: 
1.295     brouard   221:   Revision 1.294  2019/05/16 14:54:33  brouard
                    222:   Summary: There was some wrong lines added
                    223: 
1.294     brouard   224:   Revision 1.293  2019/05/09 15:17:34  brouard
                    225:   *** empty log message ***
                    226: 
1.293     brouard   227:   Revision 1.292  2019/05/09 14:17:20  brouard
                    228:   Summary: Some updates
                    229: 
1.292     brouard   230:   Revision 1.291  2019/05/09 13:44:18  brouard
                    231:   Summary: Before ncovmax
                    232: 
1.291     brouard   233:   Revision 1.290  2019/05/09 13:39:37  brouard
                    234:   Summary: 0.99r18 unlimited number of individuals
                    235: 
                    236:   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.
                    237: 
1.290     brouard   238:   Revision 1.289  2018/12/13 09:16:26  brouard
                    239:   Summary: Bug for young ages (<-30) will be in r17
                    240: 
1.289     brouard   241:   Revision 1.288  2018/05/02 20:58:27  brouard
                    242:   Summary: Some bugs fixed
                    243: 
1.288     brouard   244:   Revision 1.287  2018/05/01 17:57:25  brouard
                    245:   Summary: Bug fixed by providing frequencies only for non missing covariates
                    246: 
1.287     brouard   247:   Revision 1.286  2018/04/27 14:27:04  brouard
                    248:   Summary: some minor bugs
                    249: 
1.286     brouard   250:   Revision 1.285  2018/04/21 21:02:16  brouard
                    251:   Summary: Some bugs fixed, valgrind tested
                    252: 
1.285     brouard   253:   Revision 1.284  2018/04/20 05:22:13  brouard
                    254:   Summary: Computing mean and stdeviation of fixed quantitative variables
                    255: 
1.284     brouard   256:   Revision 1.283  2018/04/19 14:49:16  brouard
                    257:   Summary: Some minor bugs fixed
                    258: 
1.283     brouard   259:   Revision 1.282  2018/02/27 22:50:02  brouard
                    260:   *** empty log message ***
                    261: 
1.282     brouard   262:   Revision 1.281  2018/02/27 19:25:23  brouard
                    263:   Summary: Adding second argument for quitting
                    264: 
1.281     brouard   265:   Revision 1.280  2018/02/21 07:58:13  brouard
                    266:   Summary: 0.99r15
                    267: 
                    268:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                    269: 
1.280     brouard   270:   Revision 1.279  2017/07/20 13:35:01  brouard
                    271:   Summary: temporary working
                    272: 
1.279     brouard   273:   Revision 1.278  2017/07/19 14:09:02  brouard
                    274:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                    275: 
1.278     brouard   276:   Revision 1.277  2017/07/17 08:53:49  brouard
                    277:   Summary: BOM files can be read now
                    278: 
1.277     brouard   279:   Revision 1.276  2017/06/30 15:48:31  brouard
                    280:   Summary: Graphs improvements
                    281: 
1.276     brouard   282:   Revision 1.275  2017/06/30 13:39:33  brouard
                    283:   Summary: Saito's color
                    284: 
1.275     brouard   285:   Revision 1.274  2017/06/29 09:47:08  brouard
                    286:   Summary: Version 0.99r14
                    287: 
1.274     brouard   288:   Revision 1.273  2017/06/27 11:06:02  brouard
                    289:   Summary: More documentation on projections
                    290: 
1.273     brouard   291:   Revision 1.272  2017/06/27 10:22:40  brouard
                    292:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    293: 
1.272     brouard   294:   Revision 1.271  2017/06/27 10:17:50  brouard
                    295:   Summary: Some bug with rint
                    296: 
1.271     brouard   297:   Revision 1.270  2017/05/24 05:45:29  brouard
                    298:   *** empty log message ***
                    299: 
1.270     brouard   300:   Revision 1.269  2017/05/23 08:39:25  brouard
                    301:   Summary: Code into subroutine, cleanings
                    302: 
1.269     brouard   303:   Revision 1.268  2017/05/18 20:09:32  brouard
                    304:   Summary: backprojection and confidence intervals of backprevalence
                    305: 
1.268     brouard   306:   Revision 1.267  2017/05/13 10:25:05  brouard
                    307:   Summary: temporary save for backprojection
                    308: 
1.267     brouard   309:   Revision 1.266  2017/05/13 07:26:12  brouard
                    310:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    311: 
1.266     brouard   312:   Revision 1.265  2017/04/26 16:22:11  brouard
                    313:   Summary: imach 0.99r13 Some bugs fixed
                    314: 
1.265     brouard   315:   Revision 1.264  2017/04/26 06:01:29  brouard
                    316:   Summary: Labels in graphs
                    317: 
1.264     brouard   318:   Revision 1.263  2017/04/24 15:23:15  brouard
                    319:   Summary: to save
                    320: 
1.263     brouard   321:   Revision 1.262  2017/04/18 16:48:12  brouard
                    322:   *** empty log message ***
                    323: 
1.262     brouard   324:   Revision 1.261  2017/04/05 10:14:09  brouard
                    325:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    326: 
1.261     brouard   327:   Revision 1.260  2017/04/04 17:46:59  brouard
                    328:   Summary: Gnuplot indexations fixed (humm)
                    329: 
1.260     brouard   330:   Revision 1.259  2017/04/04 13:01:16  brouard
                    331:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    332: 
1.259     brouard   333:   Revision 1.258  2017/04/03 10:17:47  brouard
                    334:   Summary: Version 0.99r12
                    335: 
                    336:   Some cleanings, conformed with updated documentation.
                    337: 
1.258     brouard   338:   Revision 1.257  2017/03/29 16:53:30  brouard
                    339:   Summary: Temp
                    340: 
1.257     brouard   341:   Revision 1.256  2017/03/27 05:50:23  brouard
                    342:   Summary: Temporary
                    343: 
1.256     brouard   344:   Revision 1.255  2017/03/08 16:02:28  brouard
                    345:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    346: 
1.255     brouard   347:   Revision 1.254  2017/03/08 07:13:00  brouard
                    348:   Summary: Fixing data parameter line
                    349: 
1.254     brouard   350:   Revision 1.253  2016/12/15 11:59:41  brouard
                    351:   Summary: 0.99 in progress
                    352: 
1.253     brouard   353:   Revision 1.252  2016/09/15 21:15:37  brouard
                    354:   *** empty log message ***
                    355: 
1.252     brouard   356:   Revision 1.251  2016/09/15 15:01:13  brouard
                    357:   Summary: not working
                    358: 
1.251     brouard   359:   Revision 1.250  2016/09/08 16:07:27  brouard
                    360:   Summary: continue
                    361: 
1.250     brouard   362:   Revision 1.249  2016/09/07 17:14:18  brouard
                    363:   Summary: Starting values from frequencies
                    364: 
1.249     brouard   365:   Revision 1.248  2016/09/07 14:10:18  brouard
                    366:   *** empty log message ***
                    367: 
1.248     brouard   368:   Revision 1.247  2016/09/02 11:11:21  brouard
                    369:   *** empty log message ***
                    370: 
1.247     brouard   371:   Revision 1.246  2016/09/02 08:49:22  brouard
                    372:   *** empty log message ***
                    373: 
1.246     brouard   374:   Revision 1.245  2016/09/02 07:25:01  brouard
                    375:   *** empty log message ***
                    376: 
1.245     brouard   377:   Revision 1.244  2016/09/02 07:17:34  brouard
                    378:   *** empty log message ***
                    379: 
1.244     brouard   380:   Revision 1.243  2016/09/02 06:45:35  brouard
                    381:   *** empty log message ***
                    382: 
1.243     brouard   383:   Revision 1.242  2016/08/30 15:01:20  brouard
                    384:   Summary: Fixing a lots
                    385: 
1.242     brouard   386:   Revision 1.241  2016/08/29 17:17:25  brouard
                    387:   Summary: gnuplot problem in Back projection to fix
                    388: 
1.241     brouard   389:   Revision 1.240  2016/08/29 07:53:18  brouard
                    390:   Summary: Better
                    391: 
1.240     brouard   392:   Revision 1.239  2016/08/26 15:51:03  brouard
                    393:   Summary: Improvement in Powell output in order to copy and paste
                    394: 
                    395:   Author:
                    396: 
1.239     brouard   397:   Revision 1.238  2016/08/26 14:23:35  brouard
                    398:   Summary: Starting tests of 0.99
                    399: 
1.238     brouard   400:   Revision 1.237  2016/08/26 09:20:19  brouard
                    401:   Summary: to valgrind
                    402: 
1.237     brouard   403:   Revision 1.236  2016/08/25 10:50:18  brouard
                    404:   *** empty log message ***
                    405: 
1.236     brouard   406:   Revision 1.235  2016/08/25 06:59:23  brouard
                    407:   *** empty log message ***
                    408: 
1.235     brouard   409:   Revision 1.234  2016/08/23 16:51:20  brouard
                    410:   *** empty log message ***
                    411: 
1.234     brouard   412:   Revision 1.233  2016/08/23 07:40:50  brouard
                    413:   Summary: not working
                    414: 
1.233     brouard   415:   Revision 1.232  2016/08/22 14:20:21  brouard
                    416:   Summary: not working
                    417: 
1.232     brouard   418:   Revision 1.231  2016/08/22 07:17:15  brouard
                    419:   Summary: not working
                    420: 
1.231     brouard   421:   Revision 1.230  2016/08/22 06:55:53  brouard
                    422:   Summary: Not working
                    423: 
1.230     brouard   424:   Revision 1.229  2016/07/23 09:45:53  brouard
                    425:   Summary: Completing for func too
                    426: 
1.229     brouard   427:   Revision 1.228  2016/07/22 17:45:30  brouard
                    428:   Summary: Fixing some arrays, still debugging
                    429: 
1.227     brouard   430:   Revision 1.226  2016/07/12 18:42:34  brouard
                    431:   Summary: temp
                    432: 
1.226     brouard   433:   Revision 1.225  2016/07/12 08:40:03  brouard
                    434:   Summary: saving but not running
                    435: 
1.225     brouard   436:   Revision 1.224  2016/07/01 13:16:01  brouard
                    437:   Summary: Fixes
                    438: 
1.224     brouard   439:   Revision 1.223  2016/02/19 09:23:35  brouard
                    440:   Summary: temporary
                    441: 
1.223     brouard   442:   Revision 1.222  2016/02/17 08:14:50  brouard
                    443:   Summary: Probably last 0.98 stable version 0.98r6
                    444: 
1.222     brouard   445:   Revision 1.221  2016/02/15 23:35:36  brouard
                    446:   Summary: minor bug
                    447: 
1.220     brouard   448:   Revision 1.219  2016/02/15 00:48:12  brouard
                    449:   *** empty log message ***
                    450: 
1.219     brouard   451:   Revision 1.218  2016/02/12 11:29:23  brouard
                    452:   Summary: 0.99 Back projections
                    453: 
1.218     brouard   454:   Revision 1.217  2015/12/23 17:18:31  brouard
                    455:   Summary: Experimental backcast
                    456: 
1.217     brouard   457:   Revision 1.216  2015/12/18 17:32:11  brouard
                    458:   Summary: 0.98r4 Warning and status=-2
                    459: 
                    460:   Version 0.98r4 is now:
                    461:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    462:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    463:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    464: 
1.216     brouard   465:   Revision 1.215  2015/12/16 08:52:24  brouard
                    466:   Summary: 0.98r4 working
                    467: 
1.215     brouard   468:   Revision 1.214  2015/12/16 06:57:54  brouard
                    469:   Summary: temporary not working
                    470: 
1.214     brouard   471:   Revision 1.213  2015/12/11 18:22:17  brouard
                    472:   Summary: 0.98r4
                    473: 
1.213     brouard   474:   Revision 1.212  2015/11/21 12:47:24  brouard
                    475:   Summary: minor typo
                    476: 
1.212     brouard   477:   Revision 1.211  2015/11/21 12:41:11  brouard
                    478:   Summary: 0.98r3 with some graph of projected cross-sectional
                    479: 
                    480:   Author: Nicolas Brouard
                    481: 
1.211     brouard   482:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   483:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   484:   Summary: Adding ftolpl parameter
                    485:   Author: N Brouard
                    486: 
                    487:   We had difficulties to get smoothed confidence intervals. It was due
                    488:   to the period prevalence which wasn't computed accurately. The inner
                    489:   parameter ftolpl is now an outer parameter of the .imach parameter
                    490:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    491:   computation are long.
                    492: 
1.209     brouard   493:   Revision 1.208  2015/11/17 14:31:57  brouard
                    494:   Summary: temporary
                    495: 
1.208     brouard   496:   Revision 1.207  2015/10/27 17:36:57  brouard
                    497:   *** empty log message ***
                    498: 
1.207     brouard   499:   Revision 1.206  2015/10/24 07:14:11  brouard
                    500:   *** empty log message ***
                    501: 
1.206     brouard   502:   Revision 1.205  2015/10/23 15:50:53  brouard
                    503:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    504: 
1.205     brouard   505:   Revision 1.204  2015/10/01 16:20:26  brouard
                    506:   Summary: Some new graphs of contribution to likelihood
                    507: 
1.204     brouard   508:   Revision 1.203  2015/09/30 17:45:14  brouard
                    509:   Summary: looking at better estimation of the hessian
                    510: 
                    511:   Also a better criteria for convergence to the period prevalence And
                    512:   therefore adding the number of years needed to converge. (The
                    513:   prevalence in any alive state shold sum to one
                    514: 
1.203     brouard   515:   Revision 1.202  2015/09/22 19:45:16  brouard
                    516:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    517: 
1.202     brouard   518:   Revision 1.201  2015/09/15 17:34:58  brouard
                    519:   Summary: 0.98r0
                    520: 
                    521:   - Some new graphs like suvival functions
                    522:   - Some bugs fixed like model=1+age+V2.
                    523: 
1.201     brouard   524:   Revision 1.200  2015/09/09 16:53:55  brouard
                    525:   Summary: Big bug thanks to Flavia
                    526: 
                    527:   Even model=1+age+V2. did not work anymore
                    528: 
1.200     brouard   529:   Revision 1.199  2015/09/07 14:09:23  brouard
                    530:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    531: 
1.199     brouard   532:   Revision 1.198  2015/09/03 07:14:39  brouard
                    533:   Summary: 0.98q5 Flavia
                    534: 
1.198     brouard   535:   Revision 1.197  2015/09/01 18:24:39  brouard
                    536:   *** empty log message ***
                    537: 
1.197     brouard   538:   Revision 1.196  2015/08/18 23:17:52  brouard
                    539:   Summary: 0.98q5
                    540: 
1.196     brouard   541:   Revision 1.195  2015/08/18 16:28:39  brouard
                    542:   Summary: Adding a hack for testing purpose
                    543: 
                    544:   After reading the title, ftol and model lines, if the comment line has
                    545:   a q, starting with #q, the answer at the end of the run is quit. It
                    546:   permits to run test files in batch with ctest. The former workaround was
                    547:   $ echo q | imach foo.imach
                    548: 
1.195     brouard   549:   Revision 1.194  2015/08/18 13:32:00  brouard
                    550:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    551: 
1.194     brouard   552:   Revision 1.193  2015/08/04 07:17:42  brouard
                    553:   Summary: 0.98q4
                    554: 
1.193     brouard   555:   Revision 1.192  2015/07/16 16:49:02  brouard
                    556:   Summary: Fixing some outputs
                    557: 
1.192     brouard   558:   Revision 1.191  2015/07/14 10:00:33  brouard
                    559:   Summary: Some fixes
                    560: 
1.191     brouard   561:   Revision 1.190  2015/05/05 08:51:13  brouard
                    562:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    563: 
                    564:   Fix 1+age+.
                    565: 
1.190     brouard   566:   Revision 1.189  2015/04/30 14:45:16  brouard
                    567:   Summary: 0.98q2
                    568: 
1.189     brouard   569:   Revision 1.188  2015/04/30 08:27:53  brouard
                    570:   *** empty log message ***
                    571: 
1.188     brouard   572:   Revision 1.187  2015/04/29 09:11:15  brouard
                    573:   *** empty log message ***
                    574: 
1.187     brouard   575:   Revision 1.186  2015/04/23 12:01:52  brouard
                    576:   Summary: V1*age is working now, version 0.98q1
                    577: 
                    578:   Some codes had been disabled in order to simplify and Vn*age was
                    579:   working in the optimization phase, ie, giving correct MLE parameters,
                    580:   but, as usual, outputs were not correct and program core dumped.
                    581: 
1.186     brouard   582:   Revision 1.185  2015/03/11 13:26:42  brouard
                    583:   Summary: Inclusion of compile and links command line for Intel Compiler
                    584: 
1.185     brouard   585:   Revision 1.184  2015/03/11 11:52:39  brouard
                    586:   Summary: Back from Windows 8. Intel Compiler
                    587: 
1.184     brouard   588:   Revision 1.183  2015/03/10 20:34:32  brouard
                    589:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    590: 
                    591:   We use directest instead of original Powell test; probably no
                    592:   incidence on the results, but better justifications;
                    593:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    594:   wrong results.
                    595: 
1.183     brouard   596:   Revision 1.182  2015/02/12 08:19:57  brouard
                    597:   Summary: Trying to keep directest which seems simpler and more general
                    598:   Author: Nicolas Brouard
                    599: 
1.182     brouard   600:   Revision 1.181  2015/02/11 23:22:24  brouard
                    601:   Summary: Comments on Powell added
                    602: 
                    603:   Author:
                    604: 
1.181     brouard   605:   Revision 1.180  2015/02/11 17:33:45  brouard
                    606:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    607: 
1.180     brouard   608:   Revision 1.179  2015/01/04 09:57:06  brouard
                    609:   Summary: back to OS/X
                    610: 
1.179     brouard   611:   Revision 1.178  2015/01/04 09:35:48  brouard
                    612:   *** empty log message ***
                    613: 
1.178     brouard   614:   Revision 1.177  2015/01/03 18:40:56  brouard
                    615:   Summary: Still testing ilc32 on OSX
                    616: 
1.177     brouard   617:   Revision 1.176  2015/01/03 16:45:04  brouard
                    618:   *** empty log message ***
                    619: 
1.176     brouard   620:   Revision 1.175  2015/01/03 16:33:42  brouard
                    621:   *** empty log message ***
                    622: 
1.175     brouard   623:   Revision 1.174  2015/01/03 16:15:49  brouard
                    624:   Summary: Still in cross-compilation
                    625: 
1.174     brouard   626:   Revision 1.173  2015/01/03 12:06:26  brouard
                    627:   Summary: trying to detect cross-compilation
                    628: 
1.173     brouard   629:   Revision 1.172  2014/12/27 12:07:47  brouard
                    630:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    631: 
1.172     brouard   632:   Revision 1.171  2014/12/23 13:26:59  brouard
                    633:   Summary: Back from Visual C
                    634: 
                    635:   Still problem with utsname.h on Windows
                    636: 
1.171     brouard   637:   Revision 1.170  2014/12/23 11:17:12  brouard
                    638:   Summary: Cleaning some \%% back to %%
                    639: 
                    640:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    641: 
1.170     brouard   642:   Revision 1.169  2014/12/22 23:08:31  brouard
                    643:   Summary: 0.98p
                    644: 
                    645:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    646: 
1.169     brouard   647:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   648:   Summary: update
1.169     brouard   649: 
1.168     brouard   650:   Revision 1.167  2014/12/22 13:50:56  brouard
                    651:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    652: 
                    653:   Testing on Linux 64
                    654: 
1.167     brouard   655:   Revision 1.166  2014/12/22 11:40:47  brouard
                    656:   *** empty log message ***
                    657: 
1.166     brouard   658:   Revision 1.165  2014/12/16 11:20:36  brouard
                    659:   Summary: After compiling on Visual C
                    660: 
                    661:   * imach.c (Module): Merging 1.61 to 1.162
                    662: 
1.165     brouard   663:   Revision 1.164  2014/12/16 10:52:11  brouard
                    664:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    665: 
                    666:   * imach.c (Module): Merging 1.61 to 1.162
                    667: 
1.164     brouard   668:   Revision 1.163  2014/12/16 10:30:11  brouard
                    669:   * imach.c (Module): Merging 1.61 to 1.162
                    670: 
1.163     brouard   671:   Revision 1.162  2014/09/25 11:43:39  brouard
                    672:   Summary: temporary backup 0.99!
                    673: 
1.162     brouard   674:   Revision 1.1  2014/09/16 11:06:58  brouard
                    675:   Summary: With some code (wrong) for nlopt
                    676: 
                    677:   Author:
                    678: 
                    679:   Revision 1.161  2014/09/15 20:41:41  brouard
                    680:   Summary: Problem with macro SQR on Intel compiler
                    681: 
1.161     brouard   682:   Revision 1.160  2014/09/02 09:24:05  brouard
                    683:   *** empty log message ***
                    684: 
1.160     brouard   685:   Revision 1.159  2014/09/01 10:34:10  brouard
                    686:   Summary: WIN32
                    687:   Author: Brouard
                    688: 
1.159     brouard   689:   Revision 1.158  2014/08/27 17:11:51  brouard
                    690:   *** empty log message ***
                    691: 
1.158     brouard   692:   Revision 1.157  2014/08/27 16:26:55  brouard
                    693:   Summary: Preparing windows Visual studio version
                    694:   Author: Brouard
                    695: 
                    696:   In order to compile on Visual studio, time.h is now correct and time_t
                    697:   and tm struct should be used. difftime should be used but sometimes I
                    698:   just make the differences in raw time format (time(&now).
                    699:   Trying to suppress #ifdef LINUX
                    700:   Add xdg-open for __linux in order to open default browser.
                    701: 
1.157     brouard   702:   Revision 1.156  2014/08/25 20:10:10  brouard
                    703:   *** empty log message ***
                    704: 
1.156     brouard   705:   Revision 1.155  2014/08/25 18:32:34  brouard
                    706:   Summary: New compile, minor changes
                    707:   Author: Brouard
                    708: 
1.155     brouard   709:   Revision 1.154  2014/06/20 17:32:08  brouard
                    710:   Summary: Outputs now all graphs of convergence to period prevalence
                    711: 
1.154     brouard   712:   Revision 1.153  2014/06/20 16:45:46  brouard
                    713:   Summary: If 3 live state, convergence to period prevalence on same graph
                    714:   Author: Brouard
                    715: 
1.153     brouard   716:   Revision 1.152  2014/06/18 17:54:09  brouard
                    717:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    718: 
1.152     brouard   719:   Revision 1.151  2014/06/18 16:43:30  brouard
                    720:   *** empty log message ***
                    721: 
1.151     brouard   722:   Revision 1.150  2014/06/18 16:42:35  brouard
                    723:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    724:   Author: brouard
                    725: 
1.150     brouard   726:   Revision 1.149  2014/06/18 15:51:14  brouard
                    727:   Summary: Some fixes in parameter files errors
                    728:   Author: Nicolas Brouard
                    729: 
1.149     brouard   730:   Revision 1.148  2014/06/17 17:38:48  brouard
                    731:   Summary: Nothing new
                    732:   Author: Brouard
                    733: 
                    734:   Just a new packaging for OS/X version 0.98nS
                    735: 
1.148     brouard   736:   Revision 1.147  2014/06/16 10:33:11  brouard
                    737:   *** empty log message ***
                    738: 
1.147     brouard   739:   Revision 1.146  2014/06/16 10:20:28  brouard
                    740:   Summary: Merge
                    741:   Author: Brouard
                    742: 
                    743:   Merge, before building revised version.
                    744: 
1.146     brouard   745:   Revision 1.145  2014/06/10 21:23:15  brouard
                    746:   Summary: Debugging with valgrind
                    747:   Author: Nicolas Brouard
                    748: 
                    749:   Lot of changes in order to output the results with some covariates
                    750:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    751:   improve the code.
                    752:   No more memory valgrind error but a lot has to be done in order to
                    753:   continue the work of splitting the code into subroutines.
                    754:   Also, decodemodel has been improved. Tricode is still not
                    755:   optimal. nbcode should be improved. Documentation has been added in
                    756:   the source code.
                    757: 
1.144     brouard   758:   Revision 1.143  2014/01/26 09:45:38  brouard
                    759:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    760: 
                    761:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    762:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    763: 
1.143     brouard   764:   Revision 1.142  2014/01/26 03:57:36  brouard
                    765:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    766: 
                    767:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    768: 
1.142     brouard   769:   Revision 1.141  2014/01/26 02:42:01  brouard
                    770:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    771: 
1.141     brouard   772:   Revision 1.140  2011/09/02 10:37:54  brouard
                    773:   Summary: times.h is ok with mingw32 now.
                    774: 
1.140     brouard   775:   Revision 1.139  2010/06/14 07:50:17  brouard
                    776:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    777:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    778: 
1.139     brouard   779:   Revision 1.138  2010/04/30 18:19:40  brouard
                    780:   *** empty log message ***
                    781: 
1.138     brouard   782:   Revision 1.137  2010/04/29 18:11:38  brouard
                    783:   (Module): Checking covariates for more complex models
                    784:   than V1+V2. A lot of change to be done. Unstable.
                    785: 
1.137     brouard   786:   Revision 1.136  2010/04/26 20:30:53  brouard
                    787:   (Module): merging some libgsl code. Fixing computation
                    788:   of likelione (using inter/intrapolation if mle = 0) in order to
                    789:   get same likelihood as if mle=1.
                    790:   Some cleaning of code and comments added.
                    791: 
1.136     brouard   792:   Revision 1.135  2009/10/29 15:33:14  brouard
                    793:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    794: 
1.135     brouard   795:   Revision 1.134  2009/10/29 13:18:53  brouard
                    796:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    797: 
1.134     brouard   798:   Revision 1.133  2009/07/06 10:21:25  brouard
                    799:   just nforces
                    800: 
1.133     brouard   801:   Revision 1.132  2009/07/06 08:22:05  brouard
                    802:   Many tings
                    803: 
1.132     brouard   804:   Revision 1.131  2009/06/20 16:22:47  brouard
                    805:   Some dimensions resccaled
                    806: 
1.131     brouard   807:   Revision 1.130  2009/05/26 06:44:34  brouard
                    808:   (Module): Max Covariate is now set to 20 instead of 8. A
                    809:   lot of cleaning with variables initialized to 0. Trying to make
                    810:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    811: 
1.130     brouard   812:   Revision 1.129  2007/08/31 13:49:27  lievre
                    813:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    814: 
1.129     lievre    815:   Revision 1.128  2006/06/30 13:02:05  brouard
                    816:   (Module): Clarifications on computing e.j
                    817: 
1.128     brouard   818:   Revision 1.127  2006/04/28 18:11:50  brouard
                    819:   (Module): Yes the sum of survivors was wrong since
                    820:   imach-114 because nhstepm was no more computed in the age
                    821:   loop. Now we define nhstepma in the age loop.
                    822:   (Module): In order to speed up (in case of numerous covariates) we
                    823:   compute health expectancies (without variances) in a first step
                    824:   and then all the health expectancies with variances or standard
                    825:   deviation (needs data from the Hessian matrices) which slows the
                    826:   computation.
                    827:   In the future we should be able to stop the program is only health
                    828:   expectancies and graph are needed without standard deviations.
                    829: 
1.127     brouard   830:   Revision 1.126  2006/04/28 17:23:28  brouard
                    831:   (Module): Yes the sum of survivors was wrong since
                    832:   imach-114 because nhstepm was no more computed in the age
                    833:   loop. Now we define nhstepma in the age loop.
                    834:   Version 0.98h
                    835: 
1.126     brouard   836:   Revision 1.125  2006/04/04 15:20:31  lievre
                    837:   Errors in calculation of health expectancies. Age was not initialized.
                    838:   Forecasting file added.
                    839: 
                    840:   Revision 1.124  2006/03/22 17:13:53  lievre
                    841:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    842:   The log-likelihood is printed in the log file
                    843: 
                    844:   Revision 1.123  2006/03/20 10:52:43  brouard
                    845:   * imach.c (Module): <title> changed, corresponds to .htm file
                    846:   name. <head> headers where missing.
                    847: 
                    848:   * imach.c (Module): Weights can have a decimal point as for
                    849:   English (a comma might work with a correct LC_NUMERIC environment,
                    850:   otherwise the weight is truncated).
                    851:   Modification of warning when the covariates values are not 0 or
                    852:   1.
                    853:   Version 0.98g
                    854: 
                    855:   Revision 1.122  2006/03/20 09:45:41  brouard
                    856:   (Module): Weights can have a decimal point as for
                    857:   English (a comma might work with a correct LC_NUMERIC environment,
                    858:   otherwise the weight is truncated).
                    859:   Modification of warning when the covariates values are not 0 or
                    860:   1.
                    861:   Version 0.98g
                    862: 
                    863:   Revision 1.121  2006/03/16 17:45:01  lievre
                    864:   * imach.c (Module): Comments concerning covariates added
                    865: 
                    866:   * imach.c (Module): refinements in the computation of lli if
                    867:   status=-2 in order to have more reliable computation if stepm is
                    868:   not 1 month. Version 0.98f
                    869: 
                    870:   Revision 1.120  2006/03/16 15:10:38  lievre
                    871:   (Module): refinements in the computation of lli if
                    872:   status=-2 in order to have more reliable computation if stepm is
                    873:   not 1 month. Version 0.98f
                    874: 
                    875:   Revision 1.119  2006/03/15 17:42:26  brouard
                    876:   (Module): Bug if status = -2, the loglikelihood was
                    877:   computed as likelihood omitting the logarithm. Version O.98e
                    878: 
                    879:   Revision 1.118  2006/03/14 18:20:07  brouard
                    880:   (Module): varevsij Comments added explaining the second
                    881:   table of variances if popbased=1 .
                    882:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    883:   (Module): Function pstamp added
                    884:   (Module): Version 0.98d
                    885: 
                    886:   Revision 1.117  2006/03/14 17:16:22  brouard
                    887:   (Module): varevsij Comments added explaining the second
                    888:   table of variances if popbased=1 .
                    889:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    890:   (Module): Function pstamp added
                    891:   (Module): Version 0.98d
                    892: 
                    893:   Revision 1.116  2006/03/06 10:29:27  brouard
                    894:   (Module): Variance-covariance wrong links and
                    895:   varian-covariance of ej. is needed (Saito).
                    896: 
                    897:   Revision 1.115  2006/02/27 12:17:45  brouard
                    898:   (Module): One freematrix added in mlikeli! 0.98c
                    899: 
                    900:   Revision 1.114  2006/02/26 12:57:58  brouard
                    901:   (Module): Some improvements in processing parameter
                    902:   filename with strsep.
                    903: 
                    904:   Revision 1.113  2006/02/24 14:20:24  brouard
                    905:   (Module): Memory leaks checks with valgrind and:
                    906:   datafile was not closed, some imatrix were not freed and on matrix
                    907:   allocation too.
                    908: 
                    909:   Revision 1.112  2006/01/30 09:55:26  brouard
                    910:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    911: 
                    912:   Revision 1.111  2006/01/25 20:38:18  brouard
                    913:   (Module): Lots of cleaning and bugs added (Gompertz)
                    914:   (Module): Comments can be added in data file. Missing date values
                    915:   can be a simple dot '.'.
                    916: 
                    917:   Revision 1.110  2006/01/25 00:51:50  brouard
                    918:   (Module): Lots of cleaning and bugs added (Gompertz)
                    919: 
                    920:   Revision 1.109  2006/01/24 19:37:15  brouard
                    921:   (Module): Comments (lines starting with a #) are allowed in data.
                    922: 
                    923:   Revision 1.108  2006/01/19 18:05:42  lievre
                    924:   Gnuplot problem appeared...
                    925:   To be fixed
                    926: 
                    927:   Revision 1.107  2006/01/19 16:20:37  brouard
                    928:   Test existence of gnuplot in imach path
                    929: 
                    930:   Revision 1.106  2006/01/19 13:24:36  brouard
                    931:   Some cleaning and links added in html output
                    932: 
                    933:   Revision 1.105  2006/01/05 20:23:19  lievre
                    934:   *** empty log message ***
                    935: 
                    936:   Revision 1.104  2005/09/30 16:11:43  lievre
                    937:   (Module): sump fixed, loop imx fixed, and simplifications.
                    938:   (Module): If the status is missing at the last wave but we know
                    939:   that the person is alive, then we can code his/her status as -2
                    940:   (instead of missing=-1 in earlier versions) and his/her
                    941:   contributions to the likelihood is 1 - Prob of dying from last
                    942:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    943:   the healthy state at last known wave). Version is 0.98
                    944: 
                    945:   Revision 1.103  2005/09/30 15:54:49  lievre
                    946:   (Module): sump fixed, loop imx fixed, and simplifications.
                    947: 
                    948:   Revision 1.102  2004/09/15 17:31:30  brouard
                    949:   Add the possibility to read data file including tab characters.
                    950: 
                    951:   Revision 1.101  2004/09/15 10:38:38  brouard
                    952:   Fix on curr_time
                    953: 
                    954:   Revision 1.100  2004/07/12 18:29:06  brouard
                    955:   Add version for Mac OS X. Just define UNIX in Makefile
                    956: 
                    957:   Revision 1.99  2004/06/05 08:57:40  brouard
                    958:   *** empty log message ***
                    959: 
                    960:   Revision 1.98  2004/05/16 15:05:56  brouard
                    961:   New version 0.97 . First attempt to estimate force of mortality
                    962:   directly from the data i.e. without the need of knowing the health
                    963:   state at each age, but using a Gompertz model: log u =a + b*age .
                    964:   This is the basic analysis of mortality and should be done before any
                    965:   other analysis, in order to test if the mortality estimated from the
                    966:   cross-longitudinal survey is different from the mortality estimated
                    967:   from other sources like vital statistic data.
                    968: 
                    969:   The same imach parameter file can be used but the option for mle should be -3.
                    970: 
1.324     brouard   971:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   972:   former routines in order to include the new code within the former code.
                    973: 
                    974:   The output is very simple: only an estimate of the intercept and of
                    975:   the slope with 95% confident intervals.
                    976: 
                    977:   Current limitations:
                    978:   A) Even if you enter covariates, i.e. with the
                    979:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    980:   B) There is no computation of Life Expectancy nor Life Table.
                    981: 
                    982:   Revision 1.97  2004/02/20 13:25:42  lievre
                    983:   Version 0.96d. Population forecasting command line is (temporarily)
                    984:   suppressed.
                    985: 
                    986:   Revision 1.96  2003/07/15 15:38:55  brouard
                    987:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    988:   rewritten within the same printf. Workaround: many printfs.
                    989: 
                    990:   Revision 1.95  2003/07/08 07:54:34  brouard
                    991:   * imach.c (Repository):
                    992:   (Repository): Using imachwizard code to output a more meaningful covariance
                    993:   matrix (cov(a12,c31) instead of numbers.
                    994: 
                    995:   Revision 1.94  2003/06/27 13:00:02  brouard
                    996:   Just cleaning
                    997: 
                    998:   Revision 1.93  2003/06/25 16:33:55  brouard
                    999:   (Module): On windows (cygwin) function asctime_r doesn't
                   1000:   exist so I changed back to asctime which exists.
                   1001:   (Module): Version 0.96b
                   1002: 
                   1003:   Revision 1.92  2003/06/25 16:30:45  brouard
                   1004:   (Module): On windows (cygwin) function asctime_r doesn't
                   1005:   exist so I changed back to asctime which exists.
                   1006: 
                   1007:   Revision 1.91  2003/06/25 15:30:29  brouard
                   1008:   * imach.c (Repository): Duplicated warning errors corrected.
                   1009:   (Repository): Elapsed time after each iteration is now output. It
                   1010:   helps to forecast when convergence will be reached. Elapsed time
                   1011:   is stamped in powell.  We created a new html file for the graphs
                   1012:   concerning matrix of covariance. It has extension -cov.htm.
                   1013: 
                   1014:   Revision 1.90  2003/06/24 12:34:15  brouard
                   1015:   (Module): Some bugs corrected for windows. Also, when
                   1016:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1017:   of the covariance matrix to be input.
                   1018: 
                   1019:   Revision 1.89  2003/06/24 12:30:52  brouard
                   1020:   (Module): Some bugs corrected for windows. Also, when
                   1021:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1022:   of the covariance matrix to be input.
                   1023: 
                   1024:   Revision 1.88  2003/06/23 17:54:56  brouard
                   1025:   * 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.
                   1026: 
                   1027:   Revision 1.87  2003/06/18 12:26:01  brouard
                   1028:   Version 0.96
                   1029: 
                   1030:   Revision 1.86  2003/06/17 20:04:08  brouard
                   1031:   (Module): Change position of html and gnuplot routines and added
                   1032:   routine fileappend.
                   1033: 
                   1034:   Revision 1.85  2003/06/17 13:12:43  brouard
                   1035:   * imach.c (Repository): Check when date of death was earlier that
                   1036:   current date of interview. It may happen when the death was just
                   1037:   prior to the death. In this case, dh was negative and likelihood
                   1038:   was wrong (infinity). We still send an "Error" but patch by
                   1039:   assuming that the date of death was just one stepm after the
                   1040:   interview.
                   1041:   (Repository): Because some people have very long ID (first column)
                   1042:   we changed int to long in num[] and we added a new lvector for
                   1043:   memory allocation. But we also truncated to 8 characters (left
                   1044:   truncation)
                   1045:   (Repository): No more line truncation errors.
                   1046: 
                   1047:   Revision 1.84  2003/06/13 21:44:43  brouard
                   1048:   * imach.c (Repository): Replace "freqsummary" at a correct
                   1049:   place. It differs from routine "prevalence" which may be called
                   1050:   many times. Probs is memory consuming and must be used with
                   1051:   parcimony.
                   1052:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                   1053: 
                   1054:   Revision 1.83  2003/06/10 13:39:11  lievre
                   1055:   *** empty log message ***
                   1056: 
                   1057:   Revision 1.82  2003/06/05 15:57:20  brouard
                   1058:   Add log in  imach.c and  fullversion number is now printed.
                   1059: 
                   1060: */
                   1061: /*
                   1062:    Interpolated Markov Chain
                   1063: 
                   1064:   Short summary of the programme:
                   1065:   
1.227     brouard  1066:   This program computes Healthy Life Expectancies or State-specific
                   1067:   (if states aren't health statuses) Expectancies from
                   1068:   cross-longitudinal data. Cross-longitudinal data consist in: 
                   1069: 
                   1070:   -1- a first survey ("cross") where individuals from different ages
                   1071:   are interviewed on their health status or degree of disability (in
                   1072:   the case of a health survey which is our main interest)
                   1073: 
                   1074:   -2- at least a second wave of interviews ("longitudinal") which
                   1075:   measure each change (if any) in individual health status.  Health
                   1076:   expectancies are computed from the time spent in each health state
                   1077:   according to a model. More health states you consider, more time is
                   1078:   necessary to reach the Maximum Likelihood of the parameters involved
                   1079:   in the model.  The simplest model is the multinomial logistic model
                   1080:   where pij is the probability to be observed in state j at the second
                   1081:   wave conditional to be observed in state i at the first
                   1082:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                   1083:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                   1084:   have a more complex model than "constant and age", you should modify
                   1085:   the program where the markup *Covariates have to be included here
                   1086:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard  1087:   convergence.
                   1088: 
                   1089:   The advantage of this computer programme, compared to a simple
                   1090:   multinomial logistic model, is clear when the delay between waves is not
                   1091:   identical for each individual. Also, if a individual missed an
                   1092:   intermediate interview, the information is lost, but taken into
                   1093:   account using an interpolation or extrapolation.  
                   1094: 
                   1095:   hPijx is the probability to be observed in state i at age x+h
                   1096:   conditional to the observed state i at age x. The delay 'h' can be
                   1097:   split into an exact number (nh*stepm) of unobserved intermediate
                   1098:   states. This elementary transition (by month, quarter,
                   1099:   semester or year) is modelled as a multinomial logistic.  The hPx
                   1100:   matrix is simply the matrix product of nh*stepm elementary matrices
                   1101:   and the contribution of each individual to the likelihood is simply
                   1102:   hPijx.
                   1103: 
                   1104:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard  1105:   of the life expectancies. It also computes the period (stable) prevalence.
                   1106: 
                   1107: Back prevalence and projections:
1.227     brouard  1108: 
                   1109:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                   1110:    double agemaxpar, double ftolpl, int *ncvyearp, double
                   1111:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                   1112:    mobilavproj)
                   1113: 
                   1114:     Computes the back prevalence limit for any combination of
                   1115:     covariate values k at any age between ageminpar and agemaxpar and
                   1116:     returns it in **bprlim. In the loops,
                   1117: 
                   1118:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                   1119:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                   1120: 
                   1121:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard  1122:    Computes for any combination of covariates k and any age between bage and fage 
                   1123:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1124:                        oldm=oldms;savm=savms;
1.227     brouard  1125: 
1.267     brouard  1126:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard  1127:      Computes the transition matrix starting at age 'age' over
                   1128:      'nhstepm*hstepm*stepm' months (i.e. until
                   1129:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard  1130:      nhstepm*hstepm matrices. 
                   1131: 
                   1132:      Returns p3mat[i][j][h] after calling
                   1133:      p3mat[i][j][h]=matprod2(newm,
                   1134:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                   1135:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                   1136:      oldm);
1.226     brouard  1137: 
                   1138: Important routines
                   1139: 
                   1140: - func (or funcone), computes logit (pij) distinguishing
                   1141:   o fixed variables (single or product dummies or quantitative);
                   1142:   o varying variables by:
                   1143:    (1) wave (single, product dummies, quantitative), 
                   1144:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                   1145:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                   1146:        % varying dummy (not done) or quantitative (not done);
                   1147: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                   1148:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                   1149: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
1.325     brouard  1150:   o There are 2**cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
1.226     brouard  1151:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard  1152: 
1.226     brouard  1153: 
                   1154:   
1.324     brouard  1155:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                   1156:            Institut national d'études démographiques, Paris.
1.126     brouard  1157:   This software have been partly granted by Euro-REVES, a concerted action
                   1158:   from the European Union.
                   1159:   It is copyrighted identically to a GNU software product, ie programme and
                   1160:   software can be distributed freely for non commercial use. Latest version
                   1161:   can be accessed at http://euroreves.ined.fr/imach .
                   1162: 
                   1163:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                   1164:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                   1165:   
                   1166:   **********************************************************************/
                   1167: /*
                   1168:   main
                   1169:   read parameterfile
                   1170:   read datafile
                   1171:   concatwav
                   1172:   freqsummary
                   1173:   if (mle >= 1)
                   1174:     mlikeli
                   1175:   print results files
                   1176:   if mle==1 
                   1177:      computes hessian
                   1178:   read end of parameter file: agemin, agemax, bage, fage, estepm
                   1179:       begin-prev-date,...
                   1180:   open gnuplot file
                   1181:   open html file
1.145     brouard  1182:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1183:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1184:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1185:     freexexit2 possible for memory heap.
                   1186: 
                   1187:   h Pij x                         | pij_nom  ficrestpij
                   1188:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1189:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1190:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1191: 
                   1192:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1193:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1194:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1195:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1196:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1197: 
1.126     brouard  1198:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1199:   health expectancies
                   1200:   Variance-covariance of DFLE
                   1201:   prevalence()
                   1202:    movingaverage()
                   1203:   varevsij() 
                   1204:   if popbased==1 varevsij(,popbased)
                   1205:   total life expectancies
                   1206:   Variance of period (stable) prevalence
                   1207:  end
                   1208: */
                   1209: 
1.187     brouard  1210: /* #define DEBUG */
                   1211: /* #define DEBUGBRENT */
1.203     brouard  1212: /* #define DEBUGLINMIN */
                   1213: /* #define DEBUGHESS */
                   1214: #define DEBUGHESSIJ
1.224     brouard  1215: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1216: #define POWELL /* Instead of NLOPT */
1.224     brouard  1217: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1218: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1219: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.319     brouard  1220: /* #define FLATSUP  *//* Suppresses directions where likelihood is flat */
1.126     brouard  1221: 
                   1222: #include <math.h>
                   1223: #include <stdio.h>
                   1224: #include <stdlib.h>
                   1225: #include <string.h>
1.226     brouard  1226: #include <ctype.h>
1.159     brouard  1227: 
                   1228: #ifdef _WIN32
                   1229: #include <io.h>
1.172     brouard  1230: #include <windows.h>
                   1231: #include <tchar.h>
1.159     brouard  1232: #else
1.126     brouard  1233: #include <unistd.h>
1.159     brouard  1234: #endif
1.126     brouard  1235: 
                   1236: #include <limits.h>
                   1237: #include <sys/types.h>
1.171     brouard  1238: 
                   1239: #if defined(__GNUC__)
                   1240: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1241: #endif
                   1242: 
1.126     brouard  1243: #include <sys/stat.h>
                   1244: #include <errno.h>
1.159     brouard  1245: /* extern int errno; */
1.126     brouard  1246: 
1.157     brouard  1247: /* #ifdef LINUX */
                   1248: /* #include <time.h> */
                   1249: /* #include "timeval.h" */
                   1250: /* #else */
                   1251: /* #include <sys/time.h> */
                   1252: /* #endif */
                   1253: 
1.126     brouard  1254: #include <time.h>
                   1255: 
1.136     brouard  1256: #ifdef GSL
                   1257: #include <gsl/gsl_errno.h>
                   1258: #include <gsl/gsl_multimin.h>
                   1259: #endif
                   1260: 
1.167     brouard  1261: 
1.162     brouard  1262: #ifdef NLOPT
                   1263: #include <nlopt.h>
                   1264: typedef struct {
                   1265:   double (* function)(double [] );
                   1266: } myfunc_data ;
                   1267: #endif
                   1268: 
1.126     brouard  1269: /* #include <libintl.h> */
                   1270: /* #define _(String) gettext (String) */
                   1271: 
1.251     brouard  1272: #define MAXLINE 2048 /* Was 256 and 1024. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1273: 
                   1274: #define GNUPLOTPROGRAM "gnuplot"
                   1275: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
1.329     brouard  1276: #define FILENAMELENGTH 256
1.126     brouard  1277: 
                   1278: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1279: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1280: 
1.144     brouard  1281: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                   1282: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1283: 
                   1284: #define NINTERVMAX 8
1.144     brouard  1285: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1286: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.325     brouard  1287: #define NCOVMAX 30  /**< Maximum number of covariates used in the model, including generated covariates V1*V2 or V1*age */
1.197     brouard  1288: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1289: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1290: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1291: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1292: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1293: /* #define AGESUP 130 */
1.288     brouard  1294: /* #define AGESUP 150 */
                   1295: #define AGESUP 200
1.268     brouard  1296: #define AGEINF 0
1.218     brouard  1297: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1298: #define AGEBASE 40
1.194     brouard  1299: #define AGEOVERFLOW 1.e20
1.164     brouard  1300: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1301: #ifdef _WIN32
                   1302: #define DIRSEPARATOR '\\'
                   1303: #define CHARSEPARATOR "\\"
                   1304: #define ODIRSEPARATOR '/'
                   1305: #else
1.126     brouard  1306: #define DIRSEPARATOR '/'
                   1307: #define CHARSEPARATOR "/"
                   1308: #define ODIRSEPARATOR '\\'
                   1309: #endif
                   1310: 
1.340   ! brouard  1311: /* $Id: imach.c,v 1.339 2022/09/09 17:55:22 brouard Exp $ */
1.126     brouard  1312: /* $State: Exp $ */
1.196     brouard  1313: #include "version.h"
                   1314: char version[]=__IMACH_VERSION__;
1.337     brouard  1315: char copyright[]="September 2022,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015-2020, Nihon University 2021-202, INED 2000-2022";
1.340   ! brouard  1316: char fullversion[]="$Revision: 1.339 $ $Date: 2022/09/09 17:55:22 $"; 
1.126     brouard  1317: char strstart[80];
                   1318: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1319: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard  1320: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.330     brouard  1321: /* Number of covariates model (1)=V2+V1+ V3*age+V2*V4 */
                   1322: /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
1.335     brouard  1323: 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  1324: 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  1325: int cptcovs=0; /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   1326: int cptcovsnq=0; /**< cptcovsnq number of SIMPLE covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1327: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                   1328: int cptcovprodnoage=0; /**< Number of covariate products without age */   
1.335     brouard  1329: 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  1330: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1331: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.339     brouard  1332: int ncovvt=0; /* Total number of effective (wave) varying covariates (dummy or quantitative or products [without age]) in the model */
1.232     brouard  1333: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
1.234     brouard  1334: int nsd=0; /**< Total number of single dummy variables (output) */
                   1335: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1336: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1337: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1338: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1339: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1340: int cptcov=0; /* Working variable */
1.334     brouard  1341: int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs+1 declared globally ;*/
1.290     brouard  1342: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1343: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.302     brouard  1344: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
1.126     brouard  1345: int nlstate=2; /* Number of live states */
                   1346: int ndeath=1; /* Number of dead states */
1.130     brouard  1347: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.339     brouard  1348: int nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable*/
                   1349: int ncovcolt=0; /* ncovcolt=ncovcol+nqv+ntv+nqtv; total of covariates in the data, not in the model equation*/ 
1.126     brouard  1350: int popbased=0;
                   1351: 
                   1352: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1353: int maxwav=0; /* Maxim number of waves */
                   1354: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1355: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1356: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard  1357:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1358: int mle=1, weightopt=0;
1.126     brouard  1359: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1360: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1361: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1362:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1363: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1364: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1365: 
1.130     brouard  1366: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1367: double **matprod2(); /* test */
1.126     brouard  1368: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1369: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1370: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1371: 
1.136     brouard  1372: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1373: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1374: FILE *ficlog, *ficrespow;
1.130     brouard  1375: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1376: double fretone; /* Only one call to likelihood */
1.130     brouard  1377: long ipmx=0; /* Number of contributions */
1.126     brouard  1378: double sw; /* Sum of weights */
                   1379: char filerespow[FILENAMELENGTH];
                   1380: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1381: FILE *ficresilk;
                   1382: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1383: FILE *ficresprobmorprev;
                   1384: FILE *fichtm, *fichtmcov; /* Html File */
                   1385: FILE *ficreseij;
                   1386: char filerese[FILENAMELENGTH];
                   1387: FILE *ficresstdeij;
                   1388: char fileresstde[FILENAMELENGTH];
                   1389: FILE *ficrescveij;
                   1390: char filerescve[FILENAMELENGTH];
                   1391: FILE  *ficresvij;
                   1392: char fileresv[FILENAMELENGTH];
1.269     brouard  1393: 
1.126     brouard  1394: char title[MAXLINE];
1.234     brouard  1395: char model[MAXLINE]; /**< The model line */
1.217     brouard  1396: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1397: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1398: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1399: char command[FILENAMELENGTH];
                   1400: int  outcmd=0;
                   1401: 
1.217     brouard  1402: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1403: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1404: char filelog[FILENAMELENGTH]; /* Log file */
                   1405: char filerest[FILENAMELENGTH];
                   1406: char fileregp[FILENAMELENGTH];
                   1407: char popfile[FILENAMELENGTH];
                   1408: 
                   1409: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1410: 
1.157     brouard  1411: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1412: /* struct timezone tzp; */
                   1413: /* extern int gettimeofday(); */
                   1414: struct tm tml, *gmtime(), *localtime();
                   1415: 
                   1416: extern time_t time();
                   1417: 
                   1418: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1419: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                   1420: struct tm tm;
                   1421: 
1.126     brouard  1422: char strcurr[80], strfor[80];
                   1423: 
                   1424: char *endptr;
                   1425: long lval;
                   1426: double dval;
                   1427: 
                   1428: #define NR_END 1
                   1429: #define FREE_ARG char*
                   1430: #define FTOL 1.0e-10
                   1431: 
                   1432: #define NRANSI 
1.240     brouard  1433: #define ITMAX 200
                   1434: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1435: 
                   1436: #define TOL 2.0e-4 
                   1437: 
                   1438: #define CGOLD 0.3819660 
                   1439: #define ZEPS 1.0e-10 
                   1440: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1441: 
                   1442: #define GOLD 1.618034 
                   1443: #define GLIMIT 100.0 
                   1444: #define TINY 1.0e-20 
                   1445: 
                   1446: static double maxarg1,maxarg2;
                   1447: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1448: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1449:   
                   1450: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1451: #define rint(a) floor(a+0.5)
1.166     brouard  1452: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1453: #define mytinydouble 1.0e-16
1.166     brouard  1454: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1455: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1456: /* static double dsqrarg; */
                   1457: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1458: static double sqrarg;
                   1459: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1460: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1461: int agegomp= AGEGOMP;
                   1462: 
                   1463: int imx; 
                   1464: int stepm=1;
                   1465: /* Stepm, step in month: minimum step interpolation*/
                   1466: 
                   1467: int estepm;
                   1468: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1469: 
                   1470: int m,nb;
                   1471: long *num;
1.197     brouard  1472: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1473: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1474:                   covariate for which somebody answered excluding 
                   1475:                   undefined. Usually 2: 0 and 1. */
                   1476: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1477:                             covariate for which somebody answered including 
                   1478:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1479: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1480: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1481: double ***mobaverage, ***mobaverages; /* New global variable */
1.332     brouard  1482: 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  1483: double *ageexmed,*agecens;
                   1484: double dateintmean=0;
1.296     brouard  1485:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1486:   double anprojf, mprojf, jprojf;
1.126     brouard  1487: 
1.296     brouard  1488:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1489:   double anbackf, mbackf, jbackf;
                   1490:   double jintmean,mintmean,aintmean;  
1.126     brouard  1491: double *weight;
                   1492: int **s; /* Status */
1.141     brouard  1493: double *agedc;
1.145     brouard  1494: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1495:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1496:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1497: double **coqvar; /* Fixed quantitative covariate nqv */
                   1498: double ***cotvar; /* Time varying covariate ntv */
1.225     brouard  1499: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1500: double  idx; 
                   1501: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.319     brouard  1502: /* Some documentation */
                   1503:       /*   Design original data
                   1504:        *  V1   V2   V3   V4  V5  V6  V7  V8  Weight ddb ddth d1st s1 V9 V10 V11 V12 s2 V9 V10 V11 V12 
                   1505:        *  <          ncovcol=6   >   nqv=2 (V7 V8)                   dv dv  dv  qtv    dv dv  dvv qtv
                   1506:        *                                                             ntv=3     nqtv=1
1.330     brouard  1507:        *  cptcovn number of covariates (not including constant and age or age*age) = number of plus sign + 1 = 10+1=11
1.319     brouard  1508:        * For time varying covariate, quanti or dummies
                   1509:        *       cotqvar[wav][iv(1 to nqtv)][i]= [1][12][i]=(V12) quanti
                   1510:        *       cotvar[wav][ntv+iv][i]= [3+(1 to nqtv)][i]=(V12) quanti
                   1511:        *       cotvar[wav][iv(1 to ntv)][i]= [1][1][i]=(V9) dummies at wav 1
                   1512:        *       cotvar[wav][iv(1 to ntv)][i]= [1][2][i]=(V10) dummies at wav 1
1.332     brouard  1513:        *       covar[Vk,i], value of the Vkth fixed covariate dummy or quanti for individual i:
1.319     brouard  1514:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   1515:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 + V9 + V9*age + V10
                   1516:        *   k=  1    2      3       4     5       6      7        8   9     10       11 
                   1517:        */
                   1518: /* According to the model, more columns can be added to covar by the product of covariates */
1.318     brouard  1519: /* 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
                   1520:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1521:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1522: */
1.319     brouard  1523: /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1524: /*    k        1  2   3   4     5    6    7     8    9 */
                   1525: /*Typevar[k]=  0  0   0   2     1    0    2     1    0 *//*0 for simple covariate (dummy, quantitative,*/
                   1526:                                                          /* fixed or varying), 1 for age product, 2 for*/
                   1527:                                                          /* product */
                   1528: /*Dummy[k]=    1  0   0   1     3    1    1     2    0 *//*Dummy[k] 0=dummy (0 1), 1 quantitative */
                   1529:                                                          /*(single or product without age), 2 dummy*/
                   1530:                                                          /* with age product, 3 quant with age product*/
                   1531: /*Tvar[k]=     5  4   3   6     5    2    7     1    1 */
                   1532: /*    nsd         1   2                              3 */ /* Counting single dummies covar fixed or tv */
1.330     brouard  1533: /*TnsdVar[Tvar]   1   2                              3 */ 
1.337     brouard  1534: /*Tvaraff[nsd]     4   3                              1 */ /* ID of single dummy cova fixed or timevary*/
1.319     brouard  1535: /*TvarsD[nsd]     4   3                              1 */ /* ID of single dummy cova fixed or timevary*/
1.338     brouard  1536: /*TvarsDind[nsd]  2   3                              9 */ /* position K of single dummy cova */
1.319     brouard  1537: /*    nsq      1                     2                 */ /* Counting single quantit tv */
                   1538: /* TvarsQ[k]   5                     2                 */ /* Number of single quantitative cova */
                   1539: /* TvarsQind   1                     6                 */ /* position K of single quantitative cova */
                   1540: /* Tprod[i]=k             1               2            */ /* Position in model of the ith prod without age */
                   1541: /* cptcovage                    1               2      */ /* Counting cov*age in the model equation */
                   1542: /* Tage[cptcovage]=k            5               8      */ /* Position in the model of ith cov*age */
                   1543: /* Tvard[1][1]@4={4,3,1,2}    V4*V3 V1*V2              */ /* Position in model of the ith prod without age */
1.330     brouard  1544: /* 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  1545: /* 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  1546: /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.234     brouard  1547: /* Type                    */
                   1548: /* V         1  2  3  4  5 */
                   1549: /*           F  F  V  V  V */
                   1550: /*           D  Q  D  D  Q */
                   1551: /*                         */
                   1552: int *TvarsD;
1.330     brouard  1553: int *TnsdVar;
1.234     brouard  1554: int *TvarsDind;
                   1555: int *TvarsQ;
                   1556: int *TvarsQind;
                   1557: 
1.318     brouard  1558: #define MAXRESULTLINESPONE 10+1
1.235     brouard  1559: int nresult=0;
1.258     brouard  1560: int parameterline=0; /* # of the parameter (type) line */
1.334     brouard  1561: int TKresult[MAXRESULTLINESPONE]; /* TKresult[nres]=k for each resultline nres give the corresponding combination of dummies */
                   1562: int resultmodel[MAXRESULTLINESPONE][NCOVMAX];/* resultmodel[k1]=k3: k1th position in the model corresponds to the k3 position in the resultline */
                   1563: int modelresult[MAXRESULTLINESPONE][NCOVMAX];/* modelresult[k3]=k1: k1th position in the model corresponds to the k3 position in the resultline */
                   1564: int Tresult[MAXRESULTLINESPONE][NCOVMAX];/* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1565: int Tinvresult[MAXRESULTLINESPONE][NCOVMAX];/* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line  */
                   1566: double TinvDoQresult[MAXRESULTLINESPONE][NCOVMAX];/* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line */
1.334     brouard  1567: int Tvresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1568: double Tqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
1.318     brouard  1569: double Tqinvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
1.332     brouard  1570: int Tvqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline */
1.318     brouard  1571: 
                   1572: /* 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
                   1573:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1574:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1575: */
1.234     brouard  1576: /* 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  1577: 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 */
                   1578: 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 */
                   1579: 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 */
                   1580: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1581: 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 */
                   1582: 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  1583: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1584: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1585: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1586: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1587: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1588: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1589: 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 */
                   1590: 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  1591: int *TvarVV; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1592: int *TvarVVind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1593:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   1594:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   1595:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   1596:       /* TvarVV={3,1,3}, for V3 and then the product V1*V3 is decomposed into V1 and V3 */            
                   1597:       /* TvarVVind={2,5,5}, for V3 and then the product V1*V3 is decomposed into V1 and V3 */         
1.230     brouard  1598: int *Tvarsel; /**< Selected covariates for output */
                   1599: double *Tvalsel; /**< Selected modality value of covariate for output */
1.226     brouard  1600: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.227     brouard  1601: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1602: 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  1603: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1604: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1605: int *Tage;
1.227     brouard  1606: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1607: 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  1608: 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*/ 
                   1609: 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  1610: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1611: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1612: int **Tvard;
1.330     brouard  1613: int **Tvardk;
1.227     brouard  1614: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1615: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1616: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1617:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1618:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1619: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1620: double *lsurv, *lpop, *tpop;
                   1621: 
1.231     brouard  1622: #define FD 1; /* Fixed dummy covariate */
                   1623: #define FQ 2; /* Fixed quantitative covariate */
                   1624: #define FP 3; /* Fixed product covariate */
                   1625: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1626: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1627: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1628: #define VD 10; /* Varying dummy covariate */
                   1629: #define VQ 11; /* Varying quantitative covariate */
                   1630: #define VP 12; /* Varying product covariate */
                   1631: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1632: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1633: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1634: #define APFD 16; /* Age product * fixed dummy covariate */
                   1635: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1636: #define APVD 18; /* Age product * varying dummy covariate */
                   1637: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1638: 
                   1639: #define FTYPE 1; /* Fixed covariate */
                   1640: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1641: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1642: 
                   1643: struct kmodel{
                   1644:        int maintype; /* main type */
                   1645:        int subtype; /* subtype */
                   1646: };
                   1647: struct kmodel modell[NCOVMAX];
                   1648: 
1.143     brouard  1649: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1650: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1651: 
                   1652: /**************** split *************************/
                   1653: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1654: {
                   1655:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1656:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1657:   */ 
                   1658:   char *ss;                            /* pointer */
1.186     brouard  1659:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1660: 
                   1661:   l1 = strlen(path );                  /* length of path */
                   1662:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1663:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1664:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1665:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1666:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1667:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1668:     /* get current working directory */
                   1669:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1670: #ifdef WIN32
                   1671:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1672: #else
                   1673:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1674: #endif
1.126     brouard  1675:       return( GLOCK_ERROR_GETCWD );
                   1676:     }
                   1677:     /* got dirc from getcwd*/
                   1678:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1679:   } else {                             /* strip directory from path */
1.126     brouard  1680:     ss++;                              /* after this, the filename */
                   1681:     l2 = strlen( ss );                 /* length of filename */
                   1682:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1683:     strcpy( name, ss );                /* save file name */
                   1684:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1685:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1686:     printf(" DIRC2 = %s \n",dirc);
                   1687:   }
                   1688:   /* We add a separator at the end of dirc if not exists */
                   1689:   l1 = strlen( dirc );                 /* length of directory */
                   1690:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1691:     dirc[l1] =  DIRSEPARATOR;
                   1692:     dirc[l1+1] = 0; 
                   1693:     printf(" DIRC3 = %s \n",dirc);
                   1694:   }
                   1695:   ss = strrchr( name, '.' );           /* find last / */
                   1696:   if (ss >0){
                   1697:     ss++;
                   1698:     strcpy(ext,ss);                    /* save extension */
                   1699:     l1= strlen( name);
                   1700:     l2= strlen(ss)+1;
                   1701:     strncpy( finame, name, l1-l2);
                   1702:     finame[l1-l2]= 0;
                   1703:   }
                   1704: 
                   1705:   return( 0 );                         /* we're done */
                   1706: }
                   1707: 
                   1708: 
                   1709: /******************************************/
                   1710: 
                   1711: void replace_back_to_slash(char *s, char*t)
                   1712: {
                   1713:   int i;
                   1714:   int lg=0;
                   1715:   i=0;
                   1716:   lg=strlen(t);
                   1717:   for(i=0; i<= lg; i++) {
                   1718:     (s[i] = t[i]);
                   1719:     if (t[i]== '\\') s[i]='/';
                   1720:   }
                   1721: }
                   1722: 
1.132     brouard  1723: char *trimbb(char *out, char *in)
1.137     brouard  1724: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1725:   char *s;
                   1726:   s=out;
                   1727:   while (*in != '\0'){
1.137     brouard  1728:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1729:       in++;
                   1730:     }
                   1731:     *out++ = *in++;
                   1732:   }
                   1733:   *out='\0';
                   1734:   return s;
                   1735: }
                   1736: 
1.187     brouard  1737: /* char *substrchaine(char *out, char *in, char *chain) */
                   1738: /* { */
                   1739: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1740: /*   char *s, *t; */
                   1741: /*   t=in;s=out; */
                   1742: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1743: /*     *out++ = *in++; */
                   1744: /*   } */
                   1745: 
                   1746: /*   /\* *in matches *chain *\/ */
                   1747: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1748: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1749: /*   } */
                   1750: /*   in--; chain--; */
                   1751: /*   while ( (*in != '\0')){ */
                   1752: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1753: /*     *out++ = *in++; */
                   1754: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1755: /*   } */
                   1756: /*   *out='\0'; */
                   1757: /*   out=s; */
                   1758: /*   return out; */
                   1759: /* } */
                   1760: char *substrchaine(char *out, char *in, char *chain)
                   1761: {
                   1762:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1763:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1764: 
                   1765:   char *strloc;
                   1766: 
                   1767:   strcpy (out, in); 
                   1768:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1769:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1770:   if(strloc != NULL){ 
                   1771:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1772:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1773:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1774:   }
                   1775:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1776:   return out;
                   1777: }
                   1778: 
                   1779: 
1.145     brouard  1780: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1781: {
1.187     brouard  1782:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1783:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.310     brouard  1784:      gives alocc="abcdef" and blocc="ghi2j".
1.145     brouard  1785:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1786:   */
1.160     brouard  1787:   char *s, *t;
1.145     brouard  1788:   t=in;s=in;
                   1789:   while ((*in != occ) && (*in != '\0')){
                   1790:     *alocc++ = *in++;
                   1791:   }
                   1792:   if( *in == occ){
                   1793:     *(alocc)='\0';
                   1794:     s=++in;
                   1795:   }
                   1796:  
                   1797:   if (s == t) {/* occ not found */
                   1798:     *(alocc-(in-s))='\0';
                   1799:     in=s;
                   1800:   }
                   1801:   while ( *in != '\0'){
                   1802:     *blocc++ = *in++;
                   1803:   }
                   1804: 
                   1805:   *blocc='\0';
                   1806:   return t;
                   1807: }
1.137     brouard  1808: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1809: {
1.187     brouard  1810:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1811:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1812:      gives blocc="abcdef2ghi" and alocc="j".
                   1813:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1814:   */
                   1815:   char *s, *t;
                   1816:   t=in;s=in;
                   1817:   while (*in != '\0'){
                   1818:     while( *in == occ){
                   1819:       *blocc++ = *in++;
                   1820:       s=in;
                   1821:     }
                   1822:     *blocc++ = *in++;
                   1823:   }
                   1824:   if (s == t) /* occ not found */
                   1825:     *(blocc-(in-s))='\0';
                   1826:   else
                   1827:     *(blocc-(in-s)-1)='\0';
                   1828:   in=s;
                   1829:   while ( *in != '\0'){
                   1830:     *alocc++ = *in++;
                   1831:   }
                   1832: 
                   1833:   *alocc='\0';
                   1834:   return s;
                   1835: }
                   1836: 
1.126     brouard  1837: int nbocc(char *s, char occ)
                   1838: {
                   1839:   int i,j=0;
                   1840:   int lg=20;
                   1841:   i=0;
                   1842:   lg=strlen(s);
                   1843:   for(i=0; i<= lg; i++) {
1.234     brouard  1844:     if  (s[i] == occ ) j++;
1.126     brouard  1845:   }
                   1846:   return j;
                   1847: }
                   1848: 
1.137     brouard  1849: /* void cutv(char *u,char *v, char*t, char occ) */
                   1850: /* { */
                   1851: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1852: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1853: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1854: /*   int i,lg,j,p=0; */
                   1855: /*   i=0; */
                   1856: /*   lg=strlen(t); */
                   1857: /*   for(j=0; j<=lg-1; j++) { */
                   1858: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1859: /*   } */
1.126     brouard  1860: 
1.137     brouard  1861: /*   for(j=0; j<p; j++) { */
                   1862: /*     (u[j] = t[j]); */
                   1863: /*   } */
                   1864: /*      u[p]='\0'; */
1.126     brouard  1865: 
1.137     brouard  1866: /*    for(j=0; j<= lg; j++) { */
                   1867: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1868: /*   } */
                   1869: /* } */
1.126     brouard  1870: 
1.160     brouard  1871: #ifdef _WIN32
                   1872: char * strsep(char **pp, const char *delim)
                   1873: {
                   1874:   char *p, *q;
                   1875:          
                   1876:   if ((p = *pp) == NULL)
                   1877:     return 0;
                   1878:   if ((q = strpbrk (p, delim)) != NULL)
                   1879:   {
                   1880:     *pp = q + 1;
                   1881:     *q = '\0';
                   1882:   }
                   1883:   else
                   1884:     *pp = 0;
                   1885:   return p;
                   1886: }
                   1887: #endif
                   1888: 
1.126     brouard  1889: /********************** nrerror ********************/
                   1890: 
                   1891: void nrerror(char error_text[])
                   1892: {
                   1893:   fprintf(stderr,"ERREUR ...\n");
                   1894:   fprintf(stderr,"%s\n",error_text);
                   1895:   exit(EXIT_FAILURE);
                   1896: }
                   1897: /*********************** vector *******************/
                   1898: double *vector(int nl, int nh)
                   1899: {
                   1900:   double *v;
                   1901:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1902:   if (!v) nrerror("allocation failure in vector");
                   1903:   return v-nl+NR_END;
                   1904: }
                   1905: 
                   1906: /************************ free vector ******************/
                   1907: void free_vector(double*v, int nl, int nh)
                   1908: {
                   1909:   free((FREE_ARG)(v+nl-NR_END));
                   1910: }
                   1911: 
                   1912: /************************ivector *******************************/
                   1913: int *ivector(long nl,long nh)
                   1914: {
                   1915:   int *v;
                   1916:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1917:   if (!v) nrerror("allocation failure in ivector");
                   1918:   return v-nl+NR_END;
                   1919: }
                   1920: 
                   1921: /******************free ivector **************************/
                   1922: void free_ivector(int *v, long nl, long nh)
                   1923: {
                   1924:   free((FREE_ARG)(v+nl-NR_END));
                   1925: }
                   1926: 
                   1927: /************************lvector *******************************/
                   1928: long *lvector(long nl,long nh)
                   1929: {
                   1930:   long *v;
                   1931:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1932:   if (!v) nrerror("allocation failure in ivector");
                   1933:   return v-nl+NR_END;
                   1934: }
                   1935: 
                   1936: /******************free lvector **************************/
                   1937: void free_lvector(long *v, long nl, long nh)
                   1938: {
                   1939:   free((FREE_ARG)(v+nl-NR_END));
                   1940: }
                   1941: 
                   1942: /******************* imatrix *******************************/
                   1943: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1944:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1945: { 
                   1946:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1947:   int **m; 
                   1948:   
                   1949:   /* allocate pointers to rows */ 
                   1950:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1951:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1952:   m += NR_END; 
                   1953:   m -= nrl; 
                   1954:   
                   1955:   
                   1956:   /* allocate rows and set pointers to them */ 
                   1957:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1958:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1959:   m[nrl] += NR_END; 
                   1960:   m[nrl] -= ncl; 
                   1961:   
                   1962:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1963:   
                   1964:   /* return pointer to array of pointers to rows */ 
                   1965:   return m; 
                   1966: } 
                   1967: 
                   1968: /****************** free_imatrix *************************/
                   1969: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1970:       int **m;
                   1971:       long nch,ncl,nrh,nrl; 
                   1972:      /* free an int matrix allocated by imatrix() */ 
                   1973: { 
                   1974:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1975:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1976: } 
                   1977: 
                   1978: /******************* matrix *******************************/
                   1979: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1980: {
                   1981:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1982:   double **m;
                   1983: 
                   1984:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1985:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1986:   m += NR_END;
                   1987:   m -= nrl;
                   1988: 
                   1989:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1990:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1991:   m[nrl] += NR_END;
                   1992:   m[nrl] -= ncl;
                   1993: 
                   1994:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1995:   return m;
1.145     brouard  1996:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1997: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1998: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1999:    */
                   2000: }
                   2001: 
                   2002: /*************************free matrix ************************/
                   2003: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   2004: {
                   2005:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2006:   free((FREE_ARG)(m+nrl-NR_END));
                   2007: }
                   2008: 
                   2009: /******************* ma3x *******************************/
                   2010: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   2011: {
                   2012:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   2013:   double ***m;
                   2014: 
                   2015:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2016:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2017:   m += NR_END;
                   2018:   m -= nrl;
                   2019: 
                   2020:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2021:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2022:   m[nrl] += NR_END;
                   2023:   m[nrl] -= ncl;
                   2024: 
                   2025:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2026: 
                   2027:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   2028:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   2029:   m[nrl][ncl] += NR_END;
                   2030:   m[nrl][ncl] -= nll;
                   2031:   for (j=ncl+1; j<=nch; j++) 
                   2032:     m[nrl][j]=m[nrl][j-1]+nlay;
                   2033:   
                   2034:   for (i=nrl+1; i<=nrh; i++) {
                   2035:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   2036:     for (j=ncl+1; j<=nch; j++) 
                   2037:       m[i][j]=m[i][j-1]+nlay;
                   2038:   }
                   2039:   return m; 
                   2040:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   2041:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   2042:   */
                   2043: }
                   2044: 
                   2045: /*************************free ma3x ************************/
                   2046: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   2047: {
                   2048:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   2049:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2050:   free((FREE_ARG)(m+nrl-NR_END));
                   2051: }
                   2052: 
                   2053: /*************** function subdirf ***********/
                   2054: char *subdirf(char fileres[])
                   2055: {
                   2056:   /* Caution optionfilefiname is hidden */
                   2057:   strcpy(tmpout,optionfilefiname);
                   2058:   strcat(tmpout,"/"); /* Add to the right */
                   2059:   strcat(tmpout,fileres);
                   2060:   return tmpout;
                   2061: }
                   2062: 
                   2063: /*************** function subdirf2 ***********/
                   2064: char *subdirf2(char fileres[], char *preop)
                   2065: {
1.314     brouard  2066:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
                   2067:  Errors in subdirf, 2, 3 while printing tmpout is
1.315     brouard  2068:  rewritten within the same printf. Workaround: many printfs */
1.126     brouard  2069:   /* Caution optionfilefiname is hidden */
                   2070:   strcpy(tmpout,optionfilefiname);
                   2071:   strcat(tmpout,"/");
                   2072:   strcat(tmpout,preop);
                   2073:   strcat(tmpout,fileres);
                   2074:   return tmpout;
                   2075: }
                   2076: 
                   2077: /*************** function subdirf3 ***********/
                   2078: char *subdirf3(char fileres[], char *preop, char *preop2)
                   2079: {
                   2080:   
                   2081:   /* Caution optionfilefiname is hidden */
                   2082:   strcpy(tmpout,optionfilefiname);
                   2083:   strcat(tmpout,"/");
                   2084:   strcat(tmpout,preop);
                   2085:   strcat(tmpout,preop2);
                   2086:   strcat(tmpout,fileres);
                   2087:   return tmpout;
                   2088: }
1.213     brouard  2089:  
                   2090: /*************** function subdirfext ***********/
                   2091: char *subdirfext(char fileres[], char *preop, char *postop)
                   2092: {
                   2093:   
                   2094:   strcpy(tmpout,preop);
                   2095:   strcat(tmpout,fileres);
                   2096:   strcat(tmpout,postop);
                   2097:   return tmpout;
                   2098: }
1.126     brouard  2099: 
1.213     brouard  2100: /*************** function subdirfext3 ***********/
                   2101: char *subdirfext3(char fileres[], char *preop, char *postop)
                   2102: {
                   2103:   
                   2104:   /* Caution optionfilefiname is hidden */
                   2105:   strcpy(tmpout,optionfilefiname);
                   2106:   strcat(tmpout,"/");
                   2107:   strcat(tmpout,preop);
                   2108:   strcat(tmpout,fileres);
                   2109:   strcat(tmpout,postop);
                   2110:   return tmpout;
                   2111: }
                   2112:  
1.162     brouard  2113: char *asc_diff_time(long time_sec, char ascdiff[])
                   2114: {
                   2115:   long sec_left, days, hours, minutes;
                   2116:   days = (time_sec) / (60*60*24);
                   2117:   sec_left = (time_sec) % (60*60*24);
                   2118:   hours = (sec_left) / (60*60) ;
                   2119:   sec_left = (sec_left) %(60*60);
                   2120:   minutes = (sec_left) /60;
                   2121:   sec_left = (sec_left) % (60);
                   2122:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   2123:   return ascdiff;
                   2124: }
                   2125: 
1.126     brouard  2126: /***************** f1dim *************************/
                   2127: extern int ncom; 
                   2128: extern double *pcom,*xicom;
                   2129: extern double (*nrfunc)(double []); 
                   2130:  
                   2131: double f1dim(double x) 
                   2132: { 
                   2133:   int j; 
                   2134:   double f;
                   2135:   double *xt; 
                   2136:  
                   2137:   xt=vector(1,ncom); 
                   2138:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   2139:   f=(*nrfunc)(xt); 
                   2140:   free_vector(xt,1,ncom); 
                   2141:   return f; 
                   2142: } 
                   2143: 
                   2144: /*****************brent *************************/
                   2145: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  2146: {
                   2147:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   2148:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   2149:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   2150:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   2151:    * returned function value. 
                   2152:   */
1.126     brouard  2153:   int iter; 
                   2154:   double a,b,d,etemp;
1.159     brouard  2155:   double fu=0,fv,fw,fx;
1.164     brouard  2156:   double ftemp=0.;
1.126     brouard  2157:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   2158:   double e=0.0; 
                   2159:  
                   2160:   a=(ax < cx ? ax : cx); 
                   2161:   b=(ax > cx ? ax : cx); 
                   2162:   x=w=v=bx; 
                   2163:   fw=fv=fx=(*f)(x); 
                   2164:   for (iter=1;iter<=ITMAX;iter++) { 
                   2165:     xm=0.5*(a+b); 
                   2166:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   2167:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   2168:     printf(".");fflush(stdout);
                   2169:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  2170: #ifdef DEBUGBRENT
1.126     brouard  2171:     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);
                   2172:     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);
                   2173:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   2174: #endif
                   2175:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   2176:       *xmin=x; 
                   2177:       return fx; 
                   2178:     } 
                   2179:     ftemp=fu;
                   2180:     if (fabs(e) > tol1) { 
                   2181:       r=(x-w)*(fx-fv); 
                   2182:       q=(x-v)*(fx-fw); 
                   2183:       p=(x-v)*q-(x-w)*r; 
                   2184:       q=2.0*(q-r); 
                   2185:       if (q > 0.0) p = -p; 
                   2186:       q=fabs(q); 
                   2187:       etemp=e; 
                   2188:       e=d; 
                   2189:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  2190:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  2191:       else { 
1.224     brouard  2192:                                d=p/q; 
                   2193:                                u=x+d; 
                   2194:                                if (u-a < tol2 || b-u < tol2) 
                   2195:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  2196:       } 
                   2197:     } else { 
                   2198:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2199:     } 
                   2200:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   2201:     fu=(*f)(u); 
                   2202:     if (fu <= fx) { 
                   2203:       if (u >= x) a=x; else b=x; 
                   2204:       SHFT(v,w,x,u) 
1.183     brouard  2205:       SHFT(fv,fw,fx,fu) 
                   2206:     } else { 
                   2207:       if (u < x) a=u; else b=u; 
                   2208:       if (fu <= fw || w == x) { 
1.224     brouard  2209:                                v=w; 
                   2210:                                w=u; 
                   2211:                                fv=fw; 
                   2212:                                fw=fu; 
1.183     brouard  2213:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  2214:                                v=u; 
                   2215:                                fv=fu; 
1.183     brouard  2216:       } 
                   2217:     } 
1.126     brouard  2218:   } 
                   2219:   nrerror("Too many iterations in brent"); 
                   2220:   *xmin=x; 
                   2221:   return fx; 
                   2222: } 
                   2223: 
                   2224: /****************** mnbrak ***********************/
                   2225: 
                   2226: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2227:            double (*func)(double)) 
1.183     brouard  2228: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2229: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2230: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2231: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2232:    */
1.126     brouard  2233:   double ulim,u,r,q, dum;
                   2234:   double fu; 
1.187     brouard  2235: 
                   2236:   double scale=10.;
                   2237:   int iterscale=0;
                   2238: 
                   2239:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2240:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2241: 
                   2242: 
                   2243:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2244:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2245:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2246:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2247:   /* } */
                   2248: 
1.126     brouard  2249:   if (*fb > *fa) { 
                   2250:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2251:     SHFT(dum,*fb,*fa,dum) 
                   2252:   } 
1.126     brouard  2253:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2254:   *fc=(*func)(*cx); 
1.183     brouard  2255: #ifdef DEBUG
1.224     brouard  2256:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2257:   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  2258: #endif
1.224     brouard  2259:   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  2260:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2261:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2262:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2263:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2264:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2265:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2266:       fu=(*func)(u); 
1.163     brouard  2267: #ifdef DEBUG
                   2268:       /* f(x)=A(x-u)**2+f(u) */
                   2269:       double A, fparabu; 
                   2270:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2271:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2272:       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);
                   2273:       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  2274:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2275:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2276:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2277:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2278: #endif 
1.184     brouard  2279: #ifdef MNBRAKORIGINAL
1.183     brouard  2280: #else
1.191     brouard  2281: /*       if (fu > *fc) { */
                   2282: /* #ifdef DEBUG */
                   2283: /*       printf("mnbrak4  fu > fc \n"); */
                   2284: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2285: /* #endif */
                   2286: /*     /\* 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 *\\/  *\/ */
                   2287: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2288: /*     dum=u; /\* Shifting c and u *\/ */
                   2289: /*     u = *cx; */
                   2290: /*     *cx = dum; */
                   2291: /*     dum = fu; */
                   2292: /*     fu = *fc; */
                   2293: /*     *fc =dum; */
                   2294: /*       } else { /\* end *\/ */
                   2295: /* #ifdef DEBUG */
                   2296: /*       printf("mnbrak3  fu < fc \n"); */
                   2297: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2298: /* #endif */
                   2299: /*     dum=u; /\* Shifting c and u *\/ */
                   2300: /*     u = *cx; */
                   2301: /*     *cx = dum; */
                   2302: /*     dum = fu; */
                   2303: /*     fu = *fc; */
                   2304: /*     *fc =dum; */
                   2305: /*       } */
1.224     brouard  2306: #ifdef DEBUGMNBRAK
                   2307:                 double A, fparabu; 
                   2308:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2309:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2310:      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);
                   2311:      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  2312: #endif
1.191     brouard  2313:       dum=u; /* Shifting c and u */
                   2314:       u = *cx;
                   2315:       *cx = dum;
                   2316:       dum = fu;
                   2317:       fu = *fc;
                   2318:       *fc =dum;
1.183     brouard  2319: #endif
1.162     brouard  2320:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2321: #ifdef DEBUG
1.224     brouard  2322:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2323:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2324: #endif
1.126     brouard  2325:       fu=(*func)(u); 
                   2326:       if (fu < *fc) { 
1.183     brouard  2327: #ifdef DEBUG
1.224     brouard  2328:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2329:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2330: #endif
                   2331:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2332:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2333: #ifdef DEBUG
                   2334:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2335: #endif
                   2336:       } 
1.162     brouard  2337:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2338: #ifdef DEBUG
1.224     brouard  2339:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2340:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2341: #endif
1.126     brouard  2342:       u=ulim; 
                   2343:       fu=(*func)(u); 
1.183     brouard  2344:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2345: #ifdef DEBUG
1.224     brouard  2346:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2347:       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  2348: #endif
1.126     brouard  2349:       u=(*cx)+GOLD*(*cx-*bx); 
                   2350:       fu=(*func)(u); 
1.224     brouard  2351: #ifdef DEBUG
                   2352:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2353:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2354: #endif
1.183     brouard  2355:     } /* end tests */
1.126     brouard  2356:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2357:     SHFT(*fa,*fb,*fc,fu) 
                   2358: #ifdef DEBUG
1.224     brouard  2359:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2360:       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  2361: #endif
                   2362:   } /* 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  2363: } 
                   2364: 
                   2365: /*************** linmin ************************/
1.162     brouard  2366: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2367: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2368: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2369: the value of func at the returned location p . This is actually all accomplished by calling the
                   2370: routines mnbrak and brent .*/
1.126     brouard  2371: int ncom; 
                   2372: double *pcom,*xicom;
                   2373: double (*nrfunc)(double []); 
                   2374:  
1.224     brouard  2375: #ifdef LINMINORIGINAL
1.126     brouard  2376: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2377: #else
                   2378: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2379: #endif
1.126     brouard  2380: { 
                   2381:   double brent(double ax, double bx, double cx, 
                   2382:               double (*f)(double), double tol, double *xmin); 
                   2383:   double f1dim(double x); 
                   2384:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2385:              double *fc, double (*func)(double)); 
                   2386:   int j; 
                   2387:   double xx,xmin,bx,ax; 
                   2388:   double fx,fb,fa;
1.187     brouard  2389: 
1.203     brouard  2390: #ifdef LINMINORIGINAL
                   2391: #else
                   2392:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2393: #endif
                   2394:   
1.126     brouard  2395:   ncom=n; 
                   2396:   pcom=vector(1,n); 
                   2397:   xicom=vector(1,n); 
                   2398:   nrfunc=func; 
                   2399:   for (j=1;j<=n;j++) { 
                   2400:     pcom[j]=p[j]; 
1.202     brouard  2401:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2402:   } 
1.187     brouard  2403: 
1.203     brouard  2404: #ifdef LINMINORIGINAL
                   2405:   xx=1.;
                   2406: #else
                   2407:   axs=0.0;
                   2408:   xxs=1.;
                   2409:   do{
                   2410:     xx= xxs;
                   2411: #endif
1.187     brouard  2412:     ax=0.;
                   2413:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2414:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2415:     /* 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))   */
                   2416:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2417:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2418:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2419:     /* 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  2420: #ifdef LINMINORIGINAL
                   2421: #else
                   2422:     if (fx != fx){
1.224     brouard  2423:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2424:                        printf("|");
                   2425:                        fprintf(ficlog,"|");
1.203     brouard  2426: #ifdef DEBUGLINMIN
1.224     brouard  2427:                        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  2428: #endif
                   2429:     }
1.224     brouard  2430:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2431: #endif
                   2432:   
1.191     brouard  2433: #ifdef DEBUGLINMIN
                   2434:   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  2435:   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  2436: #endif
1.224     brouard  2437: #ifdef LINMINORIGINAL
                   2438: #else
1.317     brouard  2439:   if(fb == fx){ /* Flat function in the direction */
                   2440:     xmin=xx;
1.224     brouard  2441:     *flat=1;
1.317     brouard  2442:   }else{
1.224     brouard  2443:     *flat=0;
                   2444: #endif
                   2445:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2446:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2447:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2448:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2449:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2450:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2451: #ifdef DEBUG
1.224     brouard  2452:   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);
                   2453:   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);
                   2454: #endif
                   2455: #ifdef LINMINORIGINAL
                   2456: #else
                   2457:                        }
1.126     brouard  2458: #endif
1.191     brouard  2459: #ifdef DEBUGLINMIN
                   2460:   printf("linmin end ");
1.202     brouard  2461:   fprintf(ficlog,"linmin end ");
1.191     brouard  2462: #endif
1.126     brouard  2463:   for (j=1;j<=n;j++) { 
1.203     brouard  2464: #ifdef LINMINORIGINAL
                   2465:     xi[j] *= xmin; 
                   2466: #else
                   2467: #ifdef DEBUGLINMIN
                   2468:     if(xxs <1.0)
                   2469:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2470: #endif
                   2471:     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) */
                   2472: #ifdef DEBUGLINMIN
                   2473:     if(xxs <1.0)
                   2474:       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 );
                   2475: #endif
                   2476: #endif
1.187     brouard  2477:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2478:   } 
1.191     brouard  2479: #ifdef DEBUGLINMIN
1.203     brouard  2480:   printf("\n");
1.191     brouard  2481:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2482:   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  2483:   for (j=1;j<=n;j++) { 
1.202     brouard  2484:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2485:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2486:     if(j % ncovmodel == 0){
1.191     brouard  2487:       printf("\n");
1.202     brouard  2488:       fprintf(ficlog,"\n");
                   2489:     }
1.191     brouard  2490:   }
1.203     brouard  2491: #else
1.191     brouard  2492: #endif
1.126     brouard  2493:   free_vector(xicom,1,n); 
                   2494:   free_vector(pcom,1,n); 
                   2495: } 
                   2496: 
                   2497: 
                   2498: /*************** powell ************************/
1.162     brouard  2499: /*
1.317     brouard  2500: Minimization of a function func of n variables. Input consists in an initial starting point
                   2501: p[1..n] ; an initial matrix xi[1..n][1..n]  whose columns contain the initial set of di-
                   2502: rections (usually the n unit vectors); and ftol, the fractional tolerance in the function value
                   2503: such that failure to decrease by more than this amount in one iteration signals doneness. On
1.162     brouard  2504: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2505: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2506:  */
1.224     brouard  2507: #ifdef LINMINORIGINAL
                   2508: #else
                   2509:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2510:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2511: #endif
1.126     brouard  2512: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2513:            double (*func)(double [])) 
                   2514: { 
1.224     brouard  2515: #ifdef LINMINORIGINAL
                   2516:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2517:              double (*func)(double [])); 
1.224     brouard  2518: #else 
1.241     brouard  2519:  void linmin(double p[], double xi[], int n, double *fret,
                   2520:             double (*func)(double []),int *flat); 
1.224     brouard  2521: #endif
1.239     brouard  2522:  int i,ibig,j,jk,k; 
1.126     brouard  2523:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2524:   double directest;
1.126     brouard  2525:   double fp,fptt;
                   2526:   double *xits;
                   2527:   int niterf, itmp;
                   2528: 
                   2529:   pt=vector(1,n); 
                   2530:   ptt=vector(1,n); 
                   2531:   xit=vector(1,n); 
                   2532:   xits=vector(1,n); 
                   2533:   *fret=(*func)(p); 
                   2534:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.338     brouard  2535:   rcurr_time = time(NULL);
                   2536:   fp=(*fret); /* Initialisation */
1.126     brouard  2537:   for (*iter=1;;++(*iter)) { 
                   2538:     ibig=0; 
                   2539:     del=0.0; 
1.157     brouard  2540:     rlast_time=rcurr_time;
                   2541:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2542:     rcurr_time = time(NULL);  
                   2543:     curr_time = *localtime(&rcurr_time);
1.337     brouard  2544:     /* 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); */
                   2545:     /* 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); */
                   2546:     printf("\nPowell iter=%d -2*LL=%.12f gain=%.3lg %ld sec. %ld sec.",*iter,*fret,fp-*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   2547:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f gain=%.3lg %ld sec. %ld sec.",*iter,*fret,fp-*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1.157     brouard  2548: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.324     brouard  2549:     fp=(*fret); /* From former iteration or initial value */
1.192     brouard  2550:     for (i=1;i<=n;i++) {
1.126     brouard  2551:       fprintf(ficrespow," %.12lf", p[i]);
                   2552:     }
1.239     brouard  2553:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2554:     printf("\n#model=  1      +     age ");
                   2555:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2556:     if(nagesqr==1){
1.241     brouard  2557:        printf("  + age*age  ");
                   2558:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2559:     }
                   2560:     for(j=1;j <=ncovmodel-2;j++){
                   2561:       if(Typevar[j]==0) {
                   2562:        printf("  +      V%d  ",Tvar[j]);
                   2563:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2564:       }else if(Typevar[j]==1) {
                   2565:        printf("  +    V%d*age ",Tvar[j]);
                   2566:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2567:       }else if(Typevar[j]==2) {
                   2568:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2569:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2570:       }
                   2571:     }
1.126     brouard  2572:     printf("\n");
1.239     brouard  2573: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2574: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2575:     fprintf(ficlog,"\n");
1.239     brouard  2576:     for(i=1,jk=1; i <=nlstate; i++){
                   2577:       for(k=1; k <=(nlstate+ndeath); k++){
                   2578:        if (k != i) {
                   2579:          printf("%d%d ",i,k);
                   2580:          fprintf(ficlog,"%d%d ",i,k);
                   2581:          for(j=1; j <=ncovmodel; j++){
                   2582:            printf("%12.7f ",p[jk]);
                   2583:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2584:            jk++; 
                   2585:          }
                   2586:          printf("\n");
                   2587:          fprintf(ficlog,"\n");
                   2588:        }
                   2589:       }
                   2590:     }
1.241     brouard  2591:     if(*iter <=3 && *iter >1){
1.157     brouard  2592:       tml = *localtime(&rcurr_time);
                   2593:       strcpy(strcurr,asctime(&tml));
                   2594:       rforecast_time=rcurr_time; 
1.126     brouard  2595:       itmp = strlen(strcurr);
                   2596:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2597:        strcurr[itmp-1]='\0';
1.162     brouard  2598:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2599:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  2600:       for(niterf=10;niterf<=30;niterf+=10){
1.241     brouard  2601:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2602:        forecast_time = *localtime(&rforecast_time);
                   2603:        strcpy(strfor,asctime(&forecast_time));
                   2604:        itmp = strlen(strfor);
                   2605:        if(strfor[itmp-1]=='\n')
                   2606:          strfor[itmp-1]='\0';
                   2607:        printf("   - if your program needs %d iterations to converge, convergence will be \n   reached in %s i.e.\n   on %s (current time is %s);\n",niterf, asc_diff_time(rforecast_time-rcurr_time,tmpout),strfor,strcurr);
                   2608:        fprintf(ficlog,"   - if your program needs %d iterations to converge, convergence will be \n   reached in %s i.e.\n   on %s (current time is %s);\n",niterf, asc_diff_time(rforecast_time-rcurr_time,tmpout),strfor,strcurr);
1.126     brouard  2609:       }
                   2610:     }
1.187     brouard  2611:     for (i=1;i<=n;i++) { /* For each direction i */
                   2612:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2613:       fptt=(*fret); 
                   2614: #ifdef DEBUG
1.203     brouard  2615:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2616:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2617: #endif
1.203     brouard  2618:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2619:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2620: #ifdef LINMINORIGINAL
1.188     brouard  2621:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2622: #else
                   2623:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2624:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2625: #endif
                   2626:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2627:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2628:                                /* because that direction will be replaced unless the gain del is small */
                   2629:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2630:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2631:                                /* with the new direction. */
                   2632:                                del=fabs(fptt-(*fret)); 
                   2633:                                ibig=i; 
1.126     brouard  2634:       } 
                   2635: #ifdef DEBUG
                   2636:       printf("%d %.12e",i,(*fret));
                   2637:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2638:       for (j=1;j<=n;j++) {
1.224     brouard  2639:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2640:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2641:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2642:       }
                   2643:       for(j=1;j<=n;j++) {
1.225     brouard  2644:                                printf(" p(%d)=%.12e",j,p[j]);
                   2645:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2646:       }
                   2647:       printf("\n");
                   2648:       fprintf(ficlog,"\n");
                   2649: #endif
1.187     brouard  2650:     } /* end loop on each direction i */
                   2651:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2652:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2653:     /* New value of last point Pn is not computed, P(n-1) */
1.319     brouard  2654:     for(j=1;j<=n;j++) {
                   2655:       if(flatdir[j] >0){
                   2656:         printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2657:         fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
1.302     brouard  2658:       }
1.319     brouard  2659:       /* printf("\n"); */
                   2660:       /* fprintf(ficlog,"\n"); */
                   2661:     }
1.243     brouard  2662:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2663:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2664:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2665:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2666:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2667:       /* decreased of more than 3.84  */
                   2668:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2669:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2670:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2671:                        
1.188     brouard  2672:       /* Starting the program with initial values given by a former maximization will simply change */
                   2673:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2674:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2675:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2676: #ifdef DEBUG
                   2677:       int k[2],l;
                   2678:       k[0]=1;
                   2679:       k[1]=-1;
                   2680:       printf("Max: %.12e",(*func)(p));
                   2681:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2682:       for (j=1;j<=n;j++) {
                   2683:        printf(" %.12e",p[j]);
                   2684:        fprintf(ficlog," %.12e",p[j]);
                   2685:       }
                   2686:       printf("\n");
                   2687:       fprintf(ficlog,"\n");
                   2688:       for(l=0;l<=1;l++) {
                   2689:        for (j=1;j<=n;j++) {
                   2690:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2691:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2692:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2693:        }
                   2694:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2695:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2696:       }
                   2697: #endif
                   2698: 
                   2699:       free_vector(xit,1,n); 
                   2700:       free_vector(xits,1,n); 
                   2701:       free_vector(ptt,1,n); 
                   2702:       free_vector(pt,1,n); 
                   2703:       return; 
1.192     brouard  2704:     } /* enough precision */ 
1.240     brouard  2705:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2706:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2707:       ptt[j]=2.0*p[j]-pt[j]; 
                   2708:       xit[j]=p[j]-pt[j]; 
                   2709:       pt[j]=p[j]; 
                   2710:     } 
1.181     brouard  2711:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2712: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2713:                if (*iter <=4) {
1.225     brouard  2714: #else
                   2715: #endif
1.224     brouard  2716: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2717: #else
1.161     brouard  2718:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2719: #endif
1.162     brouard  2720:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2721:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2722:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2723:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2724:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2725:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2726:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2727:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2728:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2729:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2730:       /* mu² and del² are equal when f3=f1 */
                   2731:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2732:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2733:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2734:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2735: #ifdef NRCORIGINAL
                   2736:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2737: #else
                   2738:       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  2739:       t= t- del*SQR(fp-fptt);
1.183     brouard  2740: #endif
1.202     brouard  2741:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2742: #ifdef DEBUG
1.181     brouard  2743:       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);
                   2744:       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  2745:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2746:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2747:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2748:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2749:       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);
                   2750:       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);
                   2751: #endif
1.183     brouard  2752: #ifdef POWELLORIGINAL
                   2753:       if (t < 0.0) { /* Then we use it for new direction */
                   2754: #else
1.182     brouard  2755:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2756:                                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  2757:         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  2758:         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  2759:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2760:       } 
1.181     brouard  2761:       if (directest < 0.0) { /* Then we use it for new direction */
                   2762: #endif
1.191     brouard  2763: #ifdef DEBUGLINMIN
1.234     brouard  2764:        printf("Before linmin in direction P%d-P0\n",n);
                   2765:        for (j=1;j<=n;j++) {
                   2766:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2767:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2768:          if(j % ncovmodel == 0){
                   2769:            printf("\n");
                   2770:            fprintf(ficlog,"\n");
                   2771:          }
                   2772:        }
1.224     brouard  2773: #endif
                   2774: #ifdef LINMINORIGINAL
1.234     brouard  2775:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2776: #else
1.234     brouard  2777:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2778:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2779: #endif
1.234     brouard  2780:        
1.191     brouard  2781: #ifdef DEBUGLINMIN
1.234     brouard  2782:        for (j=1;j<=n;j++) { 
                   2783:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2784:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2785:          if(j % ncovmodel == 0){
                   2786:            printf("\n");
                   2787:            fprintf(ficlog,"\n");
                   2788:          }
                   2789:        }
1.224     brouard  2790: #endif
1.234     brouard  2791:        for (j=1;j<=n;j++) { 
                   2792:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2793:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2794:        }
1.224     brouard  2795: #ifdef LINMINORIGINAL
                   2796: #else
1.234     brouard  2797:        for (j=1, flatd=0;j<=n;j++) {
                   2798:          if(flatdir[j]>0)
                   2799:            flatd++;
                   2800:        }
                   2801:        if(flatd >0){
1.255     brouard  2802:          printf("%d flat directions: ",flatd);
                   2803:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  2804:          for (j=1;j<=n;j++) { 
                   2805:            if(flatdir[j]>0){
                   2806:              printf("%d ",j);
                   2807:              fprintf(ficlog,"%d ",j);
                   2808:            }
                   2809:          }
                   2810:          printf("\n");
                   2811:          fprintf(ficlog,"\n");
1.319     brouard  2812: #ifdef FLATSUP
                   2813:           free_vector(xit,1,n); 
                   2814:           free_vector(xits,1,n); 
                   2815:           free_vector(ptt,1,n); 
                   2816:           free_vector(pt,1,n); 
                   2817:           return;
                   2818: #endif
1.234     brouard  2819:        }
1.191     brouard  2820: #endif
1.234     brouard  2821:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2822:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2823:        
1.126     brouard  2824: #ifdef DEBUG
1.234     brouard  2825:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2826:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2827:        for(j=1;j<=n;j++){
                   2828:          printf(" %lf",xit[j]);
                   2829:          fprintf(ficlog," %lf",xit[j]);
                   2830:        }
                   2831:        printf("\n");
                   2832:        fprintf(ficlog,"\n");
1.126     brouard  2833: #endif
1.192     brouard  2834:       } /* end of t or directest negative */
1.224     brouard  2835: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2836: #else
1.234     brouard  2837:       } /* end if (fptt < fp)  */
1.192     brouard  2838: #endif
1.225     brouard  2839: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2840:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2841: #else
1.224     brouard  2842: #endif
1.234     brouard  2843:                } /* loop iteration */ 
1.126     brouard  2844: } 
1.234     brouard  2845:   
1.126     brouard  2846: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2847:   
1.235     brouard  2848:   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  2849:   {
1.338     brouard  2850:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij . Nicely done
1.279     brouard  2851:      *   (and selected quantitative values in nres)
                   2852:      *  by left multiplying the unit
                   2853:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   2854:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   2855:      * Wx is row vector: population in state 1, population in state 2, population dead
                   2856:      * or prevalence in state 1, prevalence in state 2, 0
                   2857:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   2858:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   2859:      * Output is prlim.
                   2860:      * Initial matrix pimij 
                   2861:      */
1.206     brouard  2862:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2863:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2864:   /*  0,                   0                  , 1} */
                   2865:   /*
                   2866:    * and after some iteration: */
                   2867:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2868:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2869:   /*  0,                   0                  , 1} */
                   2870:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2871:   /* {0.51571254859325999, 0.4842874514067399, */
                   2872:   /*  0.51326036147820708, 0.48673963852179264} */
                   2873:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2874:     
1.332     brouard  2875:     int i, ii,j,k, k1;
1.209     brouard  2876:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2877:   /* double **matprod2(); */ /* test */
1.218     brouard  2878:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2879:   double **newm;
1.209     brouard  2880:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2881:   int ncvloop=0;
1.288     brouard  2882:   int first=0;
1.169     brouard  2883:   
1.209     brouard  2884:   min=vector(1,nlstate);
                   2885:   max=vector(1,nlstate);
                   2886:   meandiff=vector(1,nlstate);
                   2887: 
1.218     brouard  2888:        /* Starting with matrix unity */
1.126     brouard  2889:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2890:     for (j=1;j<=nlstate+ndeath;j++){
                   2891:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2892:     }
1.169     brouard  2893:   
                   2894:   cov[1]=1.;
                   2895:   
                   2896:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2897:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2898:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2899:     ncvloop++;
1.126     brouard  2900:     newm=savm;
                   2901:     /* Covariates have to be included here again */
1.138     brouard  2902:     cov[2]=agefin;
1.319     brouard  2903:      if(nagesqr==1){
                   2904:       cov[3]= agefin*agefin;
                   2905:      }
1.332     brouard  2906:      /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   2907:      /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   2908:      for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   2909:        if(Typevar[k1]==1){ /* A product with age */
                   2910:         cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   2911:        }else{
                   2912:         cov[2+nagesqr+k1]=precov[nres][k1];
                   2913:        }
                   2914:      }/* End of loop on model equation */
                   2915:      
                   2916: /* Start of old code (replaced by a loop on position in the model equation */
                   2917:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only of the model *\/ */
                   2918:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   2919:     /*   /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; *\/ */
                   2920:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TnsdVar[TvarsD[k]])]; */
                   2921:     /*   /\* model = 1 +age + V1*V3 + age*V1 + V2 + V1 + age*V2 + V3 + V3*age + V1*V2  */
                   2922:     /*    * k                  1        2      3    4      5      6     7        8 */
                   2923:     /*    *cov[]   1    2      3        4      5    6      7      8     9       10 */
                   2924:     /*    *TypeVar[k]          2        1      0    0      1      0     1        2 */
                   2925:     /*    *Dummy[k]            0        2      0    0      2      0     2        0 */
                   2926:     /*    *Tvar[k]             4        1      2    1      2      3     3        5 */
                   2927:     /*    *nsd=3                              (1)  (2)           (3) */
                   2928:     /*    *TvarsD[nsd]                      [1]=2    1             3 */
                   2929:     /*    *TnsdVar                          [2]=2 [1]=1         [3]=3 */
                   2930:     /*    *TvarsDind[nsd](=k)               [1]=3 [2]=4         [3]=6 */
                   2931:     /*    *Tage[]                  [1]=1                  [2]=2      [3]=3 */
                   2932:     /*    *Tvard[]       [1][1]=1                                           [2][1]=1 */
                   2933:     /*    *                   [1][2]=3                                           [2][2]=2 */
                   2934:     /*    *Tprod[](=k)     [1]=1                                              [2]=8 */
                   2935:     /*    *TvarsDp(=Tvar)   [1]=1            [2]=2             [3]=3          [4]=5 */
                   2936:     /*    *TvarD (=k)       [1]=1            [2]=3 [3]=4       [3]=6          [4]=6 */
                   2937:     /*    *TvarsDpType */
                   2938:     /*    *si model= 1 + age + V3 + V2*age + V2 + V3*age */
                   2939:     /*    * nsd=1              (1)           (2) */
                   2940:     /*    *TvarsD[nsd]          3             2 */
                   2941:     /*    *TnsdVar           (3)=1          (2)=2 */
                   2942:     /*    *TvarsDind[nsd](=k)  [1]=1        [2]=3 */
                   2943:     /*    *Tage[]                  [1]=2           [2]= 3    */
                   2944:     /*    *\/ */
                   2945:     /*   /\* cov[++k1]=nbcode[TvarsD[k]][codtabm(ij,k)]; *\/ */
                   2946:     /*   /\* 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)); *\/ */
                   2947:     /* } */
                   2948:     /* for (k=1; k<=nsq;k++) { /\* For single quantitative varying covariates only of the model *\/ */
                   2949:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   2950:     /*   /\* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 *\/ */
                   2951:     /*   /\* cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   2952:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][resultmodel[nres][k1]] */
                   2953:     /*   /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   2954:     /*   /\* 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]); *\/ */
                   2955:     /* } */
                   2956:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   2957:     /*   if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   2958:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   2959:     /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   2960:     /*   } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   2961:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   2962:     /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   2963:     /*   } */
                   2964:     /*   /\* 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]); *\/ */
                   2965:     /* } */
                   2966:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   2967:     /*   /\* 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]); *\/ */
                   2968:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   2969:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   2970:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   2971:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   2972:     /*         }else{ */
                   2973:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   2974:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   2975:     /*         } */
                   2976:     /*   }else{ */
                   2977:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   2978:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   2979:     /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   2980:     /*         }else{ */
                   2981:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   2982:     /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   2983:     /*         } */
                   2984:     /*   } */
                   2985:     /* } /\* End product without age *\/ */
                   2986: /* ENd of old code */
1.138     brouard  2987:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2988:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2989:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2990:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2991:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.319     brouard  2992:     /* age and covariate values of ij are in 'cov' */
1.142     brouard  2993:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2994:     
1.126     brouard  2995:     savm=oldm;
                   2996:     oldm=newm;
1.209     brouard  2997: 
                   2998:     for(j=1; j<=nlstate; j++){
                   2999:       max[j]=0.;
                   3000:       min[j]=1.;
                   3001:     }
                   3002:     for(i=1;i<=nlstate;i++){
                   3003:       sumnew=0;
                   3004:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   3005:       for(j=1; j<=nlstate; j++){ 
                   3006:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   3007:        max[j]=FMAX(max[j],prlim[i][j]);
                   3008:        min[j]=FMIN(min[j],prlim[i][j]);
                   3009:       }
                   3010:     }
                   3011: 
1.126     brouard  3012:     maxmax=0.;
1.209     brouard  3013:     for(j=1; j<=nlstate; j++){
                   3014:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   3015:       maxmax=FMAX(maxmax,meandiff[j]);
                   3016:       /* 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  3017:     } /* j loop */
1.203     brouard  3018:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  3019:     /* 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  3020:     if(maxmax < ftolpl){
1.209     brouard  3021:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   3022:       free_vector(min,1,nlstate);
                   3023:       free_vector(max,1,nlstate);
                   3024:       free_vector(meandiff,1,nlstate);
1.126     brouard  3025:       return prlim;
                   3026:     }
1.288     brouard  3027:   } /* agefin loop */
1.208     brouard  3028:     /* After some age loop it doesn't converge */
1.288     brouard  3029:   if(!first){
                   3030:     first=1;
                   3031:     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  3032:     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);
                   3033:   }else if (first >=1 && first <10){
                   3034:     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);
                   3035:     first++;
                   3036:   }else if (first ==10){
                   3037:     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);
                   3038:     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");
                   3039:     fprintf(ficlog,"Warning: the stable prevalence no convergence; too many cases, giving up noticing, even in log file\n");
                   3040:     first++;
1.288     brouard  3041:   }
                   3042: 
1.209     brouard  3043:   /* 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); */
                   3044:   free_vector(min,1,nlstate);
                   3045:   free_vector(max,1,nlstate);
                   3046:   free_vector(meandiff,1,nlstate);
1.208     brouard  3047:   
1.169     brouard  3048:   return prlim; /* should not reach here */
1.126     brouard  3049: }
                   3050: 
1.217     brouard  3051: 
                   3052:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   3053: 
1.218     brouard  3054:  /* 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) */
                   3055:  /* 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  3056:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  3057: {
1.264     brouard  3058:   /* 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  3059:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   3060:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   3061:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   3062:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   3063:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   3064:   /* Initial matrix pimij */
                   3065:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   3066:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   3067:   /*  0,                   0                  , 1} */
                   3068:   /*
                   3069:    * and after some iteration: */
                   3070:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   3071:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   3072:   /*  0,                   0                  , 1} */
                   3073:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   3074:   /* {0.51571254859325999, 0.4842874514067399, */
                   3075:   /*  0.51326036147820708, 0.48673963852179264} */
                   3076:   /* If we start from prlim again, prlim tends to a constant matrix */
                   3077: 
1.332     brouard  3078:   int i, ii,j,k, k1;
1.247     brouard  3079:   int first=0;
1.217     brouard  3080:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   3081:   /* double **matprod2(); */ /* test */
                   3082:   double **out, cov[NCOVMAX+1], **bmij();
                   3083:   double **newm;
1.218     brouard  3084:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   3085:   double        **oldm, **savm;  /* for use */
                   3086: 
1.217     brouard  3087:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   3088:   int ncvloop=0;
                   3089:   
                   3090:   min=vector(1,nlstate);
                   3091:   max=vector(1,nlstate);
                   3092:   meandiff=vector(1,nlstate);
                   3093: 
1.266     brouard  3094:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   3095:   oldm=oldms; savm=savms;
                   3096:   
                   3097:   /* Starting with matrix unity */
                   3098:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   3099:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  3100:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3101:     }
                   3102:   
                   3103:   cov[1]=1.;
                   3104:   
                   3105:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3106:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  3107:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  3108:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   3109:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  3110:     ncvloop++;
1.218     brouard  3111:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   3112:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  3113:     /* Covariates have to be included here again */
                   3114:     cov[2]=agefin;
1.319     brouard  3115:     if(nagesqr==1){
1.217     brouard  3116:       cov[3]= agefin*agefin;;
1.319     brouard  3117:     }
1.332     brouard  3118:     for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   3119:       if(Typevar[k1]==1){ /* A product with age */
                   3120:        cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.242     brouard  3121:       }else{
1.332     brouard  3122:        cov[2+nagesqr+k1]=precov[nres][k1];
1.242     brouard  3123:       }
1.332     brouard  3124:     }/* End of loop on model equation */
                   3125: 
                   3126: /* Old code */ 
                   3127: 
                   3128:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   3129:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   3130:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; */
                   3131:     /*   /\* 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)); *\/ */
                   3132:     /* } */
                   3133:     /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   3134:     /* /\*   /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3135:     /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3136:     /* /\*   /\\* 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])]); *\\/ *\/ */
                   3137:     /* /\* } *\/ */
                   3138:     /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3139:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3140:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3141:     /*   /\* 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]); *\/ */
                   3142:     /* } */
                   3143:     /* /\* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; *\/ */
                   3144:     /* /\* for (k=1; k<=cptcovprod;k++) /\\* Useless *\\/ *\/ */
                   3145:     /* /\*   /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\\/ *\/ */
                   3146:     /* /\*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3147:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   3148:     /*   /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age *\\/ ERROR ???*\/ */
                   3149:     /*   if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3150:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3151:     /*   } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3152:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   3153:     /*   } */
                   3154:     /*   /\* 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]); *\/ */
                   3155:     /* } */
                   3156:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   3157:     /*   /\* 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]); *\/ */
                   3158:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3159:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3160:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3161:     /*         }else{ */
                   3162:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3163:     /*         } */
                   3164:     /*   }else{ */
                   3165:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3166:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3167:     /*         }else{ */
                   3168:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3169:     /*         } */
                   3170:     /*   } */
                   3171:     /* } */
1.217     brouard  3172:     
                   3173:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3174:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3175:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   3176:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3177:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  3178:                /* ij should be linked to the correct index of cov */
                   3179:                /* age and covariate values ij are in 'cov', but we need to pass
                   3180:                 * ij for the observed prevalence at age and status and covariate
                   3181:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   3182:                 */
                   3183:     /* 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 *\/ */
                   3184:     /* 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 *\/ */
                   3185:     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  3186:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  3187:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   3188:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   3189:     /*         printf("%d newm= ",i); */
                   3190:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3191:     /*           printf("%f ",newm[i][j]); */
                   3192:     /*         } */
                   3193:     /*         printf("oldm * "); */
                   3194:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3195:     /*           printf("%f ",oldm[i][j]); */
                   3196:     /*         } */
1.268     brouard  3197:     /*         printf(" bmmij "); */
1.266     brouard  3198:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3199:     /*           printf("%f ",pmmij[i][j]); */
                   3200:     /*         } */
                   3201:     /*         printf("\n"); */
                   3202:     /*   } */
                   3203:     /* } */
1.217     brouard  3204:     savm=oldm;
                   3205:     oldm=newm;
1.266     brouard  3206: 
1.217     brouard  3207:     for(j=1; j<=nlstate; j++){
                   3208:       max[j]=0.;
                   3209:       min[j]=1.;
                   3210:     }
                   3211:     for(j=1; j<=nlstate; j++){ 
                   3212:       for(i=1;i<=nlstate;i++){
1.234     brouard  3213:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   3214:        bprlim[i][j]= newm[i][j];
                   3215:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   3216:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  3217:       }
                   3218:     }
1.218     brouard  3219:                
1.217     brouard  3220:     maxmax=0.;
                   3221:     for(i=1; i<=nlstate; i++){
1.318     brouard  3222:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column, could be nan! */
1.217     brouard  3223:       maxmax=FMAX(maxmax,meandiff[i]);
                   3224:       /* 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  3225:     } /* i loop */
1.217     brouard  3226:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  3227:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3228:     if(maxmax < ftolpl){
1.220     brouard  3229:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3230:       free_vector(min,1,nlstate);
                   3231:       free_vector(max,1,nlstate);
                   3232:       free_vector(meandiff,1,nlstate);
                   3233:       return bprlim;
                   3234:     }
1.288     brouard  3235:   } /* agefin loop */
1.217     brouard  3236:     /* After some age loop it doesn't converge */
1.288     brouard  3237:   if(!first){
1.247     brouard  3238:     first=1;
                   3239:     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\
                   3240: 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);
                   3241:   }
                   3242:   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  3243: 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);
                   3244:   /* 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); */
                   3245:   free_vector(min,1,nlstate);
                   3246:   free_vector(max,1,nlstate);
                   3247:   free_vector(meandiff,1,nlstate);
                   3248:   
                   3249:   return bprlim; /* should not reach here */
                   3250: }
                   3251: 
1.126     brouard  3252: /*************** transition probabilities ***************/ 
                   3253: 
                   3254: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   3255: {
1.138     brouard  3256:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  3257:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  3258:      model to the ncovmodel covariates (including constant and age).
                   3259:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3260:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3261:      ncth covariate in the global vector x is given by the formula:
                   3262:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3263:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3264:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3265:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  3266:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  3267:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  3268:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  3269:   */
                   3270:   double s1, lnpijopii;
1.126     brouard  3271:   /*double t34;*/
1.164     brouard  3272:   int i,j, nc, ii, jj;
1.126     brouard  3273: 
1.223     brouard  3274:   for(i=1; i<= nlstate; i++){
                   3275:     for(j=1; j<i;j++){
                   3276:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3277:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3278:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3279:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3280:       }
                   3281:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3282:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3283:     }
                   3284:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3285:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3286:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3287:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3288:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3289:       }
                   3290:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3291:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3292:     }
                   3293:   }
1.218     brouard  3294:   
1.223     brouard  3295:   for(i=1; i<= nlstate; i++){
                   3296:     s1=0;
                   3297:     for(j=1; j<i; j++){
1.339     brouard  3298:       /* printf("debug1 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  3299:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3300:     }
                   3301:     for(j=i+1; j<=nlstate+ndeath; j++){
1.339     brouard  3302:       /* printf("debug2 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  3303:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3304:     }
                   3305:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3306:     ps[i][i]=1./(s1+1.);
                   3307:     /* Computing other pijs */
                   3308:     for(j=1; j<i; j++)
1.325     brouard  3309:       ps[i][j]= exp(ps[i][j])*ps[i][i];/* Bug valgrind */
1.223     brouard  3310:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3311:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3312:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3313:   } /* end i */
1.218     brouard  3314:   
1.223     brouard  3315:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3316:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3317:       ps[ii][jj]=0;
                   3318:       ps[ii][ii]=1;
                   3319:     }
                   3320:   }
1.294     brouard  3321: 
                   3322: 
1.223     brouard  3323:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3324:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3325:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3326:   /*   } */
                   3327:   /*   printf("\n "); */
                   3328:   /* } */
                   3329:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3330:   /*
                   3331:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  3332:                goto end;*/
1.266     brouard  3333:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  3334: }
                   3335: 
1.218     brouard  3336: /*************** backward transition probabilities ***************/ 
                   3337: 
                   3338:  /* 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 ) */
                   3339: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   3340:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   3341: {
1.302     brouard  3342:   /* 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  3343:    * 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  3344:    */
1.218     brouard  3345:   int i, ii, j,k;
1.222     brouard  3346:   
                   3347:   double **out, **pmij();
                   3348:   double sumnew=0.;
1.218     brouard  3349:   double agefin;
1.292     brouard  3350:   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  3351:   double **dnewm, **dsavm, **doldm;
                   3352:   double **bbmij;
                   3353:   
1.218     brouard  3354:   doldm=ddoldms; /* global pointers */
1.222     brouard  3355:   dnewm=ddnewms;
                   3356:   dsavm=ddsavms;
1.318     brouard  3357: 
                   3358:   /* Debug */
                   3359:   /* printf("Bmij ij=%d, cov[2}=%f\n", ij, cov[2]); */
1.222     brouard  3360:   agefin=cov[2];
1.268     brouard  3361:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  3362:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  3363:      the observed prevalence (with this covariate ij) at beginning of transition */
                   3364:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  3365: 
                   3366:   /* P_x */
1.325     brouard  3367:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm *//* Bug valgrind */
1.268     brouard  3368:   /* outputs pmmij which is a stochastic matrix in row */
                   3369: 
                   3370:   /* Diag(w_x) */
1.292     brouard  3371:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  3372:   sumnew=0.;
1.269     brouard  3373:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  3374:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  3375:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  3376:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   3377:   }
                   3378:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   3379:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3380:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  3381:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  3382:     }
                   3383:   }else{
                   3384:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3385:       for (j=1;j<=nlstate+ndeath;j++)
                   3386:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   3387:     }
                   3388:     /* if(sumnew <0.9){ */
                   3389:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   3390:     /* } */
                   3391:   }
                   3392:   k3=0.0;  /* We put the last diagonal to 0 */
                   3393:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   3394:       doldm[ii][ii]= k3;
                   3395:   }
                   3396:   /* End doldm, At the end doldm is diag[(w_i)] */
                   3397:   
1.292     brouard  3398:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   3399:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  3400: 
1.292     brouard  3401:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  3402:   /* 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  3403:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  3404:     sumnew=0.;
1.222     brouard  3405:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  3406:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  3407:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  3408:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  3409:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  3410:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  3411:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3412:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  3413:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3414:        /* }else */
1.268     brouard  3415:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   3416:     } /*End ii */
                   3417:   } /* 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 */
                   3418: 
1.292     brouard  3419:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  3420:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  3421:   /* end bmij */
1.266     brouard  3422:   return ps; /*pointer is unchanged */
1.218     brouard  3423: }
1.217     brouard  3424: /*************** transition probabilities ***************/ 
                   3425: 
1.218     brouard  3426: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  3427: {
                   3428:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3429:      computes the probability to be observed in state j being in state i by appying the
                   3430:      model to the ncovmodel covariates (including constant and age).
                   3431:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3432:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3433:      ncth covariate in the global vector x is given by the formula:
                   3434:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3435:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3436:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3437:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3438:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   3439:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3440:   */
                   3441:   double s1, lnpijopii;
                   3442:   /*double t34;*/
                   3443:   int i,j, nc, ii, jj;
                   3444: 
1.234     brouard  3445:   for(i=1; i<= nlstate; i++){
                   3446:     for(j=1; j<i;j++){
                   3447:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3448:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3449:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3450:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3451:       }
                   3452:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3453:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3454:     }
                   3455:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3456:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3457:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3458:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3459:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3460:       }
                   3461:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3462:     }
                   3463:   }
                   3464:   
                   3465:   for(i=1; i<= nlstate; i++){
                   3466:     s1=0;
                   3467:     for(j=1; j<i; j++){
                   3468:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3469:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3470:     }
                   3471:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3472:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3473:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3474:     }
                   3475:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3476:     ps[i][i]=1./(s1+1.);
                   3477:     /* Computing other pijs */
                   3478:     for(j=1; j<i; j++)
                   3479:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3480:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3481:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3482:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3483:   } /* end i */
                   3484:   
                   3485:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3486:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3487:       ps[ii][jj]=0;
                   3488:       ps[ii][ii]=1;
                   3489:     }
                   3490:   }
1.296     brouard  3491:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  3492:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3493:     s1=0.;
                   3494:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   3495:       s1+=ps[ii][jj];
                   3496:     }
                   3497:     for(ii=1; ii<= nlstate; ii++){
                   3498:       ps[ii][jj]=ps[ii][jj]/s1;
                   3499:     }
                   3500:   }
                   3501:   /* Transposition */
                   3502:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3503:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   3504:       s1=ps[ii][jj];
                   3505:       ps[ii][jj]=ps[jj][ii];
                   3506:       ps[jj][ii]=s1;
                   3507:     }
                   3508:   }
                   3509:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3510:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3511:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3512:   /*   } */
                   3513:   /*   printf("\n "); */
                   3514:   /* } */
                   3515:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3516:   /*
                   3517:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3518:     goto end;*/
                   3519:   return ps;
1.217     brouard  3520: }
                   3521: 
                   3522: 
1.126     brouard  3523: /**************** Product of 2 matrices ******************/
                   3524: 
1.145     brouard  3525: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  3526: {
                   3527:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3528:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3529:   /* in, b, out are matrice of pointers which should have been initialized 
                   3530:      before: only the contents of out is modified. The function returns
                   3531:      a pointer to pointers identical to out */
1.145     brouard  3532:   int i, j, k;
1.126     brouard  3533:   for(i=nrl; i<= nrh; i++)
1.145     brouard  3534:     for(k=ncolol; k<=ncoloh; k++){
                   3535:       out[i][k]=0.;
                   3536:       for(j=ncl; j<=nch; j++)
                   3537:        out[i][k] +=in[i][j]*b[j][k];
                   3538:     }
1.126     brouard  3539:   return out;
                   3540: }
                   3541: 
                   3542: 
                   3543: /************* Higher Matrix Product ***************/
                   3544: 
1.235     brouard  3545: 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  3546: {
1.336     brouard  3547:   /* Already optimized with precov.
                   3548:      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  3549:      'nhstepm*hstepm*stepm' months (i.e. until
                   3550:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3551:      nhstepm*hstepm matrices. 
                   3552:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3553:      (typically every 2 years instead of every month which is too big 
                   3554:      for the memory).
                   3555:      Model is determined by parameters x and covariates have to be 
                   3556:      included manually here. 
                   3557: 
                   3558:      */
                   3559: 
1.330     brouard  3560:   int i, j, d, h, k, k1;
1.131     brouard  3561:   double **out, cov[NCOVMAX+1];
1.126     brouard  3562:   double **newm;
1.187     brouard  3563:   double agexact;
1.214     brouard  3564:   double agebegin, ageend;
1.126     brouard  3565: 
                   3566:   /* Hstepm could be zero and should return the unit matrix */
                   3567:   for (i=1;i<=nlstate+ndeath;i++)
                   3568:     for (j=1;j<=nlstate+ndeath;j++){
                   3569:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3570:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3571:     }
                   3572:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3573:   for(h=1; h <=nhstepm; h++){
                   3574:     for(d=1; d <=hstepm; d++){
                   3575:       newm=savm;
                   3576:       /* Covariates have to be included here again */
                   3577:       cov[1]=1.;
1.214     brouard  3578:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3579:       cov[2]=agexact;
1.319     brouard  3580:       if(nagesqr==1){
1.227     brouard  3581:        cov[3]= agexact*agexact;
1.319     brouard  3582:       }
1.330     brouard  3583:       /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   3584:       /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   3585:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.332     brouard  3586:        if(Typevar[k1]==1){ /* A product with age */
                   3587:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   3588:        }else{
                   3589:          cov[2+nagesqr+k1]=precov[nres][k1];
                   3590:        }
                   3591:       }/* End of loop on model equation */
                   3592:        /* Old code */ 
                   3593: /*     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /\* Single dummy  *\/ */
                   3594: /* /\*    V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) *\/ */
                   3595: /* /\*       for (k=1; k<=nsd;k++) { /\\* For single dummy covariates only *\\/ *\/ */
                   3596: /* /\* /\\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\\/ *\/ */
                   3597: /*     /\* codtabm(ij,k)  (1 & (ij-1) >> (k-1))+1 *\/ */
                   3598: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3599: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3600: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
                   3601: /* /\*    nsd         1   2                              3 *\/ /\* Counting single dummies covar fixed or tv *\/ */
                   3602: /* /\*TvarsD[nsd]     4   3                              1 *\/ /\* ID of single dummy cova fixed or timevary*\/ */
                   3603: /* /\*TvarsDind[k]    2   3                              9 *\/ /\* position K of single dummy cova *\/ */
                   3604: /*       /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];or [codtabm(ij,TnsdVar[TvarsD[k]] *\/ */
                   3605: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]]; */
                   3606: /*       /\* 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]])); *\/ */
                   3607: /*       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); */
                   3608: /*       printf("hpxij new Dummy precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3609: /*     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /\* Single quantitative variables  *\/ */
                   3610: /*       /\* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline *\/ */
                   3611: /*       cov[2+nagesqr+k1]=Tqresult[nres][resultmodel[nres][k1]];  */
                   3612: /*       /\* for (k=1; k<=nsq;k++) { /\\* For single varying covariates only *\\/ *\/ */
                   3613: /*       /\*   /\\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\\/ *\/ */
                   3614: /*       /\*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   3615: /*       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]]); */
                   3616: /*       printf("hpxij new Quanti precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3617: /*     }else if( Dummy[k1]==2 ){ /\* For dummy with age product *\/ */
                   3618: /*       /\* Tvar[k1] Variable in the age product age*V1 is 1 *\/ */
                   3619: /*       /\* [Tinvresult[nres][V1] is its value in the resultline nres *\/ */
                   3620: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvar[k1]]*cov[2]; */
                   3621: /*       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]); */
                   3622: /*       printf("hpxij new Dummy with age product precov[nres=%d][k1=%d]=%.4f * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3623: 
                   3624: /*       /\* cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];    *\/ */
                   3625: /*       /\* for (k=1; k<=cptcovage;k++){ /\\* For product with age V1+V1*age +V4 +age*V3 *\\/ *\/ */
                   3626: /*       /\* 1+2 Tage[1]=2 TVar[2]=1 Dummy[2]=2, Tage[2]=4 TVar[4]=3 Dummy[4]=3 quant*\/ */
                   3627: /*       /\* *\/ */
1.330     brouard  3628: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3629: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3630: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
1.332     brouard  3631: /* /\*cptcovage=2                   1               2      *\/ */
                   3632: /* /\*Tage[k]=                      5               8      *\/  */
                   3633: /*     }else if( Dummy[k1]==3 ){ /\* For quant with age product *\/ */
                   3634: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];        */
                   3635: /*       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]]); */
                   3636: /*       printf("hpxij new Quanti with age product precov[nres=%d][k1=%d] * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3637: /*       /\* if(Dummy[Tage[k]]== 2){ /\\* dummy with age *\\/ *\/ */
                   3638: /*       /\* /\\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\\* dummy with age *\\\/ *\\/ *\/ */
                   3639: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\\/ *\/ */
                   3640: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\\/ *\/ */
                   3641: /*       /\*   cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\/ */
                   3642: /*       /\*   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); *\/ */
                   3643: /*       /\* } else if(Dummy[Tage[k]]== 3){ /\\* quantitative with age *\\/ *\/ */
                   3644: /*       /\*   cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; *\/ */
                   3645: /*       /\* } *\/ */
                   3646: /*       /\* 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]); *\/ */
                   3647: /*     }else if(Typevar[k1]==2 ){ /\* For product (not with age) *\/ */
                   3648: /* /\*       for (k=1; k<=cptcovprod;k++){ /\\*  For product without age *\\/ *\/ */
                   3649: /* /\* /\\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\\/ *\/ */
                   3650: /* /\* /\\*    k        1  2   3   4     5    6    7     8    9 *\\/ *\/ */
                   3651: /* /\* /\\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\\/ *\/ */
                   3652: /* /\* /\\*cptcovprod=1            1               2            *\\/ *\/ */
                   3653: /* /\* /\\*Tprod[]=                4               7            *\\/ *\/ */
                   3654: /* /\* /\\*Tvard[][1]             4               1             *\\/ *\/ */
                   3655: /* /\* /\\*Tvard[][2]               3               2           *\\/ *\/ */
1.330     brouard  3656:          
1.332     brouard  3657: /*       /\* 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])]); *\/ */
                   3658: /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3659: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];     */
                   3660: /*       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]]); */
                   3661: /*       printf("hpxij new Product no age product precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3662: 
                   3663: /*       /\* if(Dummy[Tvardk[k1][1]]==0){ *\/ */
                   3664: /*       /\*   if(Dummy[Tvardk[k1][2]]==0){ /\\* Product of dummies *\\/ *\/ */
                   3665: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3666: /*           /\* cov[2+nagesqr+k1]=Tinvresult[nres][Tvardk[k1][1]] * Tinvresult[nres][Tvardk[k1][2]];   *\/ */
                   3667: /*           /\* 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]])]; *\/ */
                   3668: /*         /\* }else{ /\\* Product of dummy by quantitative *\\/ *\/ */
                   3669: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,TnsdVar[Tvard[k][1]])] * Tqresult[nres][k]; *\/ */
                   3670: /*           /\* cov[2+nagesqr+k1]=Tresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]; *\/ */
                   3671: /*       /\*   } *\/ */
                   3672: /*       /\* }else{ /\\* Product of quantitative by...*\\/ *\/ */
                   3673: /*       /\*   if(Dummy[Tvard[k][2]]==0){  /\\* quant by dummy *\\/ *\/ */
                   3674: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][Tvard[k][1]]; *\\/ *\/ */
                   3675: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3676: /*       /\*   }else{ /\\* Product of two quant *\\/ *\/ */
                   3677: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\\/ *\/ */
                   3678: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3679: /*       /\*   } *\/ */
                   3680: /*       /\* }/\\*end of products quantitative *\\/ *\/ */
                   3681: /*     }/\*end of products *\/ */
                   3682:       /* } /\* End of loop on model equation *\/ */
1.235     brouard  3683:       /* for (k=1; k<=cptcovn;k++)  */
                   3684:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3685:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3686:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3687:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3688:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3689:       
                   3690:       
1.126     brouard  3691:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3692:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.319     brouard  3693:       /* right multiplication of oldm by the current matrix */
1.126     brouard  3694:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3695:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3696:       /* if((int)age == 70){ */
                   3697:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3698:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3699:       /*         printf("%d pmmij ",i); */
                   3700:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3701:       /*           printf("%f ",pmmij[i][j]); */
                   3702:       /*         } */
                   3703:       /*         printf(" oldm "); */
                   3704:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3705:       /*           printf("%f ",oldm[i][j]); */
                   3706:       /*         } */
                   3707:       /*         printf("\n"); */
                   3708:       /*       } */
                   3709:       /* } */
1.126     brouard  3710:       savm=oldm;
                   3711:       oldm=newm;
                   3712:     }
                   3713:     for(i=1; i<=nlstate+ndeath; i++)
                   3714:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  3715:        po[i][j][h]=newm[i][j];
                   3716:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3717:       }
1.128     brouard  3718:     /*printf("h=%d ",h);*/
1.126     brouard  3719:   } /* end h */
1.267     brouard  3720:   /*     printf("\n H=%d \n",h); */
1.126     brouard  3721:   return po;
                   3722: }
                   3723: 
1.217     brouard  3724: /************* Higher Back Matrix Product ***************/
1.218     brouard  3725: /* 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  3726: 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  3727: {
1.332     brouard  3728:   /* For dummy covariates given in each resultline (for historical, computes the corresponding combination ij),
                   3729:      computes the transition matrix starting at age 'age' over
1.217     brouard  3730:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3731:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3732:      nhstepm*hstepm matrices.
                   3733:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3734:      (typically every 2 years instead of every month which is too big
1.217     brouard  3735:      for the memory).
1.218     brouard  3736:      Model is determined by parameters x and covariates have to be
1.266     brouard  3737:      included manually here. Then we use a call to bmij(x and cov)
                   3738:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  3739:   */
1.217     brouard  3740: 
1.332     brouard  3741:   int i, j, d, h, k, k1;
1.266     brouard  3742:   double **out, cov[NCOVMAX+1], **bmij();
                   3743:   double **newm, ***newmm;
1.217     brouard  3744:   double agexact;
                   3745:   double agebegin, ageend;
1.222     brouard  3746:   double **oldm, **savm;
1.217     brouard  3747: 
1.266     brouard  3748:   newmm=po; /* To be saved */
                   3749:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  3750:   /* Hstepm could be zero and should return the unit matrix */
                   3751:   for (i=1;i<=nlstate+ndeath;i++)
                   3752:     for (j=1;j<=nlstate+ndeath;j++){
                   3753:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3754:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3755:     }
                   3756:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3757:   for(h=1; h <=nhstepm; h++){
                   3758:     for(d=1; d <=hstepm; d++){
                   3759:       newm=savm;
                   3760:       /* Covariates have to be included here again */
                   3761:       cov[1]=1.;
1.271     brouard  3762:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  3763:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
1.318     brouard  3764:         /* Debug */
                   3765:       /* printf("hBxij age=%lf, agexact=%lf\n", age, agexact); */
1.217     brouard  3766:       cov[2]=agexact;
1.332     brouard  3767:       if(nagesqr==1){
1.222     brouard  3768:        cov[3]= agexact*agexact;
1.332     brouard  3769:       }
                   3770:       /** New code */
                   3771:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   3772:        if(Typevar[k1]==1){ /* A product with age */
                   3773:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.325     brouard  3774:        }else{
1.332     brouard  3775:          cov[2+nagesqr+k1]=precov[nres][k1];
1.325     brouard  3776:        }
1.332     brouard  3777:       }/* End of loop on model equation */
                   3778:       /** End of new code */
                   3779:   /** This was old code */
                   3780:       /* for (k=1; k<=nsd;k++){ /\* For single dummy covariates only *\//\* cptcovn error *\/ */
                   3781:       /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3782:       /* /\* /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3783:       /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])];/\* Bug valgrind *\/ */
                   3784:       /*   /\* 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)); *\/ */
                   3785:       /* } */
                   3786:       /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3787:       /*       /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3788:       /*       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3789:       /*       /\* 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]); *\/ */
                   3790:       /* } */
                   3791:       /* for (k=1; k<=cptcovage;k++){ /\* Should start at cptcovn+1 *\//\* For product with age *\/ */
                   3792:       /*       /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age error!!!*\\/ *\/ */
                   3793:       /*       if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3794:       /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3795:       /*       } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3796:       /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];  */
                   3797:       /*       } */
                   3798:       /*       /\* 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]); *\/ */
                   3799:       /* } */
                   3800:       /* for (k=1; k<=cptcovprod;k++){ /\* Useless because included in cptcovn *\/ */
                   3801:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3802:       /*       if(Dummy[Tvard[k][1]]==0){ */
                   3803:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3804:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][1])]; */
                   3805:       /*         }else{ */
                   3806:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3807:       /*         } */
                   3808:       /*       }else{ */
                   3809:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3810:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3811:       /*         }else{ */
                   3812:       /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3813:       /*         } */
                   3814:       /*       } */
                   3815:       /* }                      */
                   3816:       /* /\*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*\/ */
                   3817:       /* /\*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*\/ */
                   3818: /** End of old code */
                   3819:       
1.218     brouard  3820:       /* Careful transposed matrix */
1.266     brouard  3821:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  3822:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3823:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3824:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.325     brouard  3825:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);/* Bug valgrind */
1.217     brouard  3826:       /* if((int)age == 70){ */
                   3827:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3828:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3829:       /*         printf("%d pmmij ",i); */
                   3830:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3831:       /*           printf("%f ",pmmij[i][j]); */
                   3832:       /*         } */
                   3833:       /*         printf(" oldm "); */
                   3834:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3835:       /*           printf("%f ",oldm[i][j]); */
                   3836:       /*         } */
                   3837:       /*         printf("\n"); */
                   3838:       /*       } */
                   3839:       /* } */
                   3840:       savm=oldm;
                   3841:       oldm=newm;
                   3842:     }
                   3843:     for(i=1; i<=nlstate+ndeath; i++)
                   3844:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3845:        po[i][j][h]=newm[i][j];
1.268     brouard  3846:        /* if(h==nhstepm) */
                   3847:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  3848:       }
1.268     brouard  3849:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  3850:   } /* end h */
1.268     brouard  3851:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  3852:   return po;
                   3853: }
                   3854: 
                   3855: 
1.162     brouard  3856: #ifdef NLOPT
                   3857:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3858:   double fret;
                   3859:   double *xt;
                   3860:   int j;
                   3861:   myfunc_data *d2 = (myfunc_data *) pd;
                   3862: /* xt = (p1-1); */
                   3863:   xt=vector(1,n); 
                   3864:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3865: 
                   3866:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3867:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3868:   printf("Function = %.12lf ",fret);
                   3869:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3870:   printf("\n");
                   3871:  free_vector(xt,1,n);
                   3872:   return fret;
                   3873: }
                   3874: #endif
1.126     brouard  3875: 
                   3876: /*************** log-likelihood *************/
                   3877: double func( double *x)
                   3878: {
1.336     brouard  3879:   int i, ii, j, k, mi, d, kk, kf=0;
1.226     brouard  3880:   int ioffset=0;
1.339     brouard  3881:   int ipos=0,iposold=0,ncovv=0;
                   3882: 
1.340   ! brouard  3883:   double cotvarv, cotvarvold;
1.226     brouard  3884:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3885:   double **out;
                   3886:   double lli; /* Individual log likelihood */
                   3887:   int s1, s2;
1.228     brouard  3888:   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  3889: 
1.226     brouard  3890:   double bbh, survp;
                   3891:   double agexact;
1.336     brouard  3892:   double agebegin, ageend;
1.226     brouard  3893:   /*extern weight */
                   3894:   /* We are differentiating ll according to initial status */
                   3895:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3896:   /*for(i=1;i<imx;i++) 
                   3897:     printf(" %d\n",s[4][i]);
                   3898:   */
1.162     brouard  3899: 
1.226     brouard  3900:   ++countcallfunc;
1.162     brouard  3901: 
1.226     brouard  3902:   cov[1]=1.;
1.126     brouard  3903: 
1.226     brouard  3904:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3905:   ioffset=0;
1.226     brouard  3906:   if(mle==1){
                   3907:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3908:       /* Computes the values of the ncovmodel covariates of the model
                   3909:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3910:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   3911:         to be observed in j being in i according to the model.
                   3912:       */
1.243     brouard  3913:       ioffset=2+nagesqr ;
1.233     brouard  3914:    /* Fixed */
1.336     brouard  3915:       for (kf=1; kf<=ncovf;kf++){ /* For each fixed covariate dummu or quant or prod */
1.319     brouard  3916:        /* # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi */
                   3917:         /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   3918:        /*  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  3919:         /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.336     brouard  3920:        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  3921:        /* V1*V2 (7)  TvarFind[2]=7, TvarFind[3]=9 */
1.234     brouard  3922:       }
1.226     brouard  3923:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.319     brouard  3924:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
1.226     brouard  3925:         has been calculated etc */
                   3926:       /* For an individual i, wav[i] gives the number of effective waves */
                   3927:       /* We compute the contribution to Likelihood of each effective transition
                   3928:         mw[mi][i] is real wave of the mi th effectve wave */
                   3929:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   3930:         s2=s[mw[mi+1][i]][i];
1.340   ! brouard  3931:         And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv-ncovcol-nqv][i] because (-ncovcol-nqv) in the data
1.226     brouard  3932:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   3933:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   3934:       */
1.336     brouard  3935:       for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
                   3936:       /* Wave varying (but not age varying) */
1.339     brouard  3937:        /* 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*\/ */
                   3938:        /*   /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; but where is the crossproduct? *\/ */
                   3939:        /*   cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   3940:        /* } */
1.340   ! brouard  3941:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age )*/
        !          3942:          itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
        !          3943:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
        !          3944:          if(TvarFind[itv]==0){ /* Not a fixed covariate */
        !          3945:            cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]-ncovcol-nqv][i];  /* cotvar[wav][ntv+iv][i] */
        !          3946:          }else{ /* fixed covariate */
        !          3947:            cotvarv=covar[Tvar[TvarFind[itv]]][i];
        !          3948:          }
1.339     brouard  3949:          if(ipos!=iposold){ /* Not a product or first of a product */
1.340   ! brouard  3950:            cotvarvold=cotvarv;
        !          3951:          }else{ /* A second product */
        !          3952:            cotvarv=cotvarv*cotvarvold;
1.339     brouard  3953:          }
                   3954:          iposold=ipos;
1.340   ! brouard  3955:          cov[ioffset+ipos]=cotvarv;
1.234     brouard  3956:        }
1.339     brouard  3957:        /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
                   3958:        /*   iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3959:        /*   cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
                   3960:        /*   k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
                   3961:        /*   cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
                   3962:        /*   printf(" i=%d,mi=%d,itv=%d,TmodelInvind[itv]=%d,cotvar[mw[mi][i]][TmodelInvind[itv]][i]=%f\n", i, mi, itv, TmodelInvind[itv],cotvar[mw[mi][i]][TmodelInvind[itv]][i]); */
                   3963:        /* } */
                   3964:        /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
                   3965:        /*   iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3966:        /*   /\* 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]); *\/ */
                   3967:        /*   cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
                   3968:        /* } */
                   3969:        /* for products of time varying to be done */
1.234     brouard  3970:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3971:          for (j=1;j<=nlstate+ndeath;j++){
                   3972:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3973:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3974:          }
1.336     brouard  3975: 
                   3976:        agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   3977:        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  3978:        for(d=0; d<dh[mi][i]; d++){
                   3979:          newm=savm;
                   3980:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3981:          cov[2]=agexact;
                   3982:          if(nagesqr==1)
                   3983:            cov[3]= agexact*agexact;  /* Should be changed here */
                   3984:          for (kk=1; kk<=cptcovage;kk++) {
1.318     brouard  3985:            if(!FixedV[Tvar[Tage[kk]]])
                   3986:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   3987:            else
1.340   ! brouard  3988:              cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact; /* -ntv because cotvar starts at ntv */ 
1.234     brouard  3989:          }
                   3990:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3991:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3992:          savm=oldm;
                   3993:          oldm=newm;
                   3994:        } /* end mult */
                   3995:        
                   3996:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   3997:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   3998:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   3999:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   4000:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   4001:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   4002:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   4003:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  4004:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   4005:                                 * -stepm/2 to stepm/2 .
                   4006:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   4007:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   4008:                                 */
1.234     brouard  4009:        s1=s[mw[mi][i]][i];
                   4010:        s2=s[mw[mi+1][i]][i];
                   4011:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4012:        /* bias bh is positive if real duration
                   4013:         * is higher than the multiple of stepm and negative otherwise.
                   4014:         */
                   4015:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   4016:        if( s2 > nlstate){ 
                   4017:          /* i.e. if s2 is a death state and if the date of death is known 
                   4018:             then the contribution to the likelihood is the probability to 
                   4019:             die between last step unit time and current  step unit time, 
                   4020:             which is also equal to probability to die before dh 
                   4021:             minus probability to die before dh-stepm . 
                   4022:             In version up to 0.92 likelihood was computed
                   4023:             as if date of death was unknown. Death was treated as any other
                   4024:             health state: the date of the interview describes the actual state
                   4025:             and not the date of a change in health state. The former idea was
                   4026:             to consider that at each interview the state was recorded
                   4027:             (healthy, disable or death) and IMaCh was corrected; but when we
                   4028:             introduced the exact date of death then we should have modified
                   4029:             the contribution of an exact death to the likelihood. This new
                   4030:             contribution is smaller and very dependent of the step unit
                   4031:             stepm. It is no more the probability to die between last interview
                   4032:             and month of death but the probability to survive from last
                   4033:             interview up to one month before death multiplied by the
                   4034:             probability to die within a month. Thanks to Chris
                   4035:             Jackson for correcting this bug.  Former versions increased
                   4036:             mortality artificially. The bad side is that we add another loop
                   4037:             which slows down the processing. The difference can be up to 10%
                   4038:             lower mortality.
                   4039:          */
                   4040:          /* If, at the beginning of the maximization mostly, the
                   4041:             cumulative probability or probability to be dead is
                   4042:             constant (ie = 1) over time d, the difference is equal to
                   4043:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   4044:             s1 at precedent wave, to be dead a month before current
                   4045:             wave is equal to probability, being at state s1 at
                   4046:             precedent wave, to be dead at mont of the current
                   4047:             wave. Then the observed probability (that this person died)
                   4048:             is null according to current estimated parameter. In fact,
                   4049:             it should be very low but not zero otherwise the log go to
                   4050:             infinity.
                   4051:          */
1.183     brouard  4052: /* #ifdef INFINITYORIGINAL */
                   4053: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4054: /* #else */
                   4055: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   4056: /*         lli=log(mytinydouble); */
                   4057: /*       else */
                   4058: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4059: /* #endif */
1.226     brouard  4060:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4061:          
1.226     brouard  4062:        } else if  ( s2==-1 ) { /* alive */
                   4063:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4064:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4065:          /*survp += out[s1][j]; */
                   4066:          lli= log(survp);
                   4067:        }
1.336     brouard  4068:        /* else if  (s2==-4) {  */
                   4069:        /*   for (j=3,survp=0. ; j<=nlstate; j++)   */
                   4070:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4071:        /*   lli= log(survp);  */
                   4072:        /* }  */
                   4073:        /* else if  (s2==-5) {  */
                   4074:        /*   for (j=1,survp=0. ; j<=2; j++)   */
                   4075:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4076:        /*   lli= log(survp);  */
                   4077:        /* }  */
1.226     brouard  4078:        else{
                   4079:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4080:          /*  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 */
                   4081:        } 
                   4082:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   4083:        /*if(lli ==000.0)*/
1.340   ! brouard  4084:        /* 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  4085:        ipmx +=1;
                   4086:        sw += weight[i];
                   4087:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4088:        /* if (lli < log(mytinydouble)){ */
                   4089:        /*   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); */
                   4090:        /*   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]); */
                   4091:        /* } */
                   4092:       } /* end of wave */
                   4093:     } /* end of individual */
                   4094:   }  else if(mle==2){
                   4095:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.319     brouard  4096:       ioffset=2+nagesqr ;
                   4097:       for (k=1; k<=ncovf;k++)
                   4098:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];
1.226     brouard  4099:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  4100:        for(k=1; k <= ncovv ; k++){
1.340   ! brouard  4101:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; /* Cotvar starts at ntv */
1.319     brouard  4102:        }
1.226     brouard  4103:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4104:          for (j=1;j<=nlstate+ndeath;j++){
                   4105:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4106:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4107:          }
                   4108:        for(d=0; d<=dh[mi][i]; d++){
                   4109:          newm=savm;
                   4110:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4111:          cov[2]=agexact;
                   4112:          if(nagesqr==1)
                   4113:            cov[3]= agexact*agexact;
                   4114:          for (kk=1; kk<=cptcovage;kk++) {
                   4115:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4116:          }
                   4117:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4118:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4119:          savm=oldm;
                   4120:          oldm=newm;
                   4121:        } /* end mult */
                   4122:       
                   4123:        s1=s[mw[mi][i]][i];
                   4124:        s2=s[mw[mi+1][i]][i];
                   4125:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4126:        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 */
                   4127:        ipmx +=1;
                   4128:        sw += weight[i];
                   4129:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4130:       } /* end of wave */
                   4131:     } /* end of individual */
                   4132:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   4133:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4134:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4135:       for(mi=1; mi<= wav[i]-1; mi++){
                   4136:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4137:          for (j=1;j<=nlstate+ndeath;j++){
                   4138:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4139:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4140:          }
                   4141:        for(d=0; d<dh[mi][i]; d++){
                   4142:          newm=savm;
                   4143:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4144:          cov[2]=agexact;
                   4145:          if(nagesqr==1)
                   4146:            cov[3]= agexact*agexact;
                   4147:          for (kk=1; kk<=cptcovage;kk++) {
1.340   ! brouard  4148:            if(!FixedV[Tvar[Tage[kk]]])
        !          4149:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
        !          4150:            else
        !          4151:              cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact; /* -ntv because cotvar starts at ntv */ 
1.226     brouard  4152:          }
                   4153:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4154:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4155:          savm=oldm;
                   4156:          oldm=newm;
                   4157:        } /* end mult */
                   4158:       
                   4159:        s1=s[mw[mi][i]][i];
                   4160:        s2=s[mw[mi+1][i]][i];
                   4161:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4162:        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 */
                   4163:        ipmx +=1;
                   4164:        sw += weight[i];
                   4165:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4166:       } /* end of wave */
                   4167:     } /* end of individual */
                   4168:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   4169:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4170:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4171:       for(mi=1; mi<= wav[i]-1; mi++){
                   4172:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4173:          for (j=1;j<=nlstate+ndeath;j++){
                   4174:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4175:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4176:          }
                   4177:        for(d=0; d<dh[mi][i]; d++){
                   4178:          newm=savm;
                   4179:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4180:          cov[2]=agexact;
                   4181:          if(nagesqr==1)
                   4182:            cov[3]= agexact*agexact;
                   4183:          for (kk=1; kk<=cptcovage;kk++) {
                   4184:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4185:          }
1.126     brouard  4186:        
1.226     brouard  4187:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4188:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4189:          savm=oldm;
                   4190:          oldm=newm;
                   4191:        } /* end mult */
                   4192:       
                   4193:        s1=s[mw[mi][i]][i];
                   4194:        s2=s[mw[mi+1][i]][i];
                   4195:        if( s2 > nlstate){ 
                   4196:          lli=log(out[s1][s2] - savm[s1][s2]);
                   4197:        } else if  ( s2==-1 ) { /* alive */
                   4198:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4199:            survp += out[s1][j];
                   4200:          lli= log(survp);
                   4201:        }else{
                   4202:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4203:        }
                   4204:        ipmx +=1;
                   4205:        sw += weight[i];
                   4206:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.340   ! brouard  4207:        /* 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]); */
1.226     brouard  4208:       } /* end of wave */
                   4209:     } /* end of individual */
                   4210:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   4211:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4212:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4213:       for(mi=1; mi<= wav[i]-1; mi++){
                   4214:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4215:          for (j=1;j<=nlstate+ndeath;j++){
                   4216:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4217:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4218:          }
                   4219:        for(d=0; d<dh[mi][i]; d++){
                   4220:          newm=savm;
                   4221:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4222:          cov[2]=agexact;
                   4223:          if(nagesqr==1)
                   4224:            cov[3]= agexact*agexact;
                   4225:          for (kk=1; kk<=cptcovage;kk++) {
1.340   ! brouard  4226:            if(!FixedV[Tvar[Tage[kk]]])
        !          4227:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
        !          4228:            else
        !          4229:              cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact; /* -ntv because cotvar starts at ntv */ 
1.226     brouard  4230:          }
1.126     brouard  4231:        
1.226     brouard  4232:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4233:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4234:          savm=oldm;
                   4235:          oldm=newm;
                   4236:        } /* end mult */
                   4237:       
                   4238:        s1=s[mw[mi][i]][i];
                   4239:        s2=s[mw[mi+1][i]][i];
                   4240:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4241:        ipmx +=1;
                   4242:        sw += weight[i];
                   4243:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4244:        /*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]);*/
                   4245:       } /* end of wave */
                   4246:     } /* end of individual */
                   4247:   } /* End of if */
                   4248:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   4249:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   4250:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4251:   return -l;
1.126     brouard  4252: }
                   4253: 
                   4254: /*************** log-likelihood *************/
                   4255: double funcone( double *x)
                   4256: {
1.228     brouard  4257:   /* Same as func but slower because of a lot of printf and if */
1.335     brouard  4258:   int i, ii, j, k, mi, d, kk, kf=0;
1.228     brouard  4259:   int ioffset=0;
1.339     brouard  4260:   int ipos=0,iposold=0,ncovv=0;
                   4261: 
1.340   ! brouard  4262:   double cotvarv, cotvarvold;
1.131     brouard  4263:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  4264:   double **out;
                   4265:   double lli; /* Individual log likelihood */
                   4266:   double llt;
                   4267:   int s1, s2;
1.228     brouard  4268:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   4269: 
1.126     brouard  4270:   double bbh, survp;
1.187     brouard  4271:   double agexact;
1.214     brouard  4272:   double agebegin, ageend;
1.126     brouard  4273:   /*extern weight */
                   4274:   /* We are differentiating ll according to initial status */
                   4275:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   4276:   /*for(i=1;i<imx;i++) 
                   4277:     printf(" %d\n",s[4][i]);
                   4278:   */
                   4279:   cov[1]=1.;
                   4280: 
                   4281:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  4282:   ioffset=0;
                   4283:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.336     brouard  4284:     /* Computes the values of the ncovmodel covariates of the model
                   4285:        depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   4286:        Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   4287:        to be observed in j being in i according to the model.
                   4288:     */
1.243     brouard  4289:     /* ioffset=2+nagesqr+cptcovage; */
                   4290:     ioffset=2+nagesqr;
1.232     brouard  4291:     /* Fixed */
1.224     brouard  4292:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  4293:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
1.335     brouard  4294:     for (kf=1; kf<=ncovf;kf++){ /* Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
1.339     brouard  4295:       /* printf("Debug3 TvarFind[%d]=%d",kf, TvarFind[kf]); */
                   4296:       /* printf(" Tvar[TvarFind[kf]]=%d", Tvar[TvarFind[kf]]); */
                   4297:       /* printf(" i=%d covar[Tvar[TvarFind[kf]]][i]=%f\n",i,covar[Tvar[TvarFind[kf]]][i]); */
1.335     brouard  4298:       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  4299: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   4300: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   4301: /*    cov[2+6]=covar[2][i]; V2  */
                   4302: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   4303: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   4304: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   4305: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   4306: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   4307: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  4308:     }
1.336     brouard  4309:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   4310:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
                   4311:         has been calculated etc */
                   4312:       /* For an individual i, wav[i] gives the number of effective waves */
                   4313:       /* We compute the contribution to Likelihood of each effective transition
                   4314:         mw[mi][i] is real wave of the mi th effectve wave */
                   4315:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   4316:         s2=s[mw[mi+1][i]][i];
1.340   ! brouard  4317:         And the iv th varying covariate in the DATA is the cotvar[mw[mi+1][i]][iv][i]
1.336     brouard  4318:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   4319:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   4320:       */
                   4321:     /* This part may be useless now because everythin should be in covar */
1.232     brouard  4322:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   4323:     /*   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?)*\/ */
                   4324:     /* } */
1.231     brouard  4325:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   4326:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   4327:     /* } */
1.225     brouard  4328:     
1.233     brouard  4329: 
                   4330:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.339     brouard  4331:       /* 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 */
                   4332:       /* for(k=1; k <= ncovv ; k++){ /\* Varying  covariates (single and product but no age )*\/ */
                   4333:       /*       /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; *\/ */
                   4334:       /*       cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   4335:       /* } */
                   4336:       
                   4337:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   4338:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   4339:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   4340:       /*  TvarVV[1]=V3 (first time varying in the model equation, TvarVV[2]=V1 (in V1*V3) TvarVV[3]=3(V3)  */
                   4341:       /* We need the position of the time varying or product in the model */
                   4342:       /* 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 */            
                   4343:       /* TvarVV gives the variable name */
1.340   ! brouard  4344:       /* Other example V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
        !          4345:       *      k=         1   2     3     4         5        6        7       8        9
        !          4346:       *  varying            1     2                                 3       4        5
        !          4347:       *  ncovv              1     2                                3 4     5 6      7 8
        !          4348:       *  TvarVV            V3     5                                1 3     3 5      1 5
        !          4349:       * TvarVVind           2     3                                7 7     8 8      9 9
        !          4350:       * TvarFind[k]     1   0     0     0         0        0        0       0        0
        !          4351:       * cotvar starts at ntv=2 (because of V3 V4)
        !          4352:       */
        !          4353:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age) including individual from products */
        !          4354:        itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
        !          4355:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
        !          4356:        if(TvarFind[itv]==0){ /* Not a fixed covariate */
        !          4357:          cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]-ncovcol-nqv][i];  /* cotvar[wav][ntv+iv][i] */
        !          4358:        }else{ /* fixed covariate */
        !          4359:          cotvarv=covar[Tvar[TvarFind[itv]]][i];
        !          4360:        }
1.339     brouard  4361:        if(ipos!=iposold){ /* Not a product or first of a product */
1.340   ! brouard  4362:          cotvarvold=cotvarv;
        !          4363:        }else{ /* A second product */
        !          4364:          cotvarv=cotvarv*cotvarvold;
1.339     brouard  4365:        }
                   4366:        iposold=ipos;
1.340   ! brouard  4367:        cov[ioffset+ipos]=cotvarv;
1.339     brouard  4368:        /* For products */
                   4369:       }
                   4370:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates single *\/ */
                   4371:       /*       iv=TvarVDind[itv]; /\* iv, position in the model equation of time varying covariate itv *\/ */
                   4372:       /*       /\*         "V1+V3+age*V1+age*V3+V1*V3" with V3 time varying *\/ */
                   4373:       /*       /\*           1  2   3      4      5                         *\/ */
                   4374:       /*       /\*itv           1                                           *\/ */
                   4375:       /*       /\* TvarVInd[1]= 2                                           *\/ */
                   4376:       /*       /\* iv= Tvar[Tmodelind[itv]]-ncovcol-nqv;  /\\* Counting the # varying covariate from 1 to ntveff *\\/ *\/ */
                   4377:       /*       /\* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; *\/ */
                   4378:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; *\/ */
                   4379:       /*       /\* k=ioffset-2-nagesqr-cptcovage+itv; /\\* position in simple model *\\/ *\/ */
                   4380:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; *\/ */
                   4381:       /*       cov[ioffset+iv]=cotvar[mw[mi][i]][itv][i]; */
                   4382:       /*       /\* 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]); *\/ */
                   4383:       /* } */
1.232     brouard  4384:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  4385:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4386:       /*       /\* 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]); *\/ */
                   4387:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  4388:       /* } */
1.126     brouard  4389:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  4390:        for (j=1;j<=nlstate+ndeath;j++){
                   4391:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4392:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4393:        }
1.214     brouard  4394:       
                   4395:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4396:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   4397:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  4398:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  4399:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4400:          and mw[mi+1][i]. dh depends on stepm.*/
                   4401:        newm=savm;
1.247     brouard  4402:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  4403:        cov[2]=agexact;
                   4404:        if(nagesqr==1)
                   4405:          cov[3]= agexact*agexact;
                   4406:        for (kk=1; kk<=cptcovage;kk++) {
                   4407:          if(!FixedV[Tvar[Tage[kk]]])
                   4408:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4409:          else
1.340   ! brouard  4410:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
1.242     brouard  4411:        }
                   4412:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   4413:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4414:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4415:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4416:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   4417:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   4418:        savm=oldm;
                   4419:        oldm=newm;
1.126     brouard  4420:       } /* end mult */
1.336     brouard  4421:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   4422:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   4423:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   4424:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   4425:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   4426:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   4427:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   4428:         * probability in order to take into account the bias as a fraction of the way
                   4429:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   4430:                                 * -stepm/2 to stepm/2 .
                   4431:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   4432:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   4433:                                 */
1.126     brouard  4434:       s1=s[mw[mi][i]][i];
                   4435:       s2=s[mw[mi+1][i]][i];
1.217     brouard  4436:       /* if(s2==-1){ */
1.268     brouard  4437:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  4438:       /*       /\* exit(1); *\/ */
                   4439:       /* } */
1.126     brouard  4440:       bbh=(double)bh[mi][i]/(double)stepm; 
                   4441:       /* bias is positive if real duration
                   4442:        * is higher than the multiple of stepm and negative otherwise.
                   4443:        */
                   4444:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  4445:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4446:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  4447:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   4448:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4449:        lli= log(survp);
1.126     brouard  4450:       }else if (mle==1){
1.242     brouard  4451:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  4452:       } else if(mle==2){
1.242     brouard  4453:        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  4454:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  4455:        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  4456:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  4457:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  4458:       } else{  /* mle=0 back to 1 */
1.242     brouard  4459:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4460:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  4461:       } /* End of if */
                   4462:       ipmx +=1;
                   4463:       sw += weight[i];
                   4464:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.340   ! brouard  4465:       printf("Funcone num[i]=%ld i=%6d V= ", num[i], i);
        !          4466:       for (kf=1; kf<=ncovf;kf++){ /* Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
        !          4467:        printf("%g",covar[Tvar[TvarFind[kf]]][i]);
        !          4468:       }
        !          4469:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age) including individual from products */
        !          4470:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
        !          4471:        if(ipos!=iposold){ /* Not a product or first of a product */
        !          4472:          printf(" %g",cov[ioffset+ipos]);
        !          4473:        }else{
        !          4474:          printf("*");
        !          4475:        }
        !          4476:        iposold=ipos;
        !          4477:       }
        !          4478:       for (kk=1; kk<=cptcovage;kk++) {
        !          4479:        if(!FixedV[Tvar[Tage[kk]]])
        !          4480:          printf(" %g*age",covar[Tvar[Tage[kk]]][i]);
        !          4481:        else
        !          4482:          printf(" %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]);
        !          4483:       }
        !          4484:       printf(" s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",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  4485:       if(globpr){
1.246     brouard  4486:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  4487:  %11.6f %11.6f %11.6f ", \
1.242     brouard  4488:                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  4489:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.335     brouard  4490:  /*    printf("%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\ */
                   4491:  /* %11.6f %11.6f %11.6f ", \ */
                   4492:  /*            num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw, */
                   4493:  /*            2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
1.242     brouard  4494:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   4495:          llt +=ll[k]*gipmx/gsw;
                   4496:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
1.335     brouard  4497:          /* printf(" %10.6f",-ll[k]*gipmx/gsw); */
1.242     brouard  4498:        }
                   4499:        fprintf(ficresilk," %10.6f\n", -llt);
1.335     brouard  4500:        /* printf(" %10.6f\n", -llt); */
1.126     brouard  4501:       }
1.335     brouard  4502:     } /* end of wave */
                   4503:   } /* end of individual */
                   4504:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
1.232     brouard  4505: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
1.335     brouard  4506:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4507:   if(globpr==0){ /* First time we count the contributions and weights */
                   4508:     gipmx=ipmx;
                   4509:     gsw=sw;
                   4510:   }
1.232     brouard  4511: return -l;
1.126     brouard  4512: }
                   4513: 
                   4514: 
                   4515: /*************** function likelione ***********/
1.292     brouard  4516: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  4517: {
                   4518:   /* This routine should help understanding what is done with 
                   4519:      the selection of individuals/waves and
                   4520:      to check the exact contribution to the likelihood.
                   4521:      Plotting could be done.
                   4522:    */
                   4523:   int k;
                   4524: 
                   4525:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  4526:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  4527:     strcat(fileresilk,fileresu);
1.126     brouard  4528:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   4529:       printf("Problem with resultfile: %s\n", fileresilk);
                   4530:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   4531:     }
1.214     brouard  4532:     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");
                   4533:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  4534:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   4535:     for(k=1; k<=nlstate; k++) 
                   4536:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   4537:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   4538:   }
                   4539: 
1.292     brouard  4540:   *fretone=(*func)(p);
1.126     brouard  4541:   if(*globpri !=0){
                   4542:     fclose(ficresilk);
1.205     brouard  4543:     if (mle ==0)
                   4544:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   4545:     else if(mle >=1)
                   4546:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   4547:     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  4548:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  4549:       
                   4550:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  4551:       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> \
1.208     brouard  4552: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   4553:     }
1.207     brouard  4554:     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.204     brouard  4555: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4556:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  4557: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4558:     fflush(fichtm);
1.205     brouard  4559:   }
1.126     brouard  4560:   return;
                   4561: }
                   4562: 
                   4563: 
                   4564: /*********** Maximum Likelihood Estimation ***************/
                   4565: 
                   4566: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   4567: {
1.319     brouard  4568:   int i,j,k, jk, jkk=0, iter=0;
1.126     brouard  4569:   double **xi;
                   4570:   double fret;
                   4571:   double fretone; /* Only one call to likelihood */
                   4572:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  4573: 
                   4574: #ifdef NLOPT
                   4575:   int creturn;
                   4576:   nlopt_opt opt;
                   4577:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   4578:   double *lb;
                   4579:   double minf; /* the minimum objective value, upon return */
                   4580:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   4581:   myfunc_data dinst, *d = &dinst;
                   4582: #endif
                   4583: 
                   4584: 
1.126     brouard  4585:   xi=matrix(1,npar,1,npar);
                   4586:   for (i=1;i<=npar;i++)
                   4587:     for (j=1;j<=npar;j++)
                   4588:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   4589:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  4590:   strcpy(filerespow,"POW_"); 
1.126     brouard  4591:   strcat(filerespow,fileres);
                   4592:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   4593:     printf("Problem with resultfile: %s\n", filerespow);
                   4594:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   4595:   }
                   4596:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   4597:   for (i=1;i<=nlstate;i++)
                   4598:     for(j=1;j<=nlstate+ndeath;j++)
                   4599:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   4600:   fprintf(ficrespow,"\n");
1.162     brouard  4601: #ifdef POWELL
1.319     brouard  4602: #ifdef LINMINORIGINAL
                   4603: #else /* LINMINORIGINAL */
                   4604:   
                   4605:   flatdir=ivector(1,npar); 
                   4606:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   4607: #endif /*LINMINORIGINAL */
                   4608: 
                   4609: #ifdef FLATSUP
                   4610:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4611:   /* reorganizing p by suppressing flat directions */
                   4612:   for(i=1, jk=1; i <=nlstate; i++){
                   4613:     for(k=1; k <=(nlstate+ndeath); k++){
                   4614:       if (k != i) {
                   4615:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4616:         if(flatdir[jk]==1){
                   4617:           printf(" To be skipped %d%d flatdir[%d]=%d ",i,k,jk, flatdir[jk]);
                   4618:         }
                   4619:         for(j=1; j <=ncovmodel; j++){
                   4620:           printf("%12.7f ",p[jk]);
                   4621:           jk++; 
                   4622:         }
                   4623:         printf("\n");
                   4624:       }
                   4625:     }
                   4626:   }
                   4627: /* skipping */
                   4628:   /* for(i=1, jk=1, jkk=1;(flatdir[jk]==0)&& (i <=nlstate); i++){ */
                   4629:   for(i=1, jk=1, jkk=1;i <=nlstate; i++){
                   4630:     for(k=1; k <=(nlstate+ndeath); k++){
                   4631:       if (k != i) {
                   4632:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4633:         if(flatdir[jk]==1){
                   4634:           printf(" To be skipped %d%d flatdir[%d]=%d jk=%d p[%d] ",i,k,jk, flatdir[jk],jk, jk);
                   4635:           for(j=1; j <=ncovmodel;  jk++,j++){
                   4636:             printf(" p[%d]=%12.7f",jk, p[jk]);
                   4637:             /*q[jjk]=p[jk];*/
                   4638:           }
                   4639:         }else{
                   4640:           printf(" To be kept %d%d flatdir[%d]=%d jk=%d q[%d]=p[%d] ",i,k,jk, flatdir[jk],jk, jkk, jk);
                   4641:           for(j=1; j <=ncovmodel;  jk++,jkk++,j++){
                   4642:             printf(" p[%d]=%12.7f=q[%d]",jk, p[jk],jkk);
                   4643:             /*q[jjk]=p[jk];*/
                   4644:           }
                   4645:         }
                   4646:         printf("\n");
                   4647:       }
                   4648:       fflush(stdout);
                   4649:     }
                   4650:   }
                   4651:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4652: #else  /* FLATSUP */
1.126     brouard  4653:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.319     brouard  4654: #endif  /* FLATSUP */
                   4655: 
                   4656: #ifdef LINMINORIGINAL
                   4657: #else
                   4658:       free_ivector(flatdir,1,npar); 
                   4659: #endif  /* LINMINORIGINAL*/
                   4660: #endif /* POWELL */
1.126     brouard  4661: 
1.162     brouard  4662: #ifdef NLOPT
                   4663: #ifdef NEWUOA
                   4664:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   4665: #else
                   4666:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   4667: #endif
                   4668:   lb=vector(0,npar-1);
                   4669:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   4670:   nlopt_set_lower_bounds(opt, lb);
                   4671:   nlopt_set_initial_step1(opt, 0.1);
                   4672:   
                   4673:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   4674:   d->function = func;
                   4675:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   4676:   nlopt_set_min_objective(opt, myfunc, d);
                   4677:   nlopt_set_xtol_rel(opt, ftol);
                   4678:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   4679:     printf("nlopt failed! %d\n",creturn); 
                   4680:   }
                   4681:   else {
                   4682:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   4683:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   4684:     iter=1; /* not equal */
                   4685:   }
                   4686:   nlopt_destroy(opt);
                   4687: #endif
1.319     brouard  4688: #ifdef FLATSUP
                   4689:   /* npared = npar -flatd/ncovmodel; */
                   4690:   /* xired= matrix(1,npared,1,npared); */
                   4691:   /* paramred= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */
                   4692:   /* powell(pred,xired,npared,ftol,&iter,&fret,flatdir,func); */
                   4693:   /* free_matrix(xire,1,npared,1,npared); */
                   4694: #else  /* FLATSUP */
                   4695: #endif /* FLATSUP */
1.126     brouard  4696:   free_matrix(xi,1,npar,1,npar);
                   4697:   fclose(ficrespow);
1.203     brouard  4698:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   4699:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  4700:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  4701: 
                   4702: }
                   4703: 
                   4704: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  4705: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  4706: {
                   4707:   double  **a,**y,*x,pd;
1.203     brouard  4708:   /* double **hess; */
1.164     brouard  4709:   int i, j;
1.126     brouard  4710:   int *indx;
                   4711: 
                   4712:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  4713:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  4714:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   4715:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   4716:   double gompertz(double p[]);
1.203     brouard  4717:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  4718: 
                   4719:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   4720:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   4721:   for (i=1;i<=npar;i++){
1.203     brouard  4722:     printf("%d-",i);fflush(stdout);
                   4723:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  4724:    
                   4725:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   4726:     
                   4727:     /*  printf(" %f ",p[i]);
                   4728:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   4729:   }
                   4730:   
                   4731:   for (i=1;i<=npar;i++) {
                   4732:     for (j=1;j<=npar;j++)  {
                   4733:       if (j>i) { 
1.203     brouard  4734:        printf(".%d-%d",i,j);fflush(stdout);
                   4735:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   4736:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  4737:        
                   4738:        hess[j][i]=hess[i][j];    
                   4739:        /*printf(" %lf ",hess[i][j]);*/
                   4740:       }
                   4741:     }
                   4742:   }
                   4743:   printf("\n");
                   4744:   fprintf(ficlog,"\n");
                   4745: 
                   4746:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4747:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4748:   
                   4749:   a=matrix(1,npar,1,npar);
                   4750:   y=matrix(1,npar,1,npar);
                   4751:   x=vector(1,npar);
                   4752:   indx=ivector(1,npar);
                   4753:   for (i=1;i<=npar;i++)
                   4754:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   4755:   ludcmp(a,npar,indx,&pd);
                   4756: 
                   4757:   for (j=1;j<=npar;j++) {
                   4758:     for (i=1;i<=npar;i++) x[i]=0;
                   4759:     x[j]=1;
                   4760:     lubksb(a,npar,indx,x);
                   4761:     for (i=1;i<=npar;i++){ 
                   4762:       matcov[i][j]=x[i];
                   4763:     }
                   4764:   }
                   4765: 
                   4766:   printf("\n#Hessian matrix#\n");
                   4767:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   4768:   for (i=1;i<=npar;i++) { 
                   4769:     for (j=1;j<=npar;j++) { 
1.203     brouard  4770:       printf("%.6e ",hess[i][j]);
                   4771:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  4772:     }
                   4773:     printf("\n");
                   4774:     fprintf(ficlog,"\n");
                   4775:   }
                   4776: 
1.203     brouard  4777:   /* printf("\n#Covariance matrix#\n"); */
                   4778:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   4779:   /* for (i=1;i<=npar;i++) {  */
                   4780:   /*   for (j=1;j<=npar;j++) {  */
                   4781:   /*     printf("%.6e ",matcov[i][j]); */
                   4782:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   4783:   /*   } */
                   4784:   /*   printf("\n"); */
                   4785:   /*   fprintf(ficlog,"\n"); */
                   4786:   /* } */
                   4787: 
1.126     brouard  4788:   /* Recompute Inverse */
1.203     brouard  4789:   /* for (i=1;i<=npar;i++) */
                   4790:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   4791:   /* ludcmp(a,npar,indx,&pd); */
                   4792: 
                   4793:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   4794: 
                   4795:   /* for (j=1;j<=npar;j++) { */
                   4796:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   4797:   /*   x[j]=1; */
                   4798:   /*   lubksb(a,npar,indx,x); */
                   4799:   /*   for (i=1;i<=npar;i++){  */
                   4800:   /*     y[i][j]=x[i]; */
                   4801:   /*     printf("%.3e ",y[i][j]); */
                   4802:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   4803:   /*   } */
                   4804:   /*   printf("\n"); */
                   4805:   /*   fprintf(ficlog,"\n"); */
                   4806:   /* } */
                   4807: 
                   4808:   /* Verifying the inverse matrix */
                   4809: #ifdef DEBUGHESS
                   4810:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  4811: 
1.203     brouard  4812:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   4813:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  4814: 
                   4815:   for (j=1;j<=npar;j++) {
                   4816:     for (i=1;i<=npar;i++){ 
1.203     brouard  4817:       printf("%.2f ",y[i][j]);
                   4818:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  4819:     }
                   4820:     printf("\n");
                   4821:     fprintf(ficlog,"\n");
                   4822:   }
1.203     brouard  4823: #endif
1.126     brouard  4824: 
                   4825:   free_matrix(a,1,npar,1,npar);
                   4826:   free_matrix(y,1,npar,1,npar);
                   4827:   free_vector(x,1,npar);
                   4828:   free_ivector(indx,1,npar);
1.203     brouard  4829:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  4830: 
                   4831: 
                   4832: }
                   4833: 
                   4834: /*************** hessian matrix ****************/
                   4835: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  4836: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  4837:   int i;
                   4838:   int l=1, lmax=20;
1.203     brouard  4839:   double k1,k2, res, fx;
1.132     brouard  4840:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  4841:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   4842:   int k=0,kmax=10;
                   4843:   double l1;
                   4844: 
                   4845:   fx=func(x);
                   4846:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  4847:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  4848:     l1=pow(10,l);
                   4849:     delts=delt;
                   4850:     for(k=1 ; k <kmax; k=k+1){
                   4851:       delt = delta*(l1*k);
                   4852:       p2[theta]=x[theta] +delt;
1.145     brouard  4853:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  4854:       p2[theta]=x[theta]-delt;
                   4855:       k2=func(p2)-fx;
                   4856:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  4857:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  4858:       
1.203     brouard  4859: #ifdef DEBUGHESSII
1.126     brouard  4860:       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);
                   4861:       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);
                   4862: #endif
                   4863:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   4864:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   4865:        k=kmax;
                   4866:       }
                   4867:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  4868:        k=kmax; l=lmax*10;
1.126     brouard  4869:       }
                   4870:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   4871:        delts=delt;
                   4872:       }
1.203     brouard  4873:     } /* End loop k */
1.126     brouard  4874:   }
                   4875:   delti[theta]=delts;
                   4876:   return res; 
                   4877:   
                   4878: }
                   4879: 
1.203     brouard  4880: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  4881: {
                   4882:   int i;
1.164     brouard  4883:   int l=1, lmax=20;
1.126     brouard  4884:   double k1,k2,k3,k4,res,fx;
1.132     brouard  4885:   double p2[MAXPARM+1];
1.203     brouard  4886:   int k, kmax=1;
                   4887:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  4888: 
                   4889:   int firstime=0;
1.203     brouard  4890:   
1.126     brouard  4891:   fx=func(x);
1.203     brouard  4892:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  4893:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  4894:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4895:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4896:     k1=func(p2)-fx;
                   4897:   
1.203     brouard  4898:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4899:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4900:     k2=func(p2)-fx;
                   4901:   
1.203     brouard  4902:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4903:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4904:     k3=func(p2)-fx;
                   4905:   
1.203     brouard  4906:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4907:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4908:     k4=func(p2)-fx;
1.203     brouard  4909:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   4910:     if(k1*k2*k3*k4 <0.){
1.208     brouard  4911:       firstime=1;
1.203     brouard  4912:       kmax=kmax+10;
1.208     brouard  4913:     }
                   4914:     if(kmax >=10 || firstime ==1){
1.246     brouard  4915:       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);
                   4916:       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  4917:       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);
                   4918:       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);
                   4919:     }
                   4920: #ifdef DEBUGHESSIJ
                   4921:     v1=hess[thetai][thetai];
                   4922:     v2=hess[thetaj][thetaj];
                   4923:     cv12=res;
                   4924:     /* Computing eigen value of Hessian matrix */
                   4925:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4926:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4927:     if ((lc2 <0) || (lc1 <0) ){
                   4928:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4929:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4930:       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);
                   4931:       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);
                   4932:     }
1.126     brouard  4933: #endif
                   4934:   }
                   4935:   return res;
                   4936: }
                   4937: 
1.203     brouard  4938:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   4939: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   4940: /* { */
                   4941: /*   int i; */
                   4942: /*   int l=1, lmax=20; */
                   4943: /*   double k1,k2,k3,k4,res,fx; */
                   4944: /*   double p2[MAXPARM+1]; */
                   4945: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   4946: /*   int k=0,kmax=10; */
                   4947: /*   double l1; */
                   4948:   
                   4949: /*   fx=func(x); */
                   4950: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   4951: /*     l1=pow(10,l); */
                   4952: /*     delts=delt; */
                   4953: /*     for(k=1 ; k <kmax; k=k+1){ */
                   4954: /*       delt = delti*(l1*k); */
                   4955: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   4956: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4957: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4958: /*       k1=func(p2)-fx; */
                   4959:       
                   4960: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4961: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4962: /*       k2=func(p2)-fx; */
                   4963:       
                   4964: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4965: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4966: /*       k3=func(p2)-fx; */
                   4967:       
                   4968: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4969: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4970: /*       k4=func(p2)-fx; */
                   4971: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   4972: /* #ifdef DEBUGHESSIJ */
                   4973: /*       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); */
                   4974: /*       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); */
                   4975: /* #endif */
                   4976: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   4977: /*     k=kmax; */
                   4978: /*       } */
                   4979: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   4980: /*     k=kmax; l=lmax*10; */
                   4981: /*       } */
                   4982: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   4983: /*     delts=delt; */
                   4984: /*       } */
                   4985: /*     } /\* End loop k *\/ */
                   4986: /*   } */
                   4987: /*   delti[theta]=delts; */
                   4988: /*   return res;  */
                   4989: /* } */
                   4990: 
                   4991: 
1.126     brouard  4992: /************** Inverse of matrix **************/
                   4993: void ludcmp(double **a, int n, int *indx, double *d) 
                   4994: { 
                   4995:   int i,imax,j,k; 
                   4996:   double big,dum,sum,temp; 
                   4997:   double *vv; 
                   4998:  
                   4999:   vv=vector(1,n); 
                   5000:   *d=1.0; 
                   5001:   for (i=1;i<=n;i++) { 
                   5002:     big=0.0; 
                   5003:     for (j=1;j<=n;j++) 
                   5004:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  5005:     if (big == 0.0){
                   5006:       printf(" Singular Hessian matrix at row %d:\n",i);
                   5007:       for (j=1;j<=n;j++) {
                   5008:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   5009:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   5010:       }
                   5011:       fflush(ficlog);
                   5012:       fclose(ficlog);
                   5013:       nrerror("Singular matrix in routine ludcmp"); 
                   5014:     }
1.126     brouard  5015:     vv[i]=1.0/big; 
                   5016:   } 
                   5017:   for (j=1;j<=n;j++) { 
                   5018:     for (i=1;i<j;i++) { 
                   5019:       sum=a[i][j]; 
                   5020:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   5021:       a[i][j]=sum; 
                   5022:     } 
                   5023:     big=0.0; 
                   5024:     for (i=j;i<=n;i++) { 
                   5025:       sum=a[i][j]; 
                   5026:       for (k=1;k<j;k++) 
                   5027:        sum -= a[i][k]*a[k][j]; 
                   5028:       a[i][j]=sum; 
                   5029:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   5030:        big=dum; 
                   5031:        imax=i; 
                   5032:       } 
                   5033:     } 
                   5034:     if (j != imax) { 
                   5035:       for (k=1;k<=n;k++) { 
                   5036:        dum=a[imax][k]; 
                   5037:        a[imax][k]=a[j][k]; 
                   5038:        a[j][k]=dum; 
                   5039:       } 
                   5040:       *d = -(*d); 
                   5041:       vv[imax]=vv[j]; 
                   5042:     } 
                   5043:     indx[j]=imax; 
                   5044:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   5045:     if (j != n) { 
                   5046:       dum=1.0/(a[j][j]); 
                   5047:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   5048:     } 
                   5049:   } 
                   5050:   free_vector(vv,1,n);  /* Doesn't work */
                   5051: ;
                   5052: } 
                   5053: 
                   5054: void lubksb(double **a, int n, int *indx, double b[]) 
                   5055: { 
                   5056:   int i,ii=0,ip,j; 
                   5057:   double sum; 
                   5058:  
                   5059:   for (i=1;i<=n;i++) { 
                   5060:     ip=indx[i]; 
                   5061:     sum=b[ip]; 
                   5062:     b[ip]=b[i]; 
                   5063:     if (ii) 
                   5064:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   5065:     else if (sum) ii=i; 
                   5066:     b[i]=sum; 
                   5067:   } 
                   5068:   for (i=n;i>=1;i--) { 
                   5069:     sum=b[i]; 
                   5070:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   5071:     b[i]=sum/a[i][i]; 
                   5072:   } 
                   5073: } 
                   5074: 
                   5075: void pstamp(FILE *fichier)
                   5076: {
1.196     brouard  5077:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  5078: }
                   5079: 
1.297     brouard  5080: void date2dmy(double date,double *day, double *month, double *year){
                   5081:   double yp=0., yp1=0., yp2=0.;
                   5082:   
                   5083:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   5084:                        fractional in yp1 */
                   5085:   *year=yp;
                   5086:   yp2=modf((yp1*12),&yp);
                   5087:   *month=yp;
                   5088:   yp1=modf((yp2*30.5),&yp);
                   5089:   *day=yp;
                   5090:   if(*day==0) *day=1;
                   5091:   if(*month==0) *month=1;
                   5092: }
                   5093: 
1.253     brouard  5094: 
                   5095: 
1.126     brouard  5096: /************ Frequencies ********************/
1.251     brouard  5097: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  5098:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   5099:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  5100: {  /* Some frequencies as well as proposing some starting values */
1.332     brouard  5101:   /* Frequencies of any combination of dummy covariate used in the model equation */ 
1.265     brouard  5102:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  5103:   int iind=0, iage=0;
                   5104:   int mi; /* Effective wave */
                   5105:   int first;
                   5106:   double ***freq; /* Frequencies */
1.268     brouard  5107:   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 */
                   5108:   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  5109:   double *meanq, *stdq, *idq;
1.226     brouard  5110:   double **meanqt;
                   5111:   double *pp, **prop, *posprop, *pospropt;
                   5112:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   5113:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   5114:   double agebegin, ageend;
                   5115:     
                   5116:   pp=vector(1,nlstate);
1.251     brouard  5117:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  5118:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   5119:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   5120:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   5121:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  5122:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  5123:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  5124:   meanqt=matrix(1,lastpass,1,nqtveff);
                   5125:   strcpy(fileresp,"P_");
                   5126:   strcat(fileresp,fileresu);
                   5127:   /*strcat(fileresphtm,fileresu);*/
                   5128:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   5129:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   5130:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   5131:     exit(0);
                   5132:   }
1.240     brouard  5133:   
1.226     brouard  5134:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   5135:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   5136:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5137:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5138:     fflush(ficlog);
                   5139:     exit(70); 
                   5140:   }
                   5141:   else{
                   5142:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  5143: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  5144: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5145:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5146:   }
1.319     brouard  5147:   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  5148:   
1.226     brouard  5149:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   5150:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   5151:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5152:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5153:     fflush(ficlog);
                   5154:     exit(70); 
1.240     brouard  5155:   } else{
1.226     brouard  5156:     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  5157: ,<hr size=\"2\" color=\"#EC5E5E\"> \n                                  \
1.214     brouard  5158: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5159:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5160:   }
1.319     brouard  5161:   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  5162:   
1.253     brouard  5163:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   5164:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  5165:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  5166:   j1=0;
1.126     brouard  5167:   
1.227     brouard  5168:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
1.335     brouard  5169:   j=cptcoveff;  /* Only simple dummy covariates used in the model */
1.330     brouard  5170:   /* j=cptcovn;  /\* Only dummy covariates of the model *\/ */
1.226     brouard  5171:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  5172:   
                   5173:   
1.226     brouard  5174:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   5175:      reference=low_education V1=0,V2=0
                   5176:      med_educ                V1=1 V2=0, 
                   5177:      high_educ               V1=0 V2=1
1.330     brouard  5178:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcovn 
1.226     brouard  5179:   */
1.249     brouard  5180:   dateintsum=0;
                   5181:   k2cpt=0;
                   5182: 
1.253     brouard  5183:   if(cptcoveff == 0 )
1.265     brouard  5184:     nl=1;  /* Constant and age model only */
1.253     brouard  5185:   else
                   5186:     nl=2;
1.265     brouard  5187: 
                   5188:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   5189:   /* Loop on nj=1 or 2 if dummy covariates j!=0
1.335     brouard  5190:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
1.265     brouard  5191:    *     freq[s1][s2][iage] =0.
                   5192:    *     Loop on iind
                   5193:    *       ++freq[s1][s2][iage] weighted
                   5194:    *     end iind
                   5195:    *     if covariate and j!0
                   5196:    *       headers Variable on one line
                   5197:    *     endif cov j!=0
                   5198:    *     header of frequency table by age
                   5199:    *     Loop on age
                   5200:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   5201:    *       pos+=freq[s1][s2][iage] weighted
                   5202:    *       Loop on s1 initial state
                   5203:    *         fprintf(ficresp
                   5204:    *       end s1
                   5205:    *     end age
                   5206:    *     if j!=0 computes starting values
                   5207:    *     end compute starting values
                   5208:    *   end j1
                   5209:    * end nl 
                   5210:    */
1.253     brouard  5211:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   5212:     if(nj==1)
                   5213:       j=0;  /* First pass for the constant */
1.265     brouard  5214:     else{
1.335     brouard  5215:       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  5216:     }
1.251     brouard  5217:     first=1;
1.332     brouard  5218:     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  5219:       posproptt=0.;
1.330     brouard  5220:       /*printf("cptcovn=%d Tvaraff=%d", cptcovn,Tvaraff[1]);
1.251     brouard  5221:        scanf("%d", i);*/
                   5222:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  5223:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  5224:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  5225:            freq[i][s2][m]=0;
1.251     brouard  5226:       
                   5227:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  5228:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  5229:          prop[i][m]=0;
                   5230:        posprop[i]=0;
                   5231:        pospropt[i]=0;
                   5232:       }
1.283     brouard  5233:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  5234:         idq[z1]=0.;
                   5235:         meanq[z1]=0.;
                   5236:         stdq[z1]=0.;
1.283     brouard  5237:       }
                   5238:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  5239:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  5240:       /*         meanqt[m][z1]=0.; */
                   5241:       /*       } */
                   5242:       /* }       */
1.251     brouard  5243:       /* dateintsum=0; */
                   5244:       /* k2cpt=0; */
                   5245:       
1.265     brouard  5246:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  5247:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   5248:        bool=1;
                   5249:        if(j !=0){
                   5250:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.335     brouard  5251:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   5252:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
1.251     brouard  5253:                /* if(Tvaraff[z1] ==-20){ */
                   5254:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   5255:                /* }else  if(Tvaraff[z1] ==-10){ */
                   5256:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
1.330     brouard  5257:                /* }else  */ /* TODO TODO codtabm(j1,z1) or codtabm(j1,Tvaraff[z1]]z1)*/
1.335     brouard  5258:                /* 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); */
                   5259:                if(Tvaraff[z1]<1 || Tvaraff[z1]>=NCOVMAX)
1.338     brouard  5260:                  printf("Error Tvaraff[z1]=%d<1 or >=%d, cptcoveff=%d model=1+age+%s\n",Tvaraff[z1],NCOVMAX, cptcoveff, model);
1.332     brouard  5261:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]){ /* for combination j1 of covariates */
1.265     brouard  5262:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  5263:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
1.332     brouard  5264:                  /* 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", */
                   5265:                  /*   bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),*/
                   5266:                   /*   j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
1.251     brouard  5267:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   5268:                } /* Onlyf fixed */
                   5269:              } /* end z1 */
1.335     brouard  5270:            } /* cptcoveff > 0 */
1.251     brouard  5271:          } /* end any */
                   5272:        }/* end j==0 */
1.265     brouard  5273:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  5274:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  5275:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  5276:            m=mw[mi][iind];
                   5277:            if(j!=0){
                   5278:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
1.335     brouard  5279:                for (z1=1; z1<=cptcoveff; z1++) {
1.251     brouard  5280:                  if( Fixed[Tmodelind[z1]]==1){
1.340   ! brouard  5281:                    iv= Tvar[Tmodelind[z1]]-ncovcol-nqv; /* Good */
1.332     brouard  5282:                    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  5283:                                                                                      value is -1, we don't select. It differs from the 
                   5284:                                                                                      constant and age model which counts them. */
                   5285:                      bool=0; /* not selected */
                   5286:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
1.334     brouard  5287:                    /* i1=Tvaraff[z1]; */
                   5288:                    /* i2=TnsdVar[i1]; */
                   5289:                    /* i3=nbcode[i1][i2]; */
                   5290:                    /* i4=covar[i1][iind]; */
                   5291:                    /* if(i4 != i3){ */
                   5292:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) { /* Bug valgrind */
1.251     brouard  5293:                      bool=0;
                   5294:                    }
                   5295:                  }
                   5296:                }
                   5297:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   5298:            } /* end j==0 */
                   5299:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  5300:            if(bool==1){ /*Selected */
1.251     brouard  5301:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   5302:                 and mw[mi+1][iind]. dh depends on stepm. */
                   5303:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   5304:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   5305:              if(m >=firstpass && m <=lastpass){
                   5306:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   5307:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   5308:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   5309:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   5310:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   5311:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   5312:                if (m<lastpass) {
                   5313:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   5314:                  /*   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]); */
                   5315:                  if(s[m][iind]==-1)
                   5316:                    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.));
                   5317:                  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  5318:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
                   5319:                    if(!isnan(covar[ncovcol+z1][iind])){
1.332     brouard  5320:                      idq[z1]=idq[z1]+weight[iind];
                   5321:                      meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   5322:                      /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
                   5323:                      stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
1.311     brouard  5324:                    }
1.284     brouard  5325:                  }
1.251     brouard  5326:                  /* if((int)agev[m][iind] == 55) */
                   5327:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   5328:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   5329:                  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  5330:                }
1.251     brouard  5331:              } /* end if between passes */  
                   5332:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   5333:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   5334:                k2cpt++;
                   5335:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  5336:              }
1.251     brouard  5337:            }else{
                   5338:              bool=1;
                   5339:            }/* end bool 2 */
                   5340:          } /* end m */
1.284     brouard  5341:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   5342:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   5343:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   5344:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   5345:          /* } */
1.251     brouard  5346:        } /* end bool */
                   5347:       } /* end iind = 1 to imx */
1.319     brouard  5348:       /* prop[s][age] is fed for any initial and valid live state as well as
1.251     brouard  5349:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   5350:       
                   5351:       
                   5352:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.335     brouard  5353:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
1.265     brouard  5354:         pstamp(ficresp);
1.335     brouard  5355:       if  (cptcoveff>0 && j!=0){
1.265     brouard  5356:         pstamp(ficresp);
1.251     brouard  5357:        printf( "\n#********** Variable "); 
                   5358:        fprintf(ficresp, "\n#********** Variable "); 
                   5359:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   5360:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   5361:        fprintf(ficlog, "\n#********** Variable "); 
1.340   ! brouard  5362:        for (z1=1; z1<=cptcoveff; z1++){
1.251     brouard  5363:          if(!FixedV[Tvaraff[z1]]){
1.330     brouard  5364:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5365:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5366:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5367:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5368:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.250     brouard  5369:          }else{
1.330     brouard  5370:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5371:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5372:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5373:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5374:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.251     brouard  5375:          }
                   5376:        }
                   5377:        printf( "**********\n#");
                   5378:        fprintf(ficresp, "**********\n#");
                   5379:        fprintf(ficresphtm, "**********</h3>\n");
                   5380:        fprintf(ficresphtmfr, "**********</h3>\n");
                   5381:        fprintf(ficlog, "**********\n");
                   5382:       }
1.284     brouard  5383:       /*
                   5384:        Printing means of quantitative variables if any
                   5385:       */
                   5386:       for (z1=1; z1<= nqfveff; z1++) {
1.311     brouard  5387:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.312     brouard  5388:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
1.284     brouard  5389:        if(weightopt==1){
                   5390:          printf(" Weighted mean and standard deviation of");
                   5391:          fprintf(ficlog," Weighted mean and standard deviation of");
                   5392:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   5393:        }
1.311     brouard  5394:        /* mu = \frac{w x}{\sum w}
                   5395:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
                   5396:        */
                   5397:        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]));
                   5398:        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]));
                   5399:        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  5400:       }
                   5401:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   5402:       /*       for(m=1;m<=lastpass;m++){ */
                   5403:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   5404:       /*   } */
                   5405:       /* } */
1.283     brouard  5406: 
1.251     brouard  5407:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.335     brouard  5408:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
1.265     brouard  5409:         fprintf(ficresp, " Age");
1.335     brouard  5410:       if(nj==2) for (z1=1; z1<=cptcoveff; z1++) {
                   5411:          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]]);
                   5412:          fprintf(ficresp, " V%d=%d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5413:        }
1.251     brouard  5414:       for(i=1; i<=nlstate;i++) {
1.335     brouard  5415:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  5416:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   5417:       }
1.335     brouard  5418:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  5419:       fprintf(ficresphtm, "\n");
                   5420:       
                   5421:       /* Header of frequency table by age */
                   5422:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   5423:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  5424:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  5425:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5426:          if(s2!=0 && m!=0)
                   5427:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  5428:        }
1.226     brouard  5429:       }
1.251     brouard  5430:       fprintf(ficresphtmfr, "\n");
                   5431:     
                   5432:       /* For each age */
                   5433:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   5434:        fprintf(ficresphtm,"<tr>");
                   5435:        if(iage==iagemax+1){
                   5436:          fprintf(ficlog,"1");
                   5437:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   5438:        }else if(iage==iagemax+2){
                   5439:          fprintf(ficlog,"0");
                   5440:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   5441:        }else if(iage==iagemax+3){
                   5442:          fprintf(ficlog,"Total");
                   5443:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   5444:        }else{
1.240     brouard  5445:          if(first==1){
1.251     brouard  5446:            first=0;
                   5447:            printf("See log file for details...\n");
                   5448:          }
                   5449:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   5450:          fprintf(ficlog,"Age %d", iage);
                   5451:        }
1.265     brouard  5452:        for(s1=1; s1 <=nlstate ; s1++){
                   5453:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   5454:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  5455:        }
1.265     brouard  5456:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5457:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  5458:            pos += freq[s1][m][iage];
                   5459:          if(pp[s1]>=1.e-10){
1.251     brouard  5460:            if(first==1){
1.265     brouard  5461:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5462:            }
1.265     brouard  5463:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5464:          }else{
                   5465:            if(first==1)
1.265     brouard  5466:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   5467:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  5468:          }
                   5469:        }
                   5470:       
1.265     brouard  5471:        for(s1=1; s1 <=nlstate ; s1++){ 
                   5472:          /* posprop[s1]=0; */
                   5473:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   5474:            pp[s1] += freq[s1][m][iage];
                   5475:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   5476:       
                   5477:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   5478:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   5479:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5480:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5481:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5482:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5483:        }
                   5484:        
                   5485:        /* Writing ficresp */
1.335     brouard  5486:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5487:           if( iage <= iagemax){
                   5488:            fprintf(ficresp," %d",iage);
                   5489:           }
                   5490:         }else if( nj==2){
                   5491:           if( iage <= iagemax){
                   5492:            fprintf(ficresp," %d",iage);
1.335     brouard  5493:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.265     brouard  5494:           }
1.240     brouard  5495:        }
1.265     brouard  5496:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  5497:          if(pos>=1.e-5){
1.251     brouard  5498:            if(first==1)
1.265     brouard  5499:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   5500:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  5501:          }else{
                   5502:            if(first==1)
1.265     brouard  5503:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   5504:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  5505:          }
                   5506:          if( iage <= iagemax){
                   5507:            if(pos>=1.e-5){
1.335     brouard  5508:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5509:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5510:               }else if( nj==2){
                   5511:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5512:               }
                   5513:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5514:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   5515:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   5516:            } else{
1.335     brouard  5517:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
1.265     brouard  5518:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  5519:            }
1.240     brouard  5520:          }
1.265     brouard  5521:          pospropt[s1] +=posprop[s1];
                   5522:        } /* end loop s1 */
1.251     brouard  5523:        /* pospropt=0.; */
1.265     brouard  5524:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  5525:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5526:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  5527:              if(first==1){
1.265     brouard  5528:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5529:              }
1.265     brouard  5530:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   5531:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5532:            }
1.265     brouard  5533:            if(s1!=0 && m!=0)
                   5534:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  5535:          }
1.265     brouard  5536:        } /* end loop s1 */
1.251     brouard  5537:        posproptt=0.; 
1.265     brouard  5538:        for(s1=1; s1 <=nlstate; s1++){
                   5539:          posproptt += pospropt[s1];
1.251     brouard  5540:        }
                   5541:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  5542:        fprintf(ficresphtm,"</tr>\n");
1.335     brouard  5543:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
1.265     brouard  5544:          if(iage <= iagemax)
                   5545:            fprintf(ficresp,"\n");
1.240     brouard  5546:        }
1.251     brouard  5547:        if(first==1)
                   5548:          printf("Others in log...\n");
                   5549:        fprintf(ficlog,"\n");
                   5550:       } /* end loop age iage */
1.265     brouard  5551:       
1.251     brouard  5552:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  5553:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5554:        if(posproptt < 1.e-5){
1.265     brouard  5555:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  5556:        }else{
1.265     brouard  5557:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  5558:        }
1.226     brouard  5559:       }
1.251     brouard  5560:       fprintf(ficresphtm,"</tr>\n");
                   5561:       fprintf(ficresphtm,"</table>\n");
                   5562:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  5563:       if(posproptt < 1.e-5){
1.251     brouard  5564:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   5565:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  5566:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   5567:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  5568:        invalidvarcomb[j1]=1;
1.226     brouard  5569:       }else{
1.338     brouard  5570:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced (or no resultline).</p>",j1);
1.251     brouard  5571:        invalidvarcomb[j1]=0;
1.226     brouard  5572:       }
1.251     brouard  5573:       fprintf(ficresphtmfr,"</table>\n");
                   5574:       fprintf(ficlog,"\n");
                   5575:       if(j!=0){
                   5576:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  5577:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5578:          for(k=1; k <=(nlstate+ndeath); k++){
                   5579:            if (k != i) {
1.265     brouard  5580:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  5581:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  5582:                  if(j1==1){ /* All dummy covariates to zero */
                   5583:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   5584:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  5585:                    printf("%d%d ",i,k);
                   5586:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5587:                    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]));
                   5588:                    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]));
                   5589:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  5590:                  }
1.253     brouard  5591:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   5592:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   5593:                    x[iage]= (double)iage;
                   5594:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  5595:                    /* 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  5596:                  }
1.268     brouard  5597:                  /* Some are not finite, but linreg will ignore these ages */
                   5598:                  no=0;
1.253     brouard  5599:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  5600:                  pstart[s1]=b;
                   5601:                  pstart[s1-1]=a;
1.252     brouard  5602:                }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 */ 
                   5603:                  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]);
                   5604:                  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  5605:                  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  5606:                  printf("%d%d ",i,k);
                   5607:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5608:                  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  5609:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   5610:                  ;
                   5611:                }
                   5612:                /* printf("%12.7f )", param[i][jj][k]); */
                   5613:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5614:                s1++; 
1.251     brouard  5615:              } /* end jj */
                   5616:            } /* end k!= i */
                   5617:          } /* end k */
1.265     brouard  5618:        } /* end i, s1 */
1.251     brouard  5619:       } /* end j !=0 */
                   5620:     } /* end selected combination of covariate j1 */
                   5621:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   5622:       printf("#Freqsummary: Starting values for the constants:\n");
                   5623:       fprintf(ficlog,"\n");
1.265     brouard  5624:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5625:        for(k=1; k <=(nlstate+ndeath); k++){
                   5626:          if (k != i) {
                   5627:            printf("%d%d ",i,k);
                   5628:            fprintf(ficlog,"%d%d ",i,k);
                   5629:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  5630:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  5631:              if(jj==1){ /* Age has to be done */
1.265     brouard  5632:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   5633:                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]));
                   5634:                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  5635:              }
                   5636:              /* printf("%12.7f )", param[i][jj][k]); */
                   5637:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5638:              s1++; 
1.250     brouard  5639:            }
1.251     brouard  5640:            printf("\n");
                   5641:            fprintf(ficlog,"\n");
1.250     brouard  5642:          }
                   5643:        }
1.284     brouard  5644:       } /* end of state i */
1.251     brouard  5645:       printf("#Freqsummary\n");
                   5646:       fprintf(ficlog,"\n");
1.265     brouard  5647:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   5648:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   5649:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   5650:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5651:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5652:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   5653:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   5654:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  5655:          /* } */
                   5656:        }
1.265     brouard  5657:       } /* end loop s1 */
1.251     brouard  5658:       
                   5659:       printf("\n");
                   5660:       fprintf(ficlog,"\n");
                   5661:     } /* end j=0 */
1.249     brouard  5662:   } /* end j */
1.252     brouard  5663: 
1.253     brouard  5664:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  5665:     for(i=1, jk=1; i <=nlstate; i++){
                   5666:       for(j=1; j <=nlstate+ndeath; j++){
                   5667:        if(j!=i){
                   5668:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5669:          printf("%1d%1d",i,j);
                   5670:          fprintf(ficparo,"%1d%1d",i,j);
                   5671:          for(k=1; k<=ncovmodel;k++){
                   5672:            /*    printf(" %lf",param[i][j][k]); */
                   5673:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   5674:            p[jk]=pstart[jk];
                   5675:            printf(" %f ",pstart[jk]);
                   5676:            fprintf(ficparo," %f ",pstart[jk]);
                   5677:            jk++;
                   5678:          }
                   5679:          printf("\n");
                   5680:          fprintf(ficparo,"\n");
                   5681:        }
                   5682:       }
                   5683:     }
                   5684:   } /* end mle=-2 */
1.226     brouard  5685:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  5686:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  5687:   
1.226     brouard  5688:   fclose(ficresp);
                   5689:   fclose(ficresphtm);
                   5690:   fclose(ficresphtmfr);
1.283     brouard  5691:   free_vector(idq,1,nqfveff);
1.226     brouard  5692:   free_vector(meanq,1,nqfveff);
1.284     brouard  5693:   free_vector(stdq,1,nqfveff);
1.226     brouard  5694:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  5695:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   5696:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  5697:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5698:   free_vector(pospropt,1,nlstate);
                   5699:   free_vector(posprop,1,nlstate);
1.251     brouard  5700:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5701:   free_vector(pp,1,nlstate);
                   5702:   /* End of freqsummary */
                   5703: }
1.126     brouard  5704: 
1.268     brouard  5705: /* Simple linear regression */
                   5706: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   5707: 
                   5708:   /* y=a+bx regression */
                   5709:   double   sumx = 0.0;                        /* sum of x                      */
                   5710:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   5711:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   5712:   double   sumy = 0.0;                        /* sum of y                      */
                   5713:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   5714:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   5715:   double yhat;
                   5716:   
                   5717:   double denom=0;
                   5718:   int i;
                   5719:   int ne=*no;
                   5720:   
                   5721:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5722:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5723:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5724:       continue;
                   5725:     }
                   5726:     ne=ne+1;
                   5727:     sumx  += x[i];       
                   5728:     sumx2 += x[i]*x[i];  
                   5729:     sumxy += x[i] * y[i];
                   5730:     sumy  += y[i];      
                   5731:     sumy2 += y[i]*y[i]; 
                   5732:     denom = (ne * sumx2 - sumx*sumx);
                   5733:     /* 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); */
                   5734:   } 
                   5735:   
                   5736:   denom = (ne * sumx2 - sumx*sumx);
                   5737:   if (denom == 0) {
                   5738:     // vertical, slope m is infinity
                   5739:     *b = INFINITY;
                   5740:     *a = 0;
                   5741:     if (r) *r = 0;
                   5742:     return 1;
                   5743:   }
                   5744:   
                   5745:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   5746:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   5747:   if (r!=NULL) {
                   5748:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   5749:       sqrt((sumx2 - sumx*sumx/ne) *
                   5750:           (sumy2 - sumy*sumy/ne));
                   5751:   }
                   5752:   *no=ne;
                   5753:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5754:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5755:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5756:       continue;
                   5757:     }
                   5758:     ne=ne+1;
                   5759:     yhat = y[i] - *a -*b* x[i];
                   5760:     sume2  += yhat * yhat ;       
                   5761:     
                   5762:     denom = (ne * sumx2 - sumx*sumx);
                   5763:     /* 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); */
                   5764:   } 
                   5765:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   5766:   *sa= *sb * sqrt(sumx2/ne);
                   5767:   
                   5768:   return 0; 
                   5769: }
                   5770: 
1.126     brouard  5771: /************ Prevalence ********************/
1.227     brouard  5772: 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)
                   5773: {  
                   5774:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   5775:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   5776:      We still use firstpass and lastpass as another selection.
                   5777:   */
1.126     brouard  5778:  
1.227     brouard  5779:   int i, m, jk, j1, bool, z1,j, iv;
                   5780:   int mi; /* Effective wave */
                   5781:   int iage;
                   5782:   double agebegin, ageend;
                   5783: 
                   5784:   double **prop;
                   5785:   double posprop; 
                   5786:   double  y2; /* in fractional years */
                   5787:   int iagemin, iagemax;
                   5788:   int first; /** to stop verbosity which is redirected to log file */
                   5789: 
                   5790:   iagemin= (int) agemin;
                   5791:   iagemax= (int) agemax;
                   5792:   /*pp=vector(1,nlstate);*/
1.251     brouard  5793:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  5794:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   5795:   j1=0;
1.222     brouard  5796:   
1.227     brouard  5797:   /*j=cptcoveff;*/
                   5798:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  5799:   
1.288     brouard  5800:   first=0;
1.335     brouard  5801:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of simple dummy covariates */
1.227     brouard  5802:     for (i=1; i<=nlstate; i++)  
1.251     brouard  5803:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  5804:        prop[i][iage]=0.0;
                   5805:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   5806:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   5807:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   5808:     
                   5809:     for (i=1; i<=imx; i++) { /* Each individual */
                   5810:       bool=1;
                   5811:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   5812:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   5813:        m=mw[mi][i];
                   5814:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   5815:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   5816:        for (z1=1; z1<=cptcoveff; z1++){
                   5817:          if( Fixed[Tmodelind[z1]]==1){
                   5818:            iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
1.332     brouard  5819:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality */
1.227     brouard  5820:              bool=0;
                   5821:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
1.332     brouard  5822:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) {
1.227     brouard  5823:              bool=0;
                   5824:            }
                   5825:        }
                   5826:        if(bool==1){ /* Otherwise we skip that wave/person */
                   5827:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   5828:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   5829:          if(m >=firstpass && m <=lastpass){
                   5830:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   5831:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   5832:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   5833:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  5834:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  5835:                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); 
                   5836:                exit(1);
                   5837:              }
                   5838:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   5839:                /*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]]);*/
                   5840:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   5841:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   5842:              } /* end valid statuses */ 
                   5843:            } /* end selection of dates */
                   5844:          } /* end selection of waves */
                   5845:        } /* end bool */
                   5846:       } /* end wave */
                   5847:     } /* end individual */
                   5848:     for(i=iagemin; i <= iagemax+3; i++){  
                   5849:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   5850:        posprop += prop[jk][i]; 
                   5851:       } 
                   5852:       
                   5853:       for(jk=1; jk <=nlstate ; jk++){      
                   5854:        if( i <=  iagemax){ 
                   5855:          if(posprop>=1.e-5){ 
                   5856:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   5857:          } else{
1.288     brouard  5858:            if(!first){
                   5859:              first=1;
1.266     brouard  5860:              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]);
                   5861:            }else{
1.288     brouard  5862:              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  5863:            }
                   5864:          }
                   5865:        } 
                   5866:       }/* end jk */ 
                   5867:     }/* end i */ 
1.222     brouard  5868:      /*} *//* end i1 */
1.227     brouard  5869:   } /* end j1 */
1.222     brouard  5870:   
1.227     brouard  5871:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   5872:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  5873:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  5874: }  /* End of prevalence */
1.126     brouard  5875: 
                   5876: /************* Waves Concatenation ***************/
                   5877: 
                   5878: 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)
                   5879: {
1.298     brouard  5880:   /* 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  5881:      Death is a valid wave (if date is known).
                   5882:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   5883:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  5884:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  5885:   */
1.126     brouard  5886: 
1.224     brouard  5887:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  5888:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   5889:      double sum=0., jmean=0.;*/
1.224     brouard  5890:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  5891:   int j, k=0,jk, ju, jl;
                   5892:   double sum=0.;
                   5893:   first=0;
1.214     brouard  5894:   firstwo=0;
1.217     brouard  5895:   firsthree=0;
1.218     brouard  5896:   firstfour=0;
1.164     brouard  5897:   jmin=100000;
1.126     brouard  5898:   jmax=-1;
                   5899:   jmean=0.;
1.224     brouard  5900: 
                   5901: /* Treating live states */
1.214     brouard  5902:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  5903:     mi=0;  /* First valid wave */
1.227     brouard  5904:     mli=0; /* Last valid wave */
1.309     brouard  5905:     m=firstpass;  /* Loop on waves */
                   5906:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
1.227     brouard  5907:       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 */
                   5908:        mli=m-1;/* mw[++mi][i]=m-1; */
                   5909:       }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  5910:        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  5911:        mli=m;
1.224     brouard  5912:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   5913:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  5914:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  5915:       }
1.309     brouard  5916:       else{ /* m = lastpass, eventual special issue with warning */
1.224     brouard  5917: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  5918:        break;
1.224     brouard  5919: #else
1.317     brouard  5920:        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  5921:          if(firsthree == 0){
1.302     brouard  5922:            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  5923:            firsthree=1;
1.317     brouard  5924:          }else if(firsthree >=1 && firsthree < 10){
                   5925:            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);
                   5926:            firsthree++;
                   5927:          }else if(firsthree == 10){
                   5928:            printf("Information, too many Information flags: no more reported to log either\n");
                   5929:            fprintf(ficlog,"Information, too many Information flags: no more reported to log either\n");
                   5930:            firsthree++;
                   5931:          }else{
                   5932:            firsthree++;
1.227     brouard  5933:          }
1.309     brouard  5934:          mw[++mi][i]=m; /* Valid transition with unknown status */
1.227     brouard  5935:          mli=m;
                   5936:        }
                   5937:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   5938:          nbwarn++;
1.309     brouard  5939:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
1.227     brouard  5940:            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);
                   5941:            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);
                   5942:          }
                   5943:          break;
                   5944:        }
                   5945:        break;
1.224     brouard  5946: #endif
1.227     brouard  5947:       }/* End m >= lastpass */
1.126     brouard  5948:     }/* end while */
1.224     brouard  5949: 
1.227     brouard  5950:     /* 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  5951:     /* After last pass */
1.224     brouard  5952: /* Treating death states */
1.214     brouard  5953:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  5954:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   5955:       /* } */
1.126     brouard  5956:       mi++;    /* Death is another wave */
                   5957:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  5958:       /* Only death is a correct wave */
1.126     brouard  5959:       mw[mi][i]=m;
1.257     brouard  5960:     } /* else not in a death state */
1.224     brouard  5961: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  5962:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  5963:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.309     brouard  5964:        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  5965:          nbwarn++;
                   5966:          if(firstfiv==0){
1.309     brouard  5967:            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  5968:            firstfiv=1;
                   5969:          }else{
1.309     brouard  5970:            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  5971:          }
1.309     brouard  5972:            s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
                   5973:        }else{ /* Month of Death occured afer last wave month, potential bias */
1.227     brouard  5974:          nberr++;
                   5975:          if(firstwo==0){
1.309     brouard  5976:            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  5977:            firstwo=1;
                   5978:          }
1.309     brouard  5979:          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  5980:        }
1.257     brouard  5981:       }else{ /* if date of interview is unknown */
1.227     brouard  5982:        /* death is known but not confirmed by death status at any wave */
                   5983:        if(firstfour==0){
1.309     brouard  5984:          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  5985:          firstfour=1;
                   5986:        }
1.309     brouard  5987:        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  5988:       }
1.224     brouard  5989:     } /* end if date of death is known */
                   5990: #endif
1.309     brouard  5991:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
                   5992:     /* wav[i]=mw[mi][i];   */
1.126     brouard  5993:     if(mi==0){
                   5994:       nbwarn++;
                   5995:       if(first==0){
1.227     brouard  5996:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   5997:        first=1;
1.126     brouard  5998:       }
                   5999:       if(first==1){
1.227     brouard  6000:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  6001:       }
                   6002:     } /* end mi==0 */
                   6003:   } /* End individuals */
1.214     brouard  6004:   /* wav and mw are no more changed */
1.223     brouard  6005:        
1.317     brouard  6006:   printf("Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   6007:   fprintf(ficlog,"Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   6008: 
                   6009: 
1.126     brouard  6010:   for(i=1; i<=imx; i++){
                   6011:     for(mi=1; mi<wav[i];mi++){
                   6012:       if (stepm <=0)
1.227     brouard  6013:        dh[mi][i]=1;
1.126     brouard  6014:       else{
1.260     brouard  6015:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  6016:          if (agedc[i] < 2*AGESUP) {
                   6017:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   6018:            if(j==0) j=1;  /* Survives at least one month after exam */
                   6019:            else if(j<0){
                   6020:              nberr++;
                   6021:              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]);
                   6022:              j=1; /* Temporary Dangerous patch */
                   6023:              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);
                   6024:              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]);
                   6025:              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);
                   6026:            }
                   6027:            k=k+1;
                   6028:            if (j >= jmax){
                   6029:              jmax=j;
                   6030:              ijmax=i;
                   6031:            }
                   6032:            if (j <= jmin){
                   6033:              jmin=j;
                   6034:              ijmin=i;
                   6035:            }
                   6036:            sum=sum+j;
                   6037:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   6038:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   6039:          }
                   6040:        }
                   6041:        else{
                   6042:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  6043: /*       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  6044:                                        
1.227     brouard  6045:          k=k+1;
                   6046:          if (j >= jmax) {
                   6047:            jmax=j;
                   6048:            ijmax=i;
                   6049:          }
                   6050:          else if (j <= jmin){
                   6051:            jmin=j;
                   6052:            ijmin=i;
                   6053:          }
                   6054:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   6055:          /*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]);*/
                   6056:          if(j<0){
                   6057:            nberr++;
                   6058:            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]);
                   6059:            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]);
                   6060:          }
                   6061:          sum=sum+j;
                   6062:        }
                   6063:        jk= j/stepm;
                   6064:        jl= j -jk*stepm;
                   6065:        ju= j -(jk+1)*stepm;
                   6066:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   6067:          if(jl==0){
                   6068:            dh[mi][i]=jk;
                   6069:            bh[mi][i]=0;
                   6070:          }else{ /* We want a negative bias in order to only have interpolation ie
                   6071:                  * to avoid the price of an extra matrix product in likelihood */
                   6072:            dh[mi][i]=jk+1;
                   6073:            bh[mi][i]=ju;
                   6074:          }
                   6075:        }else{
                   6076:          if(jl <= -ju){
                   6077:            dh[mi][i]=jk;
                   6078:            bh[mi][i]=jl;       /* bias is positive if real duration
                   6079:                                 * is higher than the multiple of stepm and negative otherwise.
                   6080:                                 */
                   6081:          }
                   6082:          else{
                   6083:            dh[mi][i]=jk+1;
                   6084:            bh[mi][i]=ju;
                   6085:          }
                   6086:          if(dh[mi][i]==0){
                   6087:            dh[mi][i]=1; /* At least one step */
                   6088:            bh[mi][i]=ju; /* At least one step */
                   6089:            /*  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);*/
                   6090:          }
                   6091:        } /* end if mle */
1.126     brouard  6092:       }
                   6093:     } /* end wave */
                   6094:   }
                   6095:   jmean=sum/k;
                   6096:   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  6097:   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  6098: }
1.126     brouard  6099: 
                   6100: /*********** Tricode ****************************/
1.220     brouard  6101:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  6102:  {
                   6103:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   6104:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   6105:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   6106:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   6107:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   6108:     */
1.130     brouard  6109: 
1.242     brouard  6110:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   6111:    int modmaxcovj=0; /* Modality max of covariates j */
                   6112:    int cptcode=0; /* Modality max of covariates j */
                   6113:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  6114: 
                   6115: 
1.242     brouard  6116:    /* cptcoveff=0;  */
                   6117:    /* *cptcov=0; */
1.126     brouard  6118:  
1.242     brouard  6119:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  6120:    for (k=1; k <= maxncov; k++)
                   6121:      for(j=1; j<=2; j++)
                   6122:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  6123: 
1.242     brouard  6124:    /* Loop on covariates without age and products and no quantitative variable */
1.335     brouard  6125:    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  6126:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
1.339     brouard  6127:      printf("Testing k=%d, cptcovt=%d\n",k, cptcovt);
                   6128:      if(Dummy[k]==0 && Typevar[k] !=1 && Typevar[k] != 2){ /* Dummy covariate and not age product nor fixed product */ 
1.242     brouard  6129:        switch(Fixed[k]) {
                   6130:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.311     brouard  6131:         modmaxcovj=0;
                   6132:         modmincovj=0;
1.242     brouard  6133:         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  6134:           /* 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  6135:           ij=(int)(covar[Tvar[k]][i]);
                   6136:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   6137:            * If product of Vn*Vm, still boolean *:
                   6138:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   6139:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   6140:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   6141:              modality of the nth covariate of individual i. */
                   6142:           if (ij > modmaxcovj)
                   6143:             modmaxcovj=ij; 
                   6144:           else if (ij < modmincovj) 
                   6145:             modmincovj=ij; 
1.287     brouard  6146:           if (ij <0 || ij >1 ){
1.311     brouard  6147:             printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6148:             fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6149:             fflush(ficlog);
                   6150:             exit(1);
1.287     brouard  6151:           }
                   6152:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  6153:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   6154:             exit(1);
                   6155:           }else
                   6156:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   6157:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   6158:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   6159:           /* getting the maximum value of the modality of the covariate
                   6160:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   6161:              female ies 1, then modmaxcovj=1.
                   6162:           */
                   6163:         } /* end for loop on individuals i */
                   6164:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6165:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6166:         cptcode=modmaxcovj;
                   6167:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   6168:         /*for (i=0; i<=cptcode; i++) {*/
                   6169:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   6170:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6171:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6172:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   6173:             if( j != -1){
                   6174:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   6175:                                  covariate for which somebody answered excluding 
                   6176:                                  undefined. Usually 2: 0 and 1. */
                   6177:             }
                   6178:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   6179:                                     covariate for which somebody answered including 
                   6180:                                     undefined. Usually 3: -1, 0 and 1. */
                   6181:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   6182:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   6183:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  6184:                        
1.242     brouard  6185:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   6186:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   6187:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   6188:         /* modmincovj=3; modmaxcovj = 7; */
                   6189:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   6190:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   6191:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   6192:         /* nbcode[Tvar[j]][ij]=k; */
                   6193:         /* nbcode[Tvar[j]][1]=0; */
                   6194:         /* nbcode[Tvar[j]][2]=1; */
                   6195:         /* nbcode[Tvar[j]][3]=2; */
                   6196:         /* To be continued (not working yet). */
                   6197:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  6198: 
                   6199:         /* 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*/
                   6200:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   6201:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   6202:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   6203:         /*, could be restored in the future */
                   6204:         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  6205:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   6206:             break;
                   6207:           }
                   6208:           ij++;
1.287     brouard  6209:           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  6210:           cptcode = ij; /* New max modality for covar j */
                   6211:         } /* end of loop on modality i=-1 to 1 or more */
                   6212:         break;
                   6213:        case 1: /* Testing on varying covariate, could be simple and
                   6214:                * should look at waves or product of fixed *
                   6215:                * varying. No time to test -1, assuming 0 and 1 only */
                   6216:         ij=0;
                   6217:         for(i=0; i<=1;i++){
                   6218:           nbcode[Tvar[k]][++ij]=i;
                   6219:         }
                   6220:         break;
                   6221:        default:
                   6222:         break;
                   6223:        } /* end switch */
                   6224:      } /* end dummy test */
1.334     brouard  6225:      if(Dummy[k]==1 && Typevar[k] !=1){ /* Quantitative covariate and not age product */ 
1.311     brouard  6226:        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  6227:         if(Tvar[k]<=0 || Tvar[k]>=NCOVMAX){
                   6228:           printf("Error k=%d \n",k);
                   6229:           exit(1);
                   6230:         }
1.311     brouard  6231:         if(isnan(covar[Tvar[k]][i])){
                   6232:           printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6233:           fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6234:           fflush(ficlog);
                   6235:           exit(1);
                   6236:          }
                   6237:        }
1.335     brouard  6238:      } /* end Quanti */
1.287     brouard  6239:    } /* 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  6240:   
                   6241:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   6242:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   6243:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   6244:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   6245:      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 */ 
                   6246:      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 */
                   6247:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   6248:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   6249:   
                   6250:    ij=0;
                   6251:    /* 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  6252:    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 */
                   6253:      /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
1.242     brouard  6254:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   6255:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
1.335     brouard  6256:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy simple and non empty in the model */
                   6257:        /* Typevar[k] =0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for product */
                   6258:        /* 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  6259:        /* If product not in single variable we don't print results */
                   6260:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
1.335     brouard  6261:        ++ij;/*    V5 + V4 + V3 + V4*V3 + V5*age + V2 +  V1*V2 + V1*age + V1, *//* V5 quanti, V2 quanti, V4, V3, V1 dummies */
                   6262:        /* k=       1    2   3     4       5       6      7       8        9  */
                   6263:        /* Tvar[k]= 5    4    3    6       5       2      7       1        1  */
                   6264:        /* ij            1    2                                            3  */  
                   6265:        /* Tvaraff[ij]=  4    3                                            1  */
                   6266:        /* Tmodelind[ij]=2    3                                            9  */
                   6267:        /* TmodelInvind[ij]=2 1                                            1  */
1.242     brouard  6268:        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*/
                   6269:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   6270:        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 */
                   6271:        if(Fixed[k]!=0)
                   6272:         anyvaryingduminmodel=1;
                   6273:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   6274:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6275:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   6276:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   6277:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   6278:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6279:      } 
                   6280:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   6281:    /* ij--; */
                   6282:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
1.335     brouard  6283:    *cptcov=ij; /* cptcov= Number of total real effective simple dummies (fixed or time  arying) effective (used as cptcoveff in other functions)
1.242     brouard  6284:                * because they can be excluded from the model and real
                   6285:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   6286:    for(j=ij+1; j<= cptcovt; j++){
                   6287:      Tvaraff[j]=0;
                   6288:      Tmodelind[j]=0;
                   6289:    }
                   6290:    for(j=ntveff+1; j<= cptcovt; j++){
                   6291:      TmodelInvind[j]=0;
                   6292:    }
                   6293:    /* To be sorted */
                   6294:    ;
                   6295:  }
1.126     brouard  6296: 
1.145     brouard  6297: 
1.126     brouard  6298: /*********** Health Expectancies ****************/
                   6299: 
1.235     brouard  6300:  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  6301: 
                   6302: {
                   6303:   /* Health expectancies, no variances */
1.329     brouard  6304:   /* cij is the combination in the list of combination of dummy covariates */
                   6305:   /* strstart is a string of time at start of computing */
1.164     brouard  6306:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  6307:   int nhstepma, nstepma; /* Decreasing with age */
                   6308:   double age, agelim, hf;
                   6309:   double ***p3mat;
                   6310:   double eip;
                   6311: 
1.238     brouard  6312:   /* pstamp(ficreseij); */
1.126     brouard  6313:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   6314:   fprintf(ficreseij,"# Age");
                   6315:   for(i=1; i<=nlstate;i++){
                   6316:     for(j=1; j<=nlstate;j++){
                   6317:       fprintf(ficreseij," e%1d%1d ",i,j);
                   6318:     }
                   6319:     fprintf(ficreseij," e%1d. ",i);
                   6320:   }
                   6321:   fprintf(ficreseij,"\n");
                   6322: 
                   6323:   
                   6324:   if(estepm < stepm){
                   6325:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6326:   }
                   6327:   else  hstepm=estepm;   
                   6328:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6329:    * This is mainly to measure the difference between two models: for example
                   6330:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6331:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6332:    * progression in between and thus overestimating or underestimating according
                   6333:    * to the curvature of the survival function. If, for the same date, we 
                   6334:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6335:    * to compare the new estimate of Life expectancy with the same linear 
                   6336:    * hypothesis. A more precise result, taking into account a more precise
                   6337:    * curvature will be obtained if estepm is as small as stepm. */
                   6338: 
                   6339:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6340:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6341:      nhstepm is the number of hstepm from age to agelim 
                   6342:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  6343:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  6344:      and note for a fixed period like estepm months */
                   6345:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6346:      survival function given by stepm (the optimization length). Unfortunately it
                   6347:      means that if the survival funtion is printed only each two years of age and if
                   6348:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6349:      results. So we changed our mind and took the option of the best precision.
                   6350:   */
                   6351:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6352: 
                   6353:   agelim=AGESUP;
                   6354:   /* If stepm=6 months */
                   6355:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   6356:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   6357:     
                   6358: /* nhstepm age range expressed in number of stepm */
                   6359:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6360:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6361:   /* if (stepm >= YEARM) hstepm=1;*/
                   6362:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6363:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6364: 
                   6365:   for (age=bage; age<=fage; age ++){ 
                   6366:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6367:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6368:     /* if (stepm >= YEARM) hstepm=1;*/
                   6369:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   6370: 
                   6371:     /* If stepm=6 months */
                   6372:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6373:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
1.330     brouard  6374:     /* 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  6375:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  6376:     
                   6377:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6378:     
                   6379:     printf("%d|",(int)age);fflush(stdout);
                   6380:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6381:     
                   6382:     /* Computing expectancies */
                   6383:     for(i=1; i<=nlstate;i++)
                   6384:       for(j=1; j<=nlstate;j++)
                   6385:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6386:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   6387:          
                   6388:          /* 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]);*/
                   6389: 
                   6390:        }
                   6391: 
                   6392:     fprintf(ficreseij,"%3.0f",age );
                   6393:     for(i=1; i<=nlstate;i++){
                   6394:       eip=0;
                   6395:       for(j=1; j<=nlstate;j++){
                   6396:        eip +=eij[i][j][(int)age];
                   6397:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   6398:       }
                   6399:       fprintf(ficreseij,"%9.4f", eip );
                   6400:     }
                   6401:     fprintf(ficreseij,"\n");
                   6402:     
                   6403:   }
                   6404:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6405:   printf("\n");
                   6406:   fprintf(ficlog,"\n");
                   6407:   
                   6408: }
                   6409: 
1.235     brouard  6410:  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  6411: 
                   6412: {
                   6413:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  6414:      to initial status i, ei. .
1.126     brouard  6415:   */
1.336     brouard  6416:   /* Very time consuming function, but already optimized with precov */
1.126     brouard  6417:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   6418:   int nhstepma, nstepma; /* Decreasing with age */
                   6419:   double age, agelim, hf;
                   6420:   double ***p3matp, ***p3matm, ***varhe;
                   6421:   double **dnewm,**doldm;
                   6422:   double *xp, *xm;
                   6423:   double **gp, **gm;
                   6424:   double ***gradg, ***trgradg;
                   6425:   int theta;
                   6426: 
                   6427:   double eip, vip;
                   6428: 
                   6429:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   6430:   xp=vector(1,npar);
                   6431:   xm=vector(1,npar);
                   6432:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   6433:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   6434:   
                   6435:   pstamp(ficresstdeij);
                   6436:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   6437:   fprintf(ficresstdeij,"# Age");
                   6438:   for(i=1; i<=nlstate;i++){
                   6439:     for(j=1; j<=nlstate;j++)
                   6440:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   6441:     fprintf(ficresstdeij," e%1d. ",i);
                   6442:   }
                   6443:   fprintf(ficresstdeij,"\n");
                   6444: 
                   6445:   pstamp(ficrescveij);
                   6446:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   6447:   fprintf(ficrescveij,"# Age");
                   6448:   for(i=1; i<=nlstate;i++)
                   6449:     for(j=1; j<=nlstate;j++){
                   6450:       cptj= (j-1)*nlstate+i;
                   6451:       for(i2=1; i2<=nlstate;i2++)
                   6452:        for(j2=1; j2<=nlstate;j2++){
                   6453:          cptj2= (j2-1)*nlstate+i2;
                   6454:          if(cptj2 <= cptj)
                   6455:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   6456:        }
                   6457:     }
                   6458:   fprintf(ficrescveij,"\n");
                   6459:   
                   6460:   if(estepm < stepm){
                   6461:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6462:   }
                   6463:   else  hstepm=estepm;   
                   6464:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6465:    * This is mainly to measure the difference between two models: for example
                   6466:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6467:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6468:    * progression in between and thus overestimating or underestimating according
                   6469:    * to the curvature of the survival function. If, for the same date, we 
                   6470:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6471:    * to compare the new estimate of Life expectancy with the same linear 
                   6472:    * hypothesis. A more precise result, taking into account a more precise
                   6473:    * curvature will be obtained if estepm is as small as stepm. */
                   6474: 
                   6475:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6476:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6477:      nhstepm is the number of hstepm from age to agelim 
                   6478:      nstepm is the number of stepm from age to agelin. 
                   6479:      Look at hpijx to understand the reason of that which relies in memory size
                   6480:      and note for a fixed period like estepm months */
                   6481:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6482:      survival function given by stepm (the optimization length). Unfortunately it
                   6483:      means that if the survival funtion is printed only each two years of age and if
                   6484:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6485:      results. So we changed our mind and took the option of the best precision.
                   6486:   */
                   6487:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6488: 
                   6489:   /* If stepm=6 months */
                   6490:   /* nhstepm age range expressed in number of stepm */
                   6491:   agelim=AGESUP;
                   6492:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   6493:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6494:   /* if (stepm >= YEARM) hstepm=1;*/
                   6495:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6496:   
                   6497:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6498:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6499:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   6500:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   6501:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   6502:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   6503: 
                   6504:   for (age=bage; age<=fage; age ++){ 
                   6505:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6506:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6507:     /* if (stepm >= YEARM) hstepm=1;*/
                   6508:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  6509:                
1.126     brouard  6510:     /* If stepm=6 months */
                   6511:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6512:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   6513:     
                   6514:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  6515:                
1.126     brouard  6516:     /* Computing  Variances of health expectancies */
                   6517:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   6518:        decrease memory allocation */
                   6519:     for(theta=1; theta <=npar; theta++){
                   6520:       for(i=1; i<=npar; i++){ 
1.222     brouard  6521:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6522:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  6523:       }
1.235     brouard  6524:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   6525:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  6526:                        
1.126     brouard  6527:       for(j=1; j<= nlstate; j++){
1.222     brouard  6528:        for(i=1; i<=nlstate; i++){
                   6529:          for(h=0; h<=nhstepm-1; h++){
                   6530:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   6531:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   6532:          }
                   6533:        }
1.126     brouard  6534:       }
1.218     brouard  6535:                        
1.126     brouard  6536:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  6537:        for(h=0; h<=nhstepm-1; h++){
                   6538:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   6539:        }
1.126     brouard  6540:     }/* End theta */
                   6541:     
                   6542:     
                   6543:     for(h=0; h<=nhstepm-1; h++)
                   6544:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  6545:        for(theta=1; theta <=npar; theta++)
                   6546:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  6547:     
1.218     brouard  6548:                
1.222     brouard  6549:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  6550:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  6551:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  6552:                
1.222     brouard  6553:     printf("%d|",(int)age);fflush(stdout);
                   6554:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6555:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  6556:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  6557:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   6558:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   6559:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   6560:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   6561:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  6562:       }
                   6563:     }
1.320     brouard  6564:     /* if((int)age ==50){ */
                   6565:     /*   printf(" age=%d cij=%d nres=%d varhe[%d][%d]=%f ",(int)age, cij, nres, 1,2,varhe[1][2]); */
                   6566:     /* } */
1.126     brouard  6567:     /* Computing expectancies */
1.235     brouard  6568:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  6569:     for(i=1; i<=nlstate;i++)
                   6570:       for(j=1; j<=nlstate;j++)
1.222     brouard  6571:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6572:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  6573:                                        
1.222     brouard  6574:          /* 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  6575:                                        
1.222     brouard  6576:        }
1.269     brouard  6577: 
                   6578:     /* Standard deviation of expectancies ij */                
1.126     brouard  6579:     fprintf(ficresstdeij,"%3.0f",age );
                   6580:     for(i=1; i<=nlstate;i++){
                   6581:       eip=0.;
                   6582:       vip=0.;
                   6583:       for(j=1; j<=nlstate;j++){
1.222     brouard  6584:        eip += eij[i][j][(int)age];
                   6585:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   6586:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   6587:        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  6588:       }
                   6589:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   6590:     }
                   6591:     fprintf(ficresstdeij,"\n");
1.218     brouard  6592:                
1.269     brouard  6593:     /* Variance of expectancies ij */          
1.126     brouard  6594:     fprintf(ficrescveij,"%3.0f",age );
                   6595:     for(i=1; i<=nlstate;i++)
                   6596:       for(j=1; j<=nlstate;j++){
1.222     brouard  6597:        cptj= (j-1)*nlstate+i;
                   6598:        for(i2=1; i2<=nlstate;i2++)
                   6599:          for(j2=1; j2<=nlstate;j2++){
                   6600:            cptj2= (j2-1)*nlstate+i2;
                   6601:            if(cptj2 <= cptj)
                   6602:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   6603:          }
1.126     brouard  6604:       }
                   6605:     fprintf(ficrescveij,"\n");
1.218     brouard  6606:                
1.126     brouard  6607:   }
                   6608:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   6609:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   6610:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   6611:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   6612:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6613:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6614:   printf("\n");
                   6615:   fprintf(ficlog,"\n");
1.218     brouard  6616:        
1.126     brouard  6617:   free_vector(xm,1,npar);
                   6618:   free_vector(xp,1,npar);
                   6619:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   6620:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   6621:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   6622: }
1.218     brouard  6623:  
1.126     brouard  6624: /************ Variance ******************/
1.235     brouard  6625:  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  6626:  {
1.279     brouard  6627:    /** Variance of health expectancies 
                   6628:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   6629:     * double **newm;
                   6630:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   6631:     */
1.218     brouard  6632:   
                   6633:    /* int movingaverage(); */
                   6634:    double **dnewm,**doldm;
                   6635:    double **dnewmp,**doldmp;
                   6636:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  6637:    int first=0;
1.218     brouard  6638:    int k;
                   6639:    double *xp;
1.279     brouard  6640:    double **gp, **gm;  /**< for var eij */
                   6641:    double ***gradg, ***trgradg; /**< for var eij */
                   6642:    double **gradgp, **trgradgp; /**< for var p point j */
                   6643:    double *gpp, *gmp; /**< for var p point j */
                   6644:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
1.218     brouard  6645:    double ***p3mat;
                   6646:    double age,agelim, hf;
                   6647:    /* double ***mobaverage; */
                   6648:    int theta;
                   6649:    char digit[4];
                   6650:    char digitp[25];
                   6651: 
                   6652:    char fileresprobmorprev[FILENAMELENGTH];
                   6653: 
                   6654:    if(popbased==1){
                   6655:      if(mobilav!=0)
                   6656:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   6657:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   6658:    }
                   6659:    else 
                   6660:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  6661: 
1.218     brouard  6662:    /* if (mobilav!=0) { */
                   6663:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6664:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   6665:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   6666:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   6667:    /*   } */
                   6668:    /* } */
                   6669: 
                   6670:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   6671:    sprintf(digit,"%-d",ij);
                   6672:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   6673:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   6674:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   6675:    strcat(fileresprobmorprev,fileresu);
                   6676:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   6677:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   6678:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   6679:    }
                   6680:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6681:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6682:    pstamp(ficresprobmorprev);
                   6683:    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  6684:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
1.337     brouard  6685: 
                   6686:    /* We use TinvDoQresult[nres][resultmodel[nres][j] we sort according to the equation model and the resultline: it is a choice */
                   6687:    /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ /\* To be done*\/ */
                   6688:    /*   fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   6689:    /* } */
                   6690:    for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */ /* To be done*/
                   6691:      fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  6692:    }
1.337     brouard  6693:    /* for(j=1;j<=cptcoveff;j++)  */
                   6694:    /*   fprintf(ficresprobmorprev," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,TnsdVar[Tvaraff[j]])]); */
1.238     brouard  6695:    fprintf(ficresprobmorprev,"\n");
                   6696: 
1.218     brouard  6697:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   6698:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6699:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   6700:      for(i=1; i<=nlstate;i++)
                   6701:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   6702:    }  
                   6703:    fprintf(ficresprobmorprev,"\n");
                   6704:   
                   6705:    fprintf(ficgp,"\n# Routine varevsij");
                   6706:    fprintf(ficgp,"\nunset title \n");
                   6707:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   6708:    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");
                   6709:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  6710: 
1.218     brouard  6711:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6712:    pstamp(ficresvij);
                   6713:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   6714:    if(popbased==1)
                   6715:      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);
                   6716:    else
                   6717:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   6718:    fprintf(ficresvij,"# Age");
                   6719:    for(i=1; i<=nlstate;i++)
                   6720:      for(j=1; j<=nlstate;j++)
                   6721:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   6722:    fprintf(ficresvij,"\n");
                   6723: 
                   6724:    xp=vector(1,npar);
                   6725:    dnewm=matrix(1,nlstate,1,npar);
                   6726:    doldm=matrix(1,nlstate,1,nlstate);
                   6727:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   6728:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6729: 
                   6730:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   6731:    gpp=vector(nlstate+1,nlstate+ndeath);
                   6732:    gmp=vector(nlstate+1,nlstate+ndeath);
                   6733:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  6734:   
1.218     brouard  6735:    if(estepm < stepm){
                   6736:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   6737:    }
                   6738:    else  hstepm=estepm;   
                   6739:    /* For example we decided to compute the life expectancy with the smallest unit */
                   6740:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6741:       nhstepm is the number of hstepm from age to agelim 
                   6742:       nstepm is the number of stepm from age to agelim. 
                   6743:       Look at function hpijx to understand why because of memory size limitations, 
                   6744:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   6745:       survival function given by stepm (the optimization length). Unfortunately it
                   6746:       means that if the survival funtion is printed every two years of age and if
                   6747:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6748:       results. So we changed our mind and took the option of the best precision.
                   6749:    */
                   6750:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6751:    agelim = AGESUP;
                   6752:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6753:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6754:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6755:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6756:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   6757:      gp=matrix(0,nhstepm,1,nlstate);
                   6758:      gm=matrix(0,nhstepm,1,nlstate);
                   6759:                
                   6760:                
                   6761:      for(theta=1; theta <=npar; theta++){
                   6762:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   6763:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6764:        }
1.279     brouard  6765:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   6766:        * returns into prlim .
1.288     brouard  6767:        */
1.242     brouard  6768:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  6769: 
                   6770:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  6771:        if (popbased==1) {
                   6772:         if(mobilav ==0){
                   6773:           for(i=1; i<=nlstate;i++)
                   6774:             prlim[i][i]=probs[(int)age][i][ij];
                   6775:         }else{ /* mobilav */ 
                   6776:           for(i=1; i<=nlstate;i++)
                   6777:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6778:         }
                   6779:        }
1.295     brouard  6780:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  6781:        */                      
                   6782:        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  6783:        /**< 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  6784:        * at horizon h in state j including mortality.
                   6785:        */
1.218     brouard  6786:        for(j=1; j<= nlstate; j++){
                   6787:         for(h=0; h<=nhstepm; h++){
                   6788:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   6789:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6790:         }
                   6791:        }
1.279     brouard  6792:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  6793:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  6794:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  6795:        */
                   6796:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6797:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   6798:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  6799:        }
                   6800:        
                   6801:        /* Again with minus shift */
1.218     brouard  6802:                        
                   6803:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   6804:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6805: 
1.242     brouard  6806:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  6807:                        
                   6808:        if (popbased==1) {
                   6809:         if(mobilav ==0){
                   6810:           for(i=1; i<=nlstate;i++)
                   6811:             prlim[i][i]=probs[(int)age][i][ij];
                   6812:         }else{ /* mobilav */ 
                   6813:           for(i=1; i<=nlstate;i++)
                   6814:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6815:         }
                   6816:        }
                   6817:                        
1.235     brouard  6818:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  6819:                        
                   6820:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   6821:         for(h=0; h<=nhstepm; h++){
                   6822:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   6823:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6824:         }
                   6825:        }
                   6826:        /* This for computing probability of death (h=1 means
                   6827:          computed over hstepm matrices product = hstepm*stepm months) 
                   6828:          as a weighted average of prlim.
                   6829:        */
                   6830:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6831:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   6832:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   6833:        }    
1.279     brouard  6834:        /* end shifting computations */
                   6835: 
                   6836:        /**< Computing gradient matrix at horizon h 
                   6837:        */
1.218     brouard  6838:        for(j=1; j<= nlstate; j++) /* vareij */
                   6839:         for(h=0; h<=nhstepm; h++){
                   6840:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   6841:         }
1.279     brouard  6842:        /**< Gradient of overall mortality p.3 (or p.j) 
                   6843:        */
                   6844:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
1.218     brouard  6845:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   6846:        }
                   6847:                        
                   6848:      } /* End theta */
1.279     brouard  6849:      
                   6850:      /* We got the gradient matrix for each theta and state j */               
1.218     brouard  6851:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   6852:                
                   6853:      for(h=0; h<=nhstepm; h++) /* veij */
                   6854:        for(j=1; j<=nlstate;j++)
                   6855:         for(theta=1; theta <=npar; theta++)
                   6856:           trgradg[h][j][theta]=gradg[h][theta][j];
                   6857:                
                   6858:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   6859:        for(theta=1; theta <=npar; theta++)
                   6860:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  6861:      /**< as well as its transposed matrix 
                   6862:       */               
1.218     brouard  6863:                
                   6864:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6865:      for(i=1;i<=nlstate;i++)
                   6866:        for(j=1;j<=nlstate;j++)
                   6867:         vareij[i][j][(int)age] =0.;
1.279     brouard  6868: 
                   6869:      /* Computing trgradg by matcov by gradg at age and summing over h
                   6870:       * and k (nhstepm) formula 15 of article
                   6871:       * Lievre-Brouard-Heathcote
                   6872:       */
                   6873:      
1.218     brouard  6874:      for(h=0;h<=nhstepm;h++){
                   6875:        for(k=0;k<=nhstepm;k++){
                   6876:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   6877:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   6878:         for(i=1;i<=nlstate;i++)
                   6879:           for(j=1;j<=nlstate;j++)
                   6880:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   6881:        }
                   6882:      }
                   6883:                
1.279     brouard  6884:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
                   6885:       * p.j overall mortality formula 49 but computed directly because
                   6886:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   6887:       * wix is independent of theta.
                   6888:       */
1.218     brouard  6889:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   6890:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   6891:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   6892:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   6893:         varppt[j][i]=doldmp[j][i];
                   6894:      /* end ppptj */
                   6895:      /*  x centered again */
                   6896:                
1.242     brouard  6897:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  6898:                
                   6899:      if (popbased==1) {
                   6900:        if(mobilav ==0){
                   6901:         for(i=1; i<=nlstate;i++)
                   6902:           prlim[i][i]=probs[(int)age][i][ij];
                   6903:        }else{ /* mobilav */ 
                   6904:         for(i=1; i<=nlstate;i++)
                   6905:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   6906:        }
                   6907:      }
                   6908:                
                   6909:      /* This for computing probability of death (h=1 means
                   6910:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   6911:        as a weighted average of prlim.
                   6912:      */
1.235     brouard  6913:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  6914:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6915:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   6916:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   6917:      }    
                   6918:      /* end probability of death */
                   6919:                
                   6920:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   6921:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6922:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   6923:        for(i=1; i<=nlstate;i++){
                   6924:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   6925:        }
                   6926:      } 
                   6927:      fprintf(ficresprobmorprev,"\n");
                   6928:                
                   6929:      fprintf(ficresvij,"%.0f ",age );
                   6930:      for(i=1; i<=nlstate;i++)
                   6931:        for(j=1; j<=nlstate;j++){
                   6932:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   6933:        }
                   6934:      fprintf(ficresvij,"\n");
                   6935:      free_matrix(gp,0,nhstepm,1,nlstate);
                   6936:      free_matrix(gm,0,nhstepm,1,nlstate);
                   6937:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   6938:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   6939:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6940:    } /* End age */
                   6941:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   6942:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   6943:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   6944:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   6945:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   6946:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   6947:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   6948:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   6949:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   6950:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   6951:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6952:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6953:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   6954:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   6955:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   6956:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   6957:    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);
                   6958:    /*  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  6959:     */
1.218     brouard  6960:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   6961:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  6962: 
1.218     brouard  6963:    free_vector(xp,1,npar);
                   6964:    free_matrix(doldm,1,nlstate,1,nlstate);
                   6965:    free_matrix(dnewm,1,nlstate,1,npar);
                   6966:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6967:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   6968:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6969:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6970:    fclose(ficresprobmorprev);
                   6971:    fflush(ficgp);
                   6972:    fflush(fichtm); 
                   6973:  }  /* end varevsij */
1.126     brouard  6974: 
                   6975: /************ Variance of prevlim ******************/
1.269     brouard  6976:  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  6977: {
1.205     brouard  6978:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  6979:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  6980: 
1.268     brouard  6981:   double **dnewmpar,**doldm;
1.126     brouard  6982:   int i, j, nhstepm, hstepm;
                   6983:   double *xp;
                   6984:   double *gp, *gm;
                   6985:   double **gradg, **trgradg;
1.208     brouard  6986:   double **mgm, **mgp;
1.126     brouard  6987:   double age,agelim;
                   6988:   int theta;
                   6989:   
                   6990:   pstamp(ficresvpl);
1.288     brouard  6991:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  6992:   fprintf(ficresvpl,"# Age ");
                   6993:   if(nresult >=1)
                   6994:     fprintf(ficresvpl," Result# ");
1.126     brouard  6995:   for(i=1; i<=nlstate;i++)
                   6996:       fprintf(ficresvpl," %1d-%1d",i,i);
                   6997:   fprintf(ficresvpl,"\n");
                   6998: 
                   6999:   xp=vector(1,npar);
1.268     brouard  7000:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  7001:   doldm=matrix(1,nlstate,1,nlstate);
                   7002:   
                   7003:   hstepm=1*YEARM; /* Every year of age */
                   7004:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   7005:   agelim = AGESUP;
                   7006:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   7007:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7008:     if (stepm >= YEARM) hstepm=1;
                   7009:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7010:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  7011:     mgp=matrix(1,npar,1,nlstate);
                   7012:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  7013:     gp=vector(1,nlstate);
                   7014:     gm=vector(1,nlstate);
                   7015: 
                   7016:     for(theta=1; theta <=npar; theta++){
                   7017:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   7018:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7019:       }
1.288     brouard  7020:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   7021:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   7022:       /* else */
                   7023:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  7024:       for(i=1;i<=nlstate;i++){
1.126     brouard  7025:        gp[i] = prlim[i][i];
1.208     brouard  7026:        mgp[theta][i] = prlim[i][i];
                   7027:       }
1.126     brouard  7028:       for(i=1; i<=npar; i++) /* Computes gradient */
                   7029:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  7030:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   7031:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   7032:       /* else */
                   7033:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  7034:       for(i=1;i<=nlstate;i++){
1.126     brouard  7035:        gm[i] = prlim[i][i];
1.208     brouard  7036:        mgm[theta][i] = prlim[i][i];
                   7037:       }
1.126     brouard  7038:       for(i=1;i<=nlstate;i++)
                   7039:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  7040:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  7041:     } /* End theta */
                   7042: 
                   7043:     trgradg =matrix(1,nlstate,1,npar);
                   7044: 
                   7045:     for(j=1; j<=nlstate;j++)
                   7046:       for(theta=1; theta <=npar; theta++)
                   7047:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  7048:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7049:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7050:     /*   for(j=1; j<=nlstate;j++){ */
                   7051:     /*         printf(" %d ",j); */
                   7052:     /*         for(theta=1; theta <=npar; theta++) */
                   7053:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7054:     /*         printf("\n "); */
                   7055:     /*   } */
                   7056:     /* } */
                   7057:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7058:     /*   printf("\n gradg %d ",(int)age); */
                   7059:     /*   for(j=1; j<=nlstate;j++){ */
                   7060:     /*         printf("%d ",j); */
                   7061:     /*         for(theta=1; theta <=npar; theta++) */
                   7062:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7063:     /*         printf("\n "); */
                   7064:     /*   } */
                   7065:     /* } */
1.126     brouard  7066: 
                   7067:     for(i=1;i<=nlstate;i++)
                   7068:       varpl[i][(int)age] =0.;
1.209     brouard  7069:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  7070:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7071:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  7072:     }else{
1.268     brouard  7073:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7074:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  7075:     }
1.126     brouard  7076:     for(i=1;i<=nlstate;i++)
                   7077:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7078: 
                   7079:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  7080:     if(nresult >=1)
                   7081:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  7082:     for(i=1; i<=nlstate;i++){
1.126     brouard  7083:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  7084:       /* for(j=1;j<=nlstate;j++) */
                   7085:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   7086:     }
1.126     brouard  7087:     fprintf(ficresvpl,"\n");
                   7088:     free_vector(gp,1,nlstate);
                   7089:     free_vector(gm,1,nlstate);
1.208     brouard  7090:     free_matrix(mgm,1,npar,1,nlstate);
                   7091:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  7092:     free_matrix(gradg,1,npar,1,nlstate);
                   7093:     free_matrix(trgradg,1,nlstate,1,npar);
                   7094:   } /* End age */
                   7095: 
                   7096:   free_vector(xp,1,npar);
                   7097:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  7098:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   7099: 
                   7100: }
                   7101: 
                   7102: 
                   7103: /************ Variance of backprevalence limit ******************/
1.269     brouard  7104:  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  7105: {
                   7106:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   7107:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   7108: 
                   7109:   double **dnewmpar,**doldm;
                   7110:   int i, j, nhstepm, hstepm;
                   7111:   double *xp;
                   7112:   double *gp, *gm;
                   7113:   double **gradg, **trgradg;
                   7114:   double **mgm, **mgp;
                   7115:   double age,agelim;
                   7116:   int theta;
                   7117:   
                   7118:   pstamp(ficresvbl);
                   7119:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   7120:   fprintf(ficresvbl,"# Age ");
                   7121:   if(nresult >=1)
                   7122:     fprintf(ficresvbl," Result# ");
                   7123:   for(i=1; i<=nlstate;i++)
                   7124:       fprintf(ficresvbl," %1d-%1d",i,i);
                   7125:   fprintf(ficresvbl,"\n");
                   7126: 
                   7127:   xp=vector(1,npar);
                   7128:   dnewmpar=matrix(1,nlstate,1,npar);
                   7129:   doldm=matrix(1,nlstate,1,nlstate);
                   7130:   
                   7131:   hstepm=1*YEARM; /* Every year of age */
                   7132:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   7133:   agelim = AGEINF;
                   7134:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   7135:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7136:     if (stepm >= YEARM) hstepm=1;
                   7137:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7138:     gradg=matrix(1,npar,1,nlstate);
                   7139:     mgp=matrix(1,npar,1,nlstate);
                   7140:     mgm=matrix(1,npar,1,nlstate);
                   7141:     gp=vector(1,nlstate);
                   7142:     gm=vector(1,nlstate);
                   7143: 
                   7144:     for(theta=1; theta <=npar; theta++){
                   7145:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   7146:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7147:       }
                   7148:       if(mobilavproj > 0 )
                   7149:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7150:       else
                   7151:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7152:       for(i=1;i<=nlstate;i++){
                   7153:        gp[i] = bprlim[i][i];
                   7154:        mgp[theta][i] = bprlim[i][i];
                   7155:       }
                   7156:      for(i=1; i<=npar; i++) /* Computes gradient */
                   7157:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   7158:        if(mobilavproj > 0 )
                   7159:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7160:        else
                   7161:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7162:       for(i=1;i<=nlstate;i++){
                   7163:        gm[i] = bprlim[i][i];
                   7164:        mgm[theta][i] = bprlim[i][i];
                   7165:       }
                   7166:       for(i=1;i<=nlstate;i++)
                   7167:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   7168:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   7169:     } /* End theta */
                   7170: 
                   7171:     trgradg =matrix(1,nlstate,1,npar);
                   7172: 
                   7173:     for(j=1; j<=nlstate;j++)
                   7174:       for(theta=1; theta <=npar; theta++)
                   7175:        trgradg[j][theta]=gradg[theta][j];
                   7176:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7177:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7178:     /*   for(j=1; j<=nlstate;j++){ */
                   7179:     /*         printf(" %d ",j); */
                   7180:     /*         for(theta=1; theta <=npar; theta++) */
                   7181:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7182:     /*         printf("\n "); */
                   7183:     /*   } */
                   7184:     /* } */
                   7185:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7186:     /*   printf("\n gradg %d ",(int)age); */
                   7187:     /*   for(j=1; j<=nlstate;j++){ */
                   7188:     /*         printf("%d ",j); */
                   7189:     /*         for(theta=1; theta <=npar; theta++) */
                   7190:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7191:     /*         printf("\n "); */
                   7192:     /*   } */
                   7193:     /* } */
                   7194: 
                   7195:     for(i=1;i<=nlstate;i++)
                   7196:       varbpl[i][(int)age] =0.;
                   7197:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   7198:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7199:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7200:     }else{
                   7201:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7202:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7203:     }
                   7204:     for(i=1;i<=nlstate;i++)
                   7205:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7206: 
                   7207:     fprintf(ficresvbl,"%.0f ",age );
                   7208:     if(nresult >=1)
                   7209:       fprintf(ficresvbl,"%d ",nres );
                   7210:     for(i=1; i<=nlstate;i++)
                   7211:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   7212:     fprintf(ficresvbl,"\n");
                   7213:     free_vector(gp,1,nlstate);
                   7214:     free_vector(gm,1,nlstate);
                   7215:     free_matrix(mgm,1,npar,1,nlstate);
                   7216:     free_matrix(mgp,1,npar,1,nlstate);
                   7217:     free_matrix(gradg,1,npar,1,nlstate);
                   7218:     free_matrix(trgradg,1,nlstate,1,npar);
                   7219:   } /* End age */
                   7220: 
                   7221:   free_vector(xp,1,npar);
                   7222:   free_matrix(doldm,1,nlstate,1,npar);
                   7223:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  7224: 
                   7225: }
                   7226: 
                   7227: /************ Variance of one-step probabilities  ******************/
                   7228: 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  7229:  {
                   7230:    int i, j=0,  k1, l1, tj;
                   7231:    int k2, l2, j1,  z1;
                   7232:    int k=0, l;
                   7233:    int first=1, first1, first2;
1.326     brouard  7234:    int nres=0; /* New */
1.222     brouard  7235:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   7236:    double **dnewm,**doldm;
                   7237:    double *xp;
                   7238:    double *gp, *gm;
                   7239:    double **gradg, **trgradg;
                   7240:    double **mu;
                   7241:    double age, cov[NCOVMAX+1];
                   7242:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   7243:    int theta;
                   7244:    char fileresprob[FILENAMELENGTH];
                   7245:    char fileresprobcov[FILENAMELENGTH];
                   7246:    char fileresprobcor[FILENAMELENGTH];
                   7247:    double ***varpij;
                   7248: 
                   7249:    strcpy(fileresprob,"PROB_"); 
                   7250:    strcat(fileresprob,fileres);
                   7251:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   7252:      printf("Problem with resultfile: %s\n", fileresprob);
                   7253:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   7254:    }
                   7255:    strcpy(fileresprobcov,"PROBCOV_"); 
                   7256:    strcat(fileresprobcov,fileresu);
                   7257:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   7258:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   7259:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   7260:    }
                   7261:    strcpy(fileresprobcor,"PROBCOR_"); 
                   7262:    strcat(fileresprobcor,fileresu);
                   7263:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   7264:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   7265:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   7266:    }
                   7267:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7268:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7269:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7270:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7271:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7272:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7273:    pstamp(ficresprob);
                   7274:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   7275:    fprintf(ficresprob,"# Age");
                   7276:    pstamp(ficresprobcov);
                   7277:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   7278:    fprintf(ficresprobcov,"# Age");
                   7279:    pstamp(ficresprobcor);
                   7280:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   7281:    fprintf(ficresprobcor,"# Age");
1.126     brouard  7282: 
                   7283: 
1.222     brouard  7284:    for(i=1; i<=nlstate;i++)
                   7285:      for(j=1; j<=(nlstate+ndeath);j++){
                   7286:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   7287:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   7288:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   7289:      }  
                   7290:    /* fprintf(ficresprob,"\n");
                   7291:       fprintf(ficresprobcov,"\n");
                   7292:       fprintf(ficresprobcor,"\n");
                   7293:    */
                   7294:    xp=vector(1,npar);
                   7295:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7296:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7297:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   7298:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   7299:    first=1;
                   7300:    fprintf(ficgp,"\n# Routine varprob");
                   7301:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   7302:    fprintf(fichtm,"\n");
                   7303: 
1.288     brouard  7304:    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  7305:    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);
                   7306:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  7307: and drawn. It helps understanding how is the covariance between two incidences.\
                   7308:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  7309:    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  7310: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   7311: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   7312: standard deviations wide on each axis. <br>\
                   7313:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   7314:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   7315: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   7316: 
1.222     brouard  7317:    cov[1]=1;
                   7318:    /* tj=cptcoveff; */
1.225     brouard  7319:    tj = (int) pow(2,cptcoveff);
1.222     brouard  7320:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   7321:    j1=0;
1.332     brouard  7322: 
                   7323:    for(nres=1;nres <=nresult; nres++){ /* For each resultline */
                   7324:    for(j1=1; j1<=tj;j1++){ /* For any combination of dummy covariates, fixed and varying */
1.334     brouard  7325:      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  7326:      if(tj != 1 && TKresult[nres]!= j1)
                   7327:        continue;
                   7328: 
                   7329:    /* for(j1=1; j1<=tj;j1++){  /\* For each valid combination of covariates or only once*\/ */
                   7330:      /* for(nres=1;nres <=1; nres++){ /\* For each resultline *\/ */
                   7331:      /* /\* for(nres=1;nres <=nresult; nres++){ /\\* For each resultline *\\/ *\/ */
1.222     brouard  7332:      if  (cptcovn>0) {
1.334     brouard  7333:        fprintf(ficresprob, "\n#********** Variable ");
                   7334:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   7335:        fprintf(ficgp, "\n#********** Variable ");
                   7336:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   7337:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   7338: 
                   7339:        /* Including quantitative variables of the resultline to be done */
                   7340:        for (z1=1; z1<=cptcovs; z1++){ /* Loop on each variable of this resultline  */
1.338     brouard  7341:         printf("Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model);
                   7342:         fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model);
                   7343:         /* 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  7344:         if(Dummy[modelresult[nres][z1]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to z1 in resultline  */
                   7345:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed referenced to model equation */
                   7346:             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  */
                   7347:             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  */
                   7348:             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  */
                   7349:             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  */
                   7350:             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  */
                   7351:             fprintf(ficresprob,"fixed ");
                   7352:             fprintf(ficresprobcov,"fixed ");
                   7353:             fprintf(ficgp,"fixed ");
                   7354:             fprintf(fichtmcov,"fixed ");
                   7355:             fprintf(ficresprobcor,"fixed ");
                   7356:           }else{
                   7357:             fprintf(ficresprob,"varyi ");
                   7358:             fprintf(ficresprobcov,"varyi ");
                   7359:             fprintf(ficgp,"varyi ");
                   7360:             fprintf(fichtmcov,"varyi ");
                   7361:             fprintf(ficresprobcor,"varyi ");
                   7362:           }
                   7363:         }else if(Dummy[modelresult[nres][z1]]==1){ /* Quanti variable */
                   7364:           /* For each selected (single) quantitative value */
1.337     brouard  7365:           fprintf(ficresprob," V%d=%lg ",Tvqresult[nres][z1],Tqresult[nres][z1]);
1.334     brouard  7366:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed */
                   7367:             fprintf(ficresprob,"fixed ");
                   7368:             fprintf(ficresprobcov,"fixed ");
                   7369:             fprintf(ficgp,"fixed ");
                   7370:             fprintf(fichtmcov,"fixed ");
                   7371:             fprintf(ficresprobcor,"fixed ");
                   7372:           }else{
                   7373:             fprintf(ficresprob,"varyi ");
                   7374:             fprintf(ficresprobcov,"varyi ");
                   7375:             fprintf(ficgp,"varyi ");
                   7376:             fprintf(fichtmcov,"varyi ");
                   7377:             fprintf(ficresprobcor,"varyi ");
                   7378:           }
                   7379:         }else{
                   7380:           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 */
                   7381:           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 */
                   7382:           exit(1);
                   7383:         }
                   7384:        } /* End loop on variable of this resultline */
                   7385:        /* for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]); */
1.222     brouard  7386:        fprintf(ficresprob, "**********\n#\n");
                   7387:        fprintf(ficresprobcov, "**********\n#\n");
                   7388:        fprintf(ficgp, "**********\n#\n");
                   7389:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   7390:        fprintf(ficresprobcor, "**********\n#");    
                   7391:        if(invalidvarcomb[j1]){
                   7392:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   7393:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   7394:         continue;
                   7395:        }
                   7396:      }
                   7397:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   7398:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7399:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   7400:      gm=vector(1,(nlstate)*(nlstate+ndeath));
1.334     brouard  7401:      for (age=bage; age<=fage; age ++){ /* Fo each age we feed the model equation with covariates, using precov as in hpxij() ? */
1.222     brouard  7402:        cov[2]=age;
                   7403:        if(nagesqr==1)
                   7404:         cov[3]= age*age;
1.334     brouard  7405:        /* New code end of combination but for each resultline */
                   7406:        for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   7407:         if(Typevar[k1]==1){ /* A product with age */
                   7408:           cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.326     brouard  7409:         }else{
1.334     brouard  7410:           cov[2+nagesqr+k1]=precov[nres][k1];
1.326     brouard  7411:         }
1.334     brouard  7412:        }/* End of loop on model equation */
                   7413: /* Old code */
                   7414:        /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   7415:        /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)]; *\/ */
                   7416:        /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   7417:        /*       /\* Here comes the value of the covariate 'j1' after renumbering k with single dummy covariates *\/ */
                   7418:        /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(j1,TnsdVar[TvarsD[k]])]; */
                   7419:        /*       /\*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*\//\* j1 1 2 3 4 */
                   7420:        /*                                                                  * 1  1 1 1 1 */
                   7421:        /*                                                                  * 2  2 1 1 1 */
                   7422:        /*                                                                  * 3  1 2 1 1 */
                   7423:        /*                                                                  *\/ */
                   7424:        /*       /\* nbcode[1][1]=0 nbcode[1][2]=1;*\/ */
                   7425:        /* } */
                   7426:        /* /\* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   7427:        /* /\* ) p nbcode[Tvar[Tage[k]]][(1 & (ij-1) >> (k-1))+1] *\/ */
                   7428:        /* /\*for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; *\/ */
                   7429:        /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   7430:        /*       if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   7431:        /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(j1,TnsdVar[Tvar[Tage[k]]])]*cov[2]; */
                   7432:        /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7433:        /*       } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   7434:        /*         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]); */
                   7435:        /*         /\* cov[2+nagesqr+Tage[k]]=meanq[k]/idq[k]*cov[2];/\\* Using the mean of quantitative variable Tvar[Tage[k]] /\\* Tqresult[nres][k]; *\\/ *\/ */
                   7436:        /*         /\* exit(1); *\/ */
                   7437:        /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   7438:        /*       } */
                   7439:        /*       /\* cov[2+Tage[k]+nagesqr]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7440:        /* } */
                   7441:        /* for (k=1; k<=cptcovprod;k++){/\* For product without age *\/ */
                   7442:        /*       if(Dummy[Tvard[k][1]]==0){ */
                   7443:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7444:        /*           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]])]; */
                   7445:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7446:        /*         }else{ /\* Should we use the mean of the quantitative variables? *\/ */
                   7447:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,TnsdVar[Tvard[k][1]])] * Tqresult[nres][resultmodel[nres][k]]; */
                   7448:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   7449:        /*         } */
                   7450:        /*       }else{ */
                   7451:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7452:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(j1,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][TnsdVar[Tvard[k][1]]]; */
                   7453:        /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   7454:        /*         }else{ */
                   7455:        /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][TnsdVar[Tvard[k][1]]]*  Tqinvresult[nres][TnsdVar[Tvard[k][2]]]; */
                   7456:        /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   7457:        /*         } */
                   7458:        /*       } */
                   7459:        /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7460:        /* } */                 
1.326     brouard  7461: /* For each age and combination of dummy covariates we slightly move the parameters of delti in order to get the gradient*/                    
1.222     brouard  7462:        for(theta=1; theta <=npar; theta++){
                   7463:         for(i=1; i<=npar; i++)
                   7464:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  7465:                                
1.222     brouard  7466:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  7467:                                
1.222     brouard  7468:         k=0;
                   7469:         for(i=1; i<= (nlstate); i++){
                   7470:           for(j=1; j<=(nlstate+ndeath);j++){
                   7471:             k=k+1;
                   7472:             gp[k]=pmmij[i][j];
                   7473:           }
                   7474:         }
1.220     brouard  7475:                                
1.222     brouard  7476:         for(i=1; i<=npar; i++)
                   7477:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  7478:                                
1.222     brouard  7479:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   7480:         k=0;
                   7481:         for(i=1; i<=(nlstate); i++){
                   7482:           for(j=1; j<=(nlstate+ndeath);j++){
                   7483:             k=k+1;
                   7484:             gm[k]=pmmij[i][j];
                   7485:           }
                   7486:         }
1.220     brouard  7487:                                
1.222     brouard  7488:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   7489:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   7490:        }
1.126     brouard  7491: 
1.222     brouard  7492:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   7493:         for(theta=1; theta <=npar; theta++)
                   7494:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  7495:                        
1.222     brouard  7496:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   7497:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  7498:                        
1.222     brouard  7499:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  7500:                        
1.222     brouard  7501:        k=0;
                   7502:        for(i=1; i<=(nlstate); i++){
                   7503:         for(j=1; j<=(nlstate+ndeath);j++){
                   7504:           k=k+1;
                   7505:           mu[k][(int) age]=pmmij[i][j];
                   7506:         }
                   7507:        }
                   7508:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   7509:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   7510:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  7511:                        
1.222     brouard  7512:        /*printf("\n%d ",(int)age);
                   7513:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7514:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7515:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7516:         }*/
1.220     brouard  7517:                        
1.222     brouard  7518:        fprintf(ficresprob,"\n%d ",(int)age);
                   7519:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   7520:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  7521:                        
1.222     brouard  7522:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   7523:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   7524:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7525:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   7526:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   7527:        }
                   7528:        i=0;
                   7529:        for (k=1; k<=(nlstate);k++){
                   7530:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   7531:           i++;
                   7532:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   7533:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   7534:           for (j=1; j<=i;j++){
                   7535:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   7536:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   7537:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   7538:           }
                   7539:         }
                   7540:        }/* end of loop for state */
                   7541:      } /* end of loop for age */
                   7542:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7543:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7544:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7545:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7546:     
                   7547:      /* Confidence intervalle of pij  */
                   7548:      /*
                   7549:        fprintf(ficgp,"\nunset parametric;unset label");
                   7550:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   7551:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   7552:        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);
                   7553:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   7554:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   7555:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   7556:      */
                   7557:                
                   7558:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   7559:      first1=1;first2=2;
                   7560:      for (k2=1; k2<=(nlstate);k2++){
                   7561:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   7562:         if(l2==k2) continue;
                   7563:         j=(k2-1)*(nlstate+ndeath)+l2;
                   7564:         for (k1=1; k1<=(nlstate);k1++){
                   7565:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   7566:             if(l1==k1) continue;
                   7567:             i=(k1-1)*(nlstate+ndeath)+l1;
                   7568:             if(i<=j) continue;
                   7569:             for (age=bage; age<=fage; age ++){ 
                   7570:               if ((int)age %5==0){
                   7571:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   7572:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7573:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7574:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   7575:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   7576:                 c12=cv12/sqrt(v1*v2);
                   7577:                 /* Computing eigen value of matrix of covariance */
                   7578:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7579:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7580:                 if ((lc2 <0) || (lc1 <0) ){
                   7581:                   if(first2==1){
                   7582:                     first1=0;
                   7583:                     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);
                   7584:                   }
                   7585:                   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);
                   7586:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   7587:                   /* lc2=fabs(lc2); */
                   7588:                 }
1.220     brouard  7589:                                                                
1.222     brouard  7590:                 /* Eigen vectors */
1.280     brouard  7591:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   7592:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7593:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7594:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   7595:                 }else
                   7596:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  7597:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   7598:                 v21=(lc1-v1)/cv12*v11;
                   7599:                 v12=-v21;
                   7600:                 v22=v11;
                   7601:                 tnalp=v21/v11;
                   7602:                 if(first1==1){
                   7603:                   first1=0;
                   7604:                   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);
                   7605:                 }
                   7606:                 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);
                   7607:                 /*printf(fignu*/
                   7608:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   7609:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   7610:                 if(first==1){
                   7611:                   first=0;
                   7612:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   7613:                   fprintf(ficgp,"\nset parametric;unset label");
                   7614:                   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);
                   7615:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  7616:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  7617:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  7618: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  7619:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   7620:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7621:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7622:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   7623:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7624:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7625:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7626:                   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  7627:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   7628:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  7629:                 }else{
                   7630:                   first=0;
                   7631:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   7632:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7633:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7634:                   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  7635:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   7636:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  7637:                 }/* if first */
                   7638:               } /* age mod 5 */
                   7639:             } /* end loop age */
                   7640:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7641:             first=1;
                   7642:           } /*l12 */
                   7643:         } /* k12 */
                   7644:        } /*l1 */
                   7645:      }/* k1 */
1.332     brouard  7646:    }  /* loop on combination of covariates j1 */
1.326     brouard  7647:    } /* loop on nres */
1.222     brouard  7648:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   7649:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   7650:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7651:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   7652:    free_vector(xp,1,npar);
                   7653:    fclose(ficresprob);
                   7654:    fclose(ficresprobcov);
                   7655:    fclose(ficresprobcor);
                   7656:    fflush(ficgp);
                   7657:    fflush(fichtmcov);
                   7658:  }
1.126     brouard  7659: 
                   7660: 
                   7661: /******************* Printing html file ***********/
1.201     brouard  7662: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  7663:                  int lastpass, int stepm, int weightopt, char model[],\
                   7664:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  7665:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   7666:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   7667:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.237     brouard  7668:   int jj1, k1, i1, cpt, k4, nres;
1.319     brouard  7669:   /* In fact some results are already printed in fichtm which is open */
1.126     brouard  7670:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   7671:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   7672: </ul>");
1.319     brouard  7673: /*    fprintf(fichtm,"<ul><li> model=1+age+%s\n \ */
                   7674: /* </ul>", model); */
1.214     brouard  7675:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   7676:    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",
                   7677:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
1.332     brouard  7678:    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  7679:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   7680:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  7681:    fprintf(fichtm,"\
                   7682:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  7683:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  7684:    fprintf(fichtm,"\
1.217     brouard  7685:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   7686:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   7687:    fprintf(fichtm,"\
1.288     brouard  7688:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7689:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  7690:    fprintf(fichtm,"\
1.288     brouard  7691:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  7692:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   7693:    fprintf(fichtm,"\
1.211     brouard  7694:  - (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  7695:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7696:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  7697:    if(prevfcast==1){
                   7698:      fprintf(fichtm,"\
                   7699:  - Prevalence projections by age and states:                           \
1.201     brouard  7700:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  7701:    }
1.126     brouard  7702: 
                   7703: 
1.225     brouard  7704:    m=pow(2,cptcoveff);
1.222     brouard  7705:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7706: 
1.317     brouard  7707:    fprintf(fichtm," \n<ul><li><b>Graphs (first order)</b></li><p>");
1.264     brouard  7708: 
                   7709:    jj1=0;
                   7710: 
                   7711:    fprintf(fichtm," \n<ul>");
1.337     brouard  7712:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   7713:      /* k1=nres; */
1.338     brouard  7714:      k1=TKresult[nres];
                   7715:      if(TKresult[nres]==0)k1=1; /* To be checked for no result */
1.337     brouard  7716:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   7717:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   7718:    /*     continue; */
1.264     brouard  7719:      jj1++;
                   7720:      if (cptcovn > 0) {
                   7721:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
1.337     brouard  7722:        for (cpt=1; cpt<=cptcovs;cpt++){ /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   7723:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  7724:        }
1.337     brouard  7725:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   7726:        /*       fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   7727:        /* } */
                   7728:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   7729:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   7730:        /* } */
1.264     brouard  7731:        fprintf(fichtm,"\">");
                   7732:        
                   7733:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   7734:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  7735:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   7736:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  7737:        }
1.337     brouard  7738:        /* fprintf(fichtm,"************ Results for covariates"); */
                   7739:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   7740:        /*       fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   7741:        /* } */
                   7742:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   7743:        /*       fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   7744:        /* } */
1.264     brouard  7745:        if(invalidvarcomb[k1]){
                   7746:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   7747:         continue;
                   7748:        }
                   7749:        fprintf(fichtm,"</a></li>");
                   7750:      } /* cptcovn >0 */
                   7751:    }
1.317     brouard  7752:    fprintf(fichtm," \n</ul>");
1.264     brouard  7753: 
1.222     brouard  7754:    jj1=0;
1.237     brouard  7755: 
1.337     brouard  7756:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   7757:      /* k1=nres; */
1.338     brouard  7758:      k1=TKresult[nres];
                   7759:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  7760:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   7761:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   7762:    /*     continue; */
1.220     brouard  7763: 
1.222     brouard  7764:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7765:      jj1++;
                   7766:      if (cptcovn > 0) {
1.264     brouard  7767:        fprintf(fichtm,"\n<p><a name=\"rescov");
1.337     brouard  7768:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   7769:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  7770:        }
1.337     brouard  7771:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   7772:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   7773:        /* } */
1.264     brouard  7774:        fprintf(fichtm,"\"</a>");
                   7775:  
1.222     brouard  7776:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  7777:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   7778:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   7779:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  7780:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   7781:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  7782:        }
1.230     brouard  7783:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.338     brouard  7784:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.222     brouard  7785:        if(invalidvarcomb[k1]){
                   7786:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   7787:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   7788:         continue;
                   7789:        }
                   7790:      }
                   7791:      /* aij, bij */
1.259     brouard  7792:      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  7793: <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  7794:      /* Pij */
1.241     brouard  7795:      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> \
                   7796: <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  7797:      /* Quasi-incidences */
                   7798:      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  7799:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  7800:  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  7801: 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> \
                   7802: <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  7803:      /* Survival functions (period) in state j */
                   7804:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  7805:        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);
                   7806:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   7807:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.222     brouard  7808:      }
                   7809:      /* State specific survival functions (period) */
                   7810:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  7811:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
                   7812:  And probability to be observed in various states (up to %d) being in state %d at different ages.      \
1.329     brouard  7813:  <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);
                   7814:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   7815:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.222     brouard  7816:      }
1.288     brouard  7817:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  7818:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  7819:        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  7820:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
1.329     brouard  7821:       fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.222     brouard  7822:      }
1.296     brouard  7823:      if(prevbcast==1){
1.288     brouard  7824:        /* Backward prevalence in each health state */
1.222     brouard  7825:        for(cpt=1; cpt<=nlstate;cpt++){
1.338     brouard  7826:         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);
                   7827:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJB_"),subdirf2(optionfilefiname,"PIJB_"));
                   7828:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.222     brouard  7829:        }
1.217     brouard  7830:      }
1.222     brouard  7831:      if(prevfcast==1){
1.288     brouard  7832:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  7833:        for(cpt=1; cpt<=nlstate;cpt++){
1.314     brouard  7834:         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);
                   7835:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
                   7836:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
                   7837:                 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  7838:        }
                   7839:      }
1.296     brouard  7840:      if(prevbcast==1){
1.268     brouard  7841:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   7842:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  7843:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
                   7844:  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 \
                   7845:  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  7846: 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);
                   7847:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
                   7848:         fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
1.268     brouard  7849:        }
                   7850:      }
1.220     brouard  7851:         
1.222     brouard  7852:      for(cpt=1; cpt<=nlstate;cpt++) {
1.314     brouard  7853:        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);
                   7854:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
                   7855:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
1.222     brouard  7856:      }
                   7857:      /* } /\* end i1 *\/ */
1.337     brouard  7858:    }/* End k1=nres */
1.222     brouard  7859:    fprintf(fichtm,"</ul>");
1.126     brouard  7860: 
1.222     brouard  7861:    fprintf(fichtm,"\
1.126     brouard  7862: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  7863:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  7864:  - 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  7865: But because parameters are usually highly correlated (a higher incidence of disability \
                   7866: and a higher incidence of recovery can give very close observed transition) it might \
                   7867: be very useful to look not only at linear confidence intervals estimated from the \
                   7868: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   7869: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   7870: covariance matrix of the one-step probabilities. \
                   7871: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  7872: 
1.222     brouard  7873:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   7874:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   7875:    fprintf(fichtm,"\
1.126     brouard  7876:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7877:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  7878: 
1.222     brouard  7879:    fprintf(fichtm,"\
1.126     brouard  7880:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7881:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   7882:    fprintf(fichtm,"\
1.126     brouard  7883:  - 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): \
                   7884:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7885:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  7886:    fprintf(fichtm,"\
1.126     brouard  7887:  - (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): \
                   7888:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7889:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  7890:    fprintf(fichtm,"\
1.288     brouard  7891:  - 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  7892:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   7893:    fprintf(fichtm,"\
1.128     brouard  7894:  - 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  7895:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   7896:    fprintf(fichtm,"\
1.288     brouard  7897:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  7898:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  7899: 
                   7900: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   7901: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   7902: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   7903: /*     <br>",fileres,fileres,fileres,fileres); */
                   7904: /*  else  */
1.338     brouard  7905: /*    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  7906:    fflush(fichtm);
1.126     brouard  7907: 
1.225     brouard  7908:    m=pow(2,cptcoveff);
1.222     brouard  7909:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7910: 
1.317     brouard  7911:    fprintf(fichtm," <ul><li><b>Graphs (second order)</b></li><p>");
                   7912: 
                   7913:   jj1=0;
                   7914: 
                   7915:    fprintf(fichtm," \n<ul>");
1.337     brouard  7916:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   7917:      /* k1=nres; */
1.338     brouard  7918:      k1=TKresult[nres];
1.337     brouard  7919:      /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   7920:      /* if(m != 1 && TKresult[nres]!= k1) */
                   7921:      /*   continue; */
1.317     brouard  7922:      jj1++;
                   7923:      if (cptcovn > 0) {
                   7924:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescovsecond");
1.337     brouard  7925:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   7926:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  7927:        }
                   7928:        fprintf(fichtm,"\">");
                   7929:        
                   7930:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   7931:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  7932:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   7933:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  7934:        }
                   7935:        if(invalidvarcomb[k1]){
                   7936:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   7937:         continue;
                   7938:        }
                   7939:        fprintf(fichtm,"</a></li>");
                   7940:      } /* cptcovn >0 */
1.337     brouard  7941:    } /* End nres */
1.317     brouard  7942:    fprintf(fichtm," \n</ul>");
                   7943: 
1.222     brouard  7944:    jj1=0;
1.237     brouard  7945: 
1.241     brouard  7946:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  7947:      /* k1=nres; */
1.338     brouard  7948:      k1=TKresult[nres];
                   7949:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  7950:      /* for(k1=1; k1<=m;k1++){ */
                   7951:      /* if(m != 1 && TKresult[nres]!= k1) */
                   7952:      /*   continue; */
1.222     brouard  7953:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7954:      jj1++;
1.126     brouard  7955:      if (cptcovn > 0) {
1.317     brouard  7956:        fprintf(fichtm,"\n<p><a name=\"rescovsecond");
1.337     brouard  7957:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   7958:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  7959:        }
                   7960:        fprintf(fichtm,"\"</a>");
                   7961:        
1.126     brouard  7962:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  7963:        for (cpt=1; cpt<=cptcovs;cpt++){  /**< cptcoveff number of variables */
                   7964:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   7965:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  7966:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
1.317     brouard  7967:        }
1.237     brouard  7968: 
1.338     brouard  7969:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.220     brouard  7970: 
1.222     brouard  7971:        if(invalidvarcomb[k1]){
                   7972:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   7973:         continue;
                   7974:        }
1.337     brouard  7975:      } /* If cptcovn >0 */
1.126     brouard  7976:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  7977:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.314     brouard  7978: 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);
                   7979:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   7980:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
1.126     brouard  7981:      }
                   7982:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.314     brouard  7983: health expectancies in each live states (1 to %d). If popbased=1 the smooth (due to the model) \
1.128     brouard  7984: true period expectancies (those weighted with period prevalences are also\
                   7985:  drawn in addition to the population based expectancies computed using\
1.314     brouard  7986:  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);
                   7987:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
                   7988:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  7989:      /* } /\* end i1 *\/ */
1.241     brouard  7990:   }/* End nres */
1.222     brouard  7991:    fprintf(fichtm,"</ul>");
                   7992:    fflush(fichtm);
1.126     brouard  7993: }
                   7994: 
                   7995: /******************* Gnuplot file **************/
1.296     brouard  7996: 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  7997: 
                   7998:   char dirfileres[132],optfileres[132];
1.264     brouard  7999:   char gplotcondition[132], gplotlabel[132];
1.237     brouard  8000:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,k4=0,ij=0, ijp=0, l=0;
1.211     brouard  8001:   int lv=0, vlv=0, kl=0;
1.130     brouard  8002:   int ng=0;
1.201     brouard  8003:   int vpopbased;
1.223     brouard  8004:   int ioffset; /* variable offset for columns */
1.270     brouard  8005:   int iyearc=1; /* variable column for year of projection  */
                   8006:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  8007:   int nres=0; /* Index of resultline */
1.266     brouard  8008:   int istart=1; /* For starting graphs in projections */
1.219     brouard  8009: 
1.126     brouard  8010: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   8011: /*     printf("Problem with file %s",optionfilegnuplot); */
                   8012: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   8013: /*   } */
                   8014: 
                   8015:   /*#ifdef windows */
                   8016:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  8017:   /*#endif */
1.225     brouard  8018:   m=pow(2,cptcoveff);
1.126     brouard  8019: 
1.274     brouard  8020:   /* diagram of the model */
                   8021:   fprintf(ficgp,"\n#Diagram of the model \n");
                   8022:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   8023:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   8024:   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);
                   8025: 
                   8026:   fprintf(ficgp,"\n#Centripete arrows (turning in other direction (1-i) instead of (i-1)) \nset for [i=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);
                   8027:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   8028:   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);
                   8029:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   8030:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   8031:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   8032:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   8033: 
1.202     brouard  8034:   /* Contribution to likelihood */
                   8035:   /* Plot the probability implied in the likelihood */
1.223     brouard  8036:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   8037:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   8038:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   8039:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  8040: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  8041:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   8042: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  8043:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   8044:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8045:   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));
                   8046:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8047:   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));
                   8048:   for (i=1; i<= nlstate ; i ++) {
                   8049:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   8050:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   8051:     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);
                   8052:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   8053:       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);
                   8054:     }
                   8055:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8056:   }
                   8057:   /* 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 */               
                   8058:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   8059:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   8060:   fprintf(ficgp,"\nset out;unset log\n");
                   8061:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  8062: 
1.126     brouard  8063:   strcpy(dirfileres,optionfilefiname);
                   8064:   strcpy(optfileres,"vpl");
1.223     brouard  8065:   /* 1eme*/
1.238     brouard  8066:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
1.337     brouard  8067:     /* for (k1=1; k1<= m ; k1 ++){ /\* For each valid combination of covariate *\/ */
1.236     brouard  8068:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8069:        k1=TKresult[nres];
1.338     brouard  8070:        if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.238     brouard  8071:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.337     brouard  8072:        /* if(m != 1 && TKresult[nres]!= k1) */
                   8073:        /*   continue; */
1.238     brouard  8074:        /* We are interested in selected combination by the resultline */
1.246     brouard  8075:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  8076:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  8077:        strcpy(gplotlabel,"(");
1.337     brouard  8078:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8079:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8080:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8081: 
                   8082:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate k get corresponding value lv for combination k1 *\/ */
                   8083:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the value of the covariate corresponding to k1 combination *\\/ *\/ */
                   8084:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8085:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8086:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8087:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8088:        /*   vlv= nbcode[Tvaraff[k]][lv]; /\* vlv is the value of the covariate lv, 0 or 1 *\/ */
                   8089:        /*   /\* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv *\/ */
                   8090:        /*   /\* printf(" V%d=%d ",Tvaraff[k],vlv); *\/ */
                   8091:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8092:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8093:        /* } */
                   8094:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8095:        /*   /\* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); *\/ */
                   8096:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8097:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.264     brouard  8098:        }
                   8099:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  8100:        /* printf("\n#\n"); */
1.238     brouard  8101:        fprintf(ficgp,"\n#\n");
                   8102:        if(invalidvarcomb[k1]){
1.260     brouard  8103:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  8104:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8105:          continue;
                   8106:        }
1.235     brouard  8107:       
1.241     brouard  8108:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   8109:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  8110:        /* 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  8111:        fprintf(ficgp,"set title \"Alive state %d %s model=1+age+%s\" font \"Helvetica,12\"\n",cpt,gplotlabel,model);
1.260     brouard  8112:        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);
                   8113:        /* 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); */
                   8114:       /* k1-1 error should be nres-1*/
1.238     brouard  8115:        for (i=1; i<= nlstate ; i ++) {
                   8116:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8117:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   8118:        }
1.288     brouard  8119:        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  8120:        for (i=1; i<= nlstate ; i ++) {
                   8121:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8122:          else fprintf(ficgp," %%*lf (%%*lf)");
                   8123:        } 
1.260     brouard  8124:        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  8125:        for (i=1; i<= nlstate ; i ++) {
                   8126:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8127:          else fprintf(ficgp," %%*lf (%%*lf)");
                   8128:        }  
1.265     brouard  8129:        /* 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)); */
                   8130:        
                   8131:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   8132:         if(cptcoveff ==0){
1.271     brouard  8133:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  8134:        }else{
                   8135:          kl=0;
                   8136:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  8137:            /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8138:            lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.265     brouard  8139:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8140:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8141:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8142:            vlv= nbcode[Tvaraff[k]][lv];
                   8143:            kl++;
                   8144:            /* 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 *\/ */
                   8145:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8146:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8147:            /* ''  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*/
                   8148:            if(k==cptcoveff){
                   8149:              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], \
                   8150:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   8151:            }else{
                   8152:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   8153:              kl++;
                   8154:            }
                   8155:          } /* end covariate */
                   8156:        } /* end if no covariate */
                   8157: 
1.296     brouard  8158:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  8159:          /* 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  8160:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  8161:          if(cptcoveff ==0){
1.245     brouard  8162:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  8163:          }else{
                   8164:            kl=0;
                   8165:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  8166:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8167:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.238     brouard  8168:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8169:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8170:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8171:              /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8172:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.223     brouard  8173:              kl++;
1.238     brouard  8174:              /* 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 *\/ */
                   8175:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8176:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8177:              /* ''  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*/
                   8178:              if(k==cptcoveff){
1.245     brouard  8179:                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  8180:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  8181:              }else{
1.332     brouard  8182:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]);
1.238     brouard  8183:                kl++;
                   8184:              }
                   8185:            } /* end covariate */
                   8186:          } /* end if no covariate */
1.296     brouard  8187:          if(prevbcast == 1){
1.268     brouard  8188:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   8189:            /* k1-1 error should be nres-1*/
                   8190:            for (i=1; i<= nlstate ; i ++) {
                   8191:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8192:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   8193:            }
1.271     brouard  8194:            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  8195:            for (i=1; i<= nlstate ; i ++) {
                   8196:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8197:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8198:            } 
1.276     brouard  8199:            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  8200:            for (i=1; i<= nlstate ; i ++) {
                   8201:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8202:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8203:            } 
1.274     brouard  8204:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  8205:          } /* end if backprojcast */
1.296     brouard  8206:        } /* end if prevbcast */
1.276     brouard  8207:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   8208:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  8209:       } /* nres */
1.337     brouard  8210:     /* } /\* k1 *\/ */
1.201     brouard  8211:   } /* cpt */
1.235     brouard  8212: 
                   8213:   
1.126     brouard  8214:   /*2 eme*/
1.337     brouard  8215:   /* for (k1=1; k1<= m ; k1 ++){   */
1.238     brouard  8216:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8217:       k1=TKresult[nres];
1.338     brouard  8218:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8219:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8220:       /*       continue; */
1.238     brouard  8221:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  8222:       strcpy(gplotlabel,"(");
1.337     brouard  8223:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8224:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8225:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8226:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8227:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8228:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8229:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8230:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8231:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8232:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8233:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8234:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8235:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8236:       /* } */
                   8237:       /* /\* for(k=1; k <= ncovds; k++){ *\/ */
                   8238:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8239:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8240:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8241:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  8242:       }
1.264     brouard  8243:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8244:       fprintf(ficgp,"\n#\n");
1.223     brouard  8245:       if(invalidvarcomb[k1]){
                   8246:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8247:        continue;
                   8248:       }
1.219     brouard  8249:                        
1.241     brouard  8250:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  8251:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  8252:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   8253:        if(vpopbased==0){
1.238     brouard  8254:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  8255:        }else
1.238     brouard  8256:          fprintf(ficgp,"\nreplot ");
                   8257:        for (i=1; i<= nlstate+1 ; i ++) {
                   8258:          k=2*i;
1.261     brouard  8259:          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  8260:          for (j=1; j<= nlstate+1 ; j ++) {
                   8261:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8262:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8263:          }   
                   8264:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   8265:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
1.261     brouard  8266:          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  8267:          for (j=1; j<= nlstate+1 ; j ++) {
                   8268:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8269:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8270:          }   
                   8271:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  8272:          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  8273:          for (j=1; j<= nlstate+1 ; j ++) {
                   8274:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8275:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8276:          }   
                   8277:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   8278:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   8279:        } /* state */
                   8280:       } /* vpopbased */
1.264     brouard  8281:       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  8282:     } /* end nres */
1.337     brouard  8283:   /* } /\* k1 end 2 eme*\/ */
1.238     brouard  8284:        
                   8285:        
                   8286:   /*3eme*/
1.337     brouard  8287:   /* for (k1=1; k1<= m ; k1 ++){ */
1.238     brouard  8288:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8289:       k1=TKresult[nres];
1.338     brouard  8290:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8291:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8292:       /*       continue; */
1.238     brouard  8293: 
1.332     brouard  8294:       for (cpt=1; cpt<= nlstate ; cpt ++) { /* Fragile no verification of covariate values */
1.261     brouard  8295:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  8296:        strcpy(gplotlabel,"(");
1.337     brouard  8297:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8298:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8299:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8300:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8301:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8302:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8303:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8304:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8305:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8306:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8307:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8308:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8309:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8310:        /* } */
                   8311:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8312:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   8313:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   8314:        }
1.264     brouard  8315:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8316:        fprintf(ficgp,"\n#\n");
                   8317:        if(invalidvarcomb[k1]){
                   8318:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8319:          continue;
                   8320:        }
                   8321:                        
                   8322:        /*       k=2+nlstate*(2*cpt-2); */
                   8323:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  8324:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  8325:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  8326:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  8327: 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  8328:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8329:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8330:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   8331:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8332:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8333:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  8334:                                
1.238     brouard  8335:        */
                   8336:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  8337:          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  8338:          /*    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  8339:                                
1.238     brouard  8340:        } 
1.261     brouard  8341:        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  8342:       }
1.264     brouard  8343:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  8344:     } /* end nres */
1.337     brouard  8345:   /* } /\* end kl 3eme *\/ */
1.126     brouard  8346:   
1.223     brouard  8347:   /* 4eme */
1.201     brouard  8348:   /* Survival functions (period) from state i in state j by initial state i */
1.337     brouard  8349:   /* for (k1=1; k1<=m; k1++){    /\* For each covariate and each value *\/ */
1.238     brouard  8350:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8351:       k1=TKresult[nres];
1.338     brouard  8352:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8353:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8354:       /*       continue; */
1.238     brouard  8355:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  8356:        strcpy(gplotlabel,"(");
1.337     brouard  8357:        fprintf(ficgp,"\n#\n#\n# Survival functions in state %d : 'LIJ_' files, cov=%d state=%d", cpt, k1, cpt);
                   8358:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8359:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8360:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8361:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8362:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8363:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8364:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8365:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8366:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8367:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8368:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8369:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8370:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8371:        /* } */
                   8372:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8373:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8374:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  8375:        }       
1.264     brouard  8376:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8377:        fprintf(ficgp,"\n#\n");
                   8378:        if(invalidvarcomb[k1]){
                   8379:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8380:          continue;
1.223     brouard  8381:        }
1.238     brouard  8382:       
1.241     brouard  8383:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  8384:        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  8385:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8386: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8387:        k=3;
                   8388:        for (i=1; i<= nlstate ; i ++){
                   8389:          if(i==1){
                   8390:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8391:          }else{
                   8392:            fprintf(ficgp,", '' ");
                   8393:          }
                   8394:          l=(nlstate+ndeath)*(i-1)+1;
                   8395:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8396:          for (j=2; j<= nlstate+ndeath ; j ++)
                   8397:            fprintf(ficgp,"+$%d",k+l+j-1);
                   8398:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   8399:        } /* nlstate */
1.264     brouard  8400:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8401:       } /* end cpt state*/ 
                   8402:     } /* end nres */
1.337     brouard  8403:   /* } /\* end covariate k1 *\/   */
1.238     brouard  8404: 
1.220     brouard  8405: /* 5eme */
1.201     brouard  8406:   /* Survival functions (period) from state i in state j by final state j */
1.337     brouard  8407:   /* for (k1=1; k1<= m ; k1++){ /\* For each covariate combination if any *\/ */
1.238     brouard  8408:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8409:       k1=TKresult[nres];
1.338     brouard  8410:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8411:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8412:       /*       continue; */
1.238     brouard  8413:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  8414:        strcpy(gplotlabel,"(");
1.238     brouard  8415:        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  8416:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8417:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8418:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8419:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8420:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8421:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8422:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8423:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8424:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8425:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8426:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8427:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8428:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8429:        /* } */
                   8430:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8431:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8432:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  8433:        }       
1.264     brouard  8434:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8435:        fprintf(ficgp,"\n#\n");
                   8436:        if(invalidvarcomb[k1]){
                   8437:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8438:          continue;
                   8439:        }
1.227     brouard  8440:       
1.241     brouard  8441:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  8442:        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  8443:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8444: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8445:        k=3;
                   8446:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8447:          if(j==1)
                   8448:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8449:          else
                   8450:            fprintf(ficgp,", '' ");
                   8451:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8452:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   8453:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   8454:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   8455:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   8456:        } /* nlstate */
                   8457:        fprintf(ficgp,", '' ");
                   8458:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   8459:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8460:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8461:          if(j < nlstate)
                   8462:            fprintf(ficgp,"$%d +",k+l);
                   8463:          else
                   8464:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   8465:        }
1.264     brouard  8466:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8467:       } /* end cpt state*/ 
1.337     brouard  8468:     /* } /\* end covariate *\/   */
1.238     brouard  8469:   } /* end nres */
1.227     brouard  8470:   
1.220     brouard  8471: /* 6eme */
1.202     brouard  8472:   /* CV preval stable (period) for each covariate */
1.337     brouard  8473:   /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8474:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8475:      k1=TKresult[nres];
1.338     brouard  8476:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8477:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8478:      /*  continue; */
1.255     brouard  8479:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  8480:       strcpy(gplotlabel,"(");      
1.288     brouard  8481:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8482:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8483:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8484:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8485:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8486:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8487:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8488:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8489:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8490:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8491:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8492:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8493:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8494:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8495:       /* } */
                   8496:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8497:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8498:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8499:       }        
1.264     brouard  8500:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8501:       fprintf(ficgp,"\n#\n");
1.223     brouard  8502:       if(invalidvarcomb[k1]){
1.227     brouard  8503:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8504:        continue;
1.223     brouard  8505:       }
1.227     brouard  8506:       
1.241     brouard  8507:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  8508:       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  8509:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8510: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  8511:       k=3; /* Offset */
1.255     brouard  8512:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  8513:        if(i==1)
                   8514:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8515:        else
                   8516:          fprintf(ficgp,", '' ");
1.255     brouard  8517:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  8518:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8519:        for (j=2; j<= nlstate ; j ++)
                   8520:          fprintf(ficgp,"+$%d",k+l+j-1);
                   8521:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  8522:       } /* nlstate */
1.264     brouard  8523:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  8524:     } /* end cpt state*/ 
                   8525:   } /* end covariate */  
1.227     brouard  8526:   
                   8527:   
1.220     brouard  8528: /* 7eme */
1.296     brouard  8529:   if(prevbcast == 1){
1.288     brouard  8530:     /* CV backward prevalence  for each covariate */
1.337     brouard  8531:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8532:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8533:       k1=TKresult[nres];
1.338     brouard  8534:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8535:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8536:       /*       continue; */
1.268     brouard  8537:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  8538:        strcpy(gplotlabel,"(");      
1.288     brouard  8539:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8540:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8541:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8542:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8543:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8544:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8545:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8546:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8547:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8548:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8549:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8550:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8551:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8552:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8553:        /* } */
                   8554:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8555:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8556:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8557:        }       
1.264     brouard  8558:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8559:        fprintf(ficgp,"\n#\n");
                   8560:        if(invalidvarcomb[k1]){
                   8561:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8562:          continue;
                   8563:        }
                   8564:        
1.241     brouard  8565:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  8566:        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  8567:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8568: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  8569:        k=3; /* Offset */
1.268     brouard  8570:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  8571:          if(i==1)
                   8572:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   8573:          else
                   8574:            fprintf(ficgp,", '' ");
                   8575:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  8576:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.324     brouard  8577:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   8578:          /* 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  8579:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  8580:          /* for (j=2; j<= nlstate ; j ++) */
                   8581:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   8582:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  8583:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  8584:        } /* nlstate */
1.264     brouard  8585:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  8586:       } /* end cpt state*/ 
                   8587:     } /* end covariate */  
1.296     brouard  8588:   } /* End if prevbcast */
1.218     brouard  8589:   
1.223     brouard  8590:   /* 8eme */
1.218     brouard  8591:   if(prevfcast==1){
1.288     brouard  8592:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  8593:     
1.337     brouard  8594:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8595:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8596:       k1=TKresult[nres];
1.338     brouard  8597:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8598:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8599:       /*       continue; */
1.211     brouard  8600:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  8601:        strcpy(gplotlabel,"(");      
1.288     brouard  8602:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8603:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8604:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8605:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8606:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   8607:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   8608:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8609:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8610:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8611:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8612:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8613:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8614:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8615:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8616:        /* } */
                   8617:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8618:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8619:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8620:        }       
1.264     brouard  8621:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8622:        fprintf(ficgp,"\n#\n");
                   8623:        if(invalidvarcomb[k1]){
                   8624:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8625:          continue;
                   8626:        }
                   8627:        
                   8628:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  8629:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  8630:        fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
1.227     brouard  8631:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  8632: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  8633: 
                   8634:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   8635:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8636:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8637:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  8638:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8639:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8640:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8641:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  8642:          if(i==istart){
1.227     brouard  8643:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   8644:          }else{
                   8645:            fprintf(ficgp,",\\\n '' ");
                   8646:          }
                   8647:          if(cptcoveff ==0){ /* No covariate */
                   8648:            ioffset=2; /* Age is in 2 */
                   8649:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8650:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8651:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8652:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8653:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  8654:            if(i==nlstate+1){
1.270     brouard  8655:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  8656:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   8657:              fprintf(ficgp,",\\\n '' ");
                   8658:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  8659:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  8660:                     offyear,                           \
1.268     brouard  8661:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  8662:            }else
1.227     brouard  8663:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   8664:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8665:          }else{ /* more than 2 covariates */
1.270     brouard  8666:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   8667:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8668:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   8669:            iyearc=ioffset-1;
                   8670:            iagec=ioffset;
1.227     brouard  8671:            fprintf(ficgp," u %d:(",ioffset); 
                   8672:            kl=0;
                   8673:            strcpy(gplotcondition,"(");
                   8674:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
1.332     brouard  8675:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8676:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.227     brouard  8677:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8678:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8679:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8680:              /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   8681:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.227     brouard  8682:              kl++;
                   8683:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   8684:              kl++;
                   8685:              if(k <cptcoveff && cptcoveff>1)
                   8686:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   8687:            }
                   8688:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   8689:            /* 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 *\/ */
                   8690:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8691:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8692:            /* ''  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*/
                   8693:            if(i==nlstate+1){
1.270     brouard  8694:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   8695:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  8696:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  8697:              fprintf(ficgp," u %d:(",iagec); 
                   8698:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   8699:                      iyearc, iagec, offyear,                           \
                   8700:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  8701: /*  '' 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  8702:            }else{
                   8703:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   8704:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8705:            }
                   8706:          } /* end if covariate */
                   8707:        } /* nlstate */
1.264     brouard  8708:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  8709:       } /* end cpt state*/
                   8710:     } /* end covariate */
                   8711:   } /* End if prevfcast */
1.227     brouard  8712:   
1.296     brouard  8713:   if(prevbcast==1){
1.268     brouard  8714:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   8715:     
1.337     brouard  8716:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.268     brouard  8717:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8718:      k1=TKresult[nres];
1.338     brouard  8719:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8720:        /* if(m != 1 && TKresult[nres]!= k1) */
                   8721:        /*      continue; */
1.268     brouard  8722:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   8723:        strcpy(gplotlabel,"(");      
                   8724:        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  8725:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8726:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8727:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8728:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   8729:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   8730:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8731:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8732:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8733:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8734:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8735:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8736:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8737:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8738:        /* } */
                   8739:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8740:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8741:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.268     brouard  8742:        }       
                   8743:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   8744:        fprintf(ficgp,"\n#\n");
                   8745:        if(invalidvarcomb[k1]){
                   8746:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8747:          continue;
                   8748:        }
                   8749:        
                   8750:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   8751:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   8752:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   8753:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   8754: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8755: 
                   8756:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   8757:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8758:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8759:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   8760:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8761:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8762:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8763:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8764:          if(i==istart){
                   8765:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   8766:          }else{
                   8767:            fprintf(ficgp,",\\\n '' ");
                   8768:          }
                   8769:          if(cptcoveff ==0){ /* No covariate */
                   8770:            ioffset=2; /* Age is in 2 */
                   8771:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8772:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8773:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8774:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8775:            fprintf(ficgp," u %d:(", ioffset); 
                   8776:            if(i==nlstate+1){
1.270     brouard  8777:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  8778:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   8779:              fprintf(ficgp,",\\\n '' ");
                   8780:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  8781:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  8782:                     offbyear,                          \
                   8783:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   8784:            }else
                   8785:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   8786:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   8787:          }else{ /* more than 2 covariates */
1.270     brouard  8788:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   8789:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8790:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   8791:            iyearc=ioffset-1;
                   8792:            iagec=ioffset;
1.268     brouard  8793:            fprintf(ficgp," u %d:(",ioffset); 
                   8794:            kl=0;
                   8795:            strcpy(gplotcondition,"(");
1.337     brouard  8796:            for (k=1; k<=cptcovs; k++){    /* For each covariate k of the resultline, get corresponding value lv for combination k1 */
1.338     brouard  8797:              if(Dummy[modelresult[nres][k]]==0){  /* To be verified */
1.337     brouard  8798:                /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
                   8799:                /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8800:                /* lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8801:                lv=Tvresult[nres][k];
                   8802:                vlv=TinvDoQresult[nres][Tvresult[nres][k]];
                   8803:                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8804:                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8805:                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8806:                /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   8807:                /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8808:                kl++;
                   8809:                /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
                   8810:                sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%lg " ,kl,Tvresult[nres][k], kl+1,TinvDoQresult[nres][Tvresult[nres][k]]);
                   8811:                kl++;
1.338     brouard  8812:                if(k <cptcovs && cptcovs>1)
1.337     brouard  8813:                  sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   8814:              }
1.268     brouard  8815:            }
                   8816:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   8817:            /* 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 *\/ */
                   8818:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8819:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8820:            /* ''  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*/
                   8821:            if(i==nlstate+1){
1.270     brouard  8822:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   8823:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  8824:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  8825:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  8826:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  8827:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   8828:                      iyearc,iagec,offbyear,                            \
                   8829:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  8830: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   8831:            }else{
                   8832:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   8833:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   8834:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   8835:            }
                   8836:          } /* end if covariate */
                   8837:        } /* nlstate */
                   8838:        fprintf(ficgp,"\nset out; unset label;\n");
                   8839:       } /* end cpt state*/
                   8840:     } /* end covariate */
1.296     brouard  8841:   } /* End if prevbcast */
1.268     brouard  8842:   
1.227     brouard  8843:   
1.238     brouard  8844:   /* 9eme writing MLE parameters */
                   8845:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  8846:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  8847:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  8848:     for(k=1; k <=(nlstate+ndeath); k++){
                   8849:       if (k != i) {
1.227     brouard  8850:        fprintf(ficgp,"#   current state %d\n",k);
                   8851:        for(j=1; j <=ncovmodel; j++){
                   8852:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   8853:          jk++; 
                   8854:        }
                   8855:        fprintf(ficgp,"\n");
1.126     brouard  8856:       }
                   8857:     }
1.223     brouard  8858:   }
1.187     brouard  8859:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  8860:   
1.145     brouard  8861:   /*goto avoid;*/
1.238     brouard  8862:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   8863:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  8864:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   8865:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   8866:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   8867:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   8868:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8869:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   8870:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8871:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   8872:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   8873:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8874:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   8875:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   8876:   fprintf(ficgp,"#\n");
1.223     brouard  8877:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  8878:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.338     brouard  8879:     fprintf(ficgp,"#model=1+age+%s \n",model);
1.238     brouard  8880:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.264     brouard  8881:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
1.337     brouard  8882:     /* for(k1=1; k1 <=m; k1++)  /\* For each combination of covariate *\/ */
1.237     brouard  8883:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8884:      /* k1=nres; */
1.338     brouard  8885:       k1=TKresult[nres];
                   8886:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8887:       fprintf(ficgp,"\n\n# Resultline k1=%d ",k1);
1.264     brouard  8888:       strcpy(gplotlabel,"(");
1.276     brouard  8889:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.337     brouard  8890:       for (k=1; k<=cptcovs; k++){  /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   8891:        /* for each resultline nres, and position k, Tvresult[nres][k] gives the name of the variable and
                   8892:           TinvDoQresult[nres][Tvresult[nres][k]] gives its value double or integer) */
                   8893:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8894:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8895:       }
                   8896:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8897:       /*       continue; */
                   8898:       /* fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1); */
                   8899:       /* strcpy(gplotlabel,"("); */
                   8900:       /* /\*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*\/ */
                   8901:       /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   8902:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   8903:       /*       lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8904:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8905:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8906:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8907:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8908:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8909:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8910:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8911:       /* } */
                   8912:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8913:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8914:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8915:       /* }      */
1.264     brouard  8916:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  8917:       fprintf(ficgp,"\n#\n");
1.264     brouard  8918:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  8919:       fprintf(ficgp,"\nset key outside ");
                   8920:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   8921:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  8922:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   8923:       if (ng==1){
                   8924:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   8925:        fprintf(ficgp,"\nunset log y");
                   8926:       }else if (ng==2){
                   8927:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   8928:        fprintf(ficgp,"\nset log y");
                   8929:       }else if (ng==3){
                   8930:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   8931:        fprintf(ficgp,"\nset log y");
                   8932:       }else
                   8933:        fprintf(ficgp,"\nunset title ");
                   8934:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   8935:       i=1;
                   8936:       for(k2=1; k2<=nlstate; k2++) {
                   8937:        k3=i;
                   8938:        for(k=1; k<=(nlstate+ndeath); k++) {
                   8939:          if (k != k2){
                   8940:            switch( ng) {
                   8941:            case 1:
                   8942:              if(nagesqr==0)
                   8943:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   8944:              else /* nagesqr =1 */
                   8945:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   8946:              break;
                   8947:            case 2: /* ng=2 */
                   8948:              if(nagesqr==0)
                   8949:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   8950:              else /* nagesqr =1 */
                   8951:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   8952:              break;
                   8953:            case 3:
                   8954:              if(nagesqr==0)
                   8955:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   8956:              else /* nagesqr =1 */
                   8957:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   8958:              break;
                   8959:            }
                   8960:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  8961:            ijp=1; /* product no age */
                   8962:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   8963:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  8964:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.329     brouard  8965:              switch(Typevar[j]){
                   8966:              case 1:
                   8967:                if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   8968:                  if(j==Tage[ij]) { /* Product by age  To be looked at!!*//* Bug valgrind */
                   8969:                    if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   8970:                      if(DummyV[j]==0){/* Bug valgrind */
                   8971:                        fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   8972:                      }else{ /* quantitative */
                   8973:                        fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   8974:                        /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8975:                      }
                   8976:                      ij++;
1.268     brouard  8977:                    }
1.237     brouard  8978:                  }
1.329     brouard  8979:                }
                   8980:                break;
                   8981:              case 2:
                   8982:                if(cptcovprod >0){
                   8983:                  if(j==Tprod[ijp]) { /* */ 
                   8984:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   8985:                    if(ijp <=cptcovprod) { /* Product */
                   8986:                      if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   8987:                        if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   8988:                          /* 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)]); */
                   8989:                          fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   8990:                        }else{ /* Vn is dummy and Vm is quanti */
                   8991:                          /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8992:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8993:                        }
                   8994:                      }else{ /* Vn*Vm Vn is quanti */
                   8995:                        if(DummyV[Tvard[ijp][2]]==0){
                   8996:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   8997:                        }else{ /* Both quanti */
                   8998:                          fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8999:                        }
1.268     brouard  9000:                      }
1.329     brouard  9001:                      ijp++;
1.237     brouard  9002:                    }
1.329     brouard  9003:                  } /* end Tprod */
                   9004:                }
                   9005:                break;
                   9006:              case 0:
                   9007:                /* simple covariate */
1.264     brouard  9008:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  9009:                if(Dummy[j]==0){
                   9010:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   9011:                }else{ /* quantitative */
                   9012:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  9013:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  9014:                }
1.329     brouard  9015:               /* end simple */
                   9016:                break;
                   9017:              default:
                   9018:                break;
                   9019:              } /* end switch */
1.237     brouard  9020:            } /* end j */
1.329     brouard  9021:          }else{ /* k=k2 */
                   9022:            if(ng !=1 ){ /* For logit formula of log p11 is more difficult to get */
                   9023:              fprintf(ficgp," (1.");i=i-ncovmodel;
                   9024:            }else
                   9025:              i=i-ncovmodel;
1.223     brouard  9026:          }
1.227     brouard  9027:          
1.223     brouard  9028:          if(ng != 1){
                   9029:            fprintf(ficgp,")/(1");
1.227     brouard  9030:            
1.264     brouard  9031:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  9032:              if(nagesqr==0)
1.264     brouard  9033:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  9034:              else /* nagesqr =1 */
1.264     brouard  9035:                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  9036:               
1.223     brouard  9037:              ij=1;
1.329     brouard  9038:              ijp=1;
                   9039:              /* for(j=3; j <=ncovmodel-nagesqr; j++){ */
                   9040:              for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
                   9041:                switch(Typevar[j]){
                   9042:                case 1:
                   9043:                  if(cptcovage >0){ 
                   9044:                    if(j==Tage[ij]) { /* Bug valgrind */
                   9045:                      if(ij <=cptcovage) { /* Bug valgrind */
                   9046:                        if(DummyV[j]==0){/* Bug valgrind */
                   9047:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]); */
                   9048:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,nbcode[Tvar[j]][codtabm(k1,j)]); */
                   9049:                          fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]);
                   9050:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);; */
                   9051:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9052:                        }else{ /* quantitative */
                   9053:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   9054:                          fprintf(ficgp,"+p%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   9055:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   9056:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9057:                        }
                   9058:                        ij++;
                   9059:                      }
                   9060:                    }
                   9061:                  }
                   9062:                  break;
                   9063:                case 2:
                   9064:                  if(cptcovprod >0){
                   9065:                    if(j==Tprod[ijp]) { /* */ 
                   9066:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9067:                      if(ijp <=cptcovprod) { /* Product */
                   9068:                        if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   9069:                          if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   9070:                            /* 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)]); */
                   9071:                            fprintf(ficgp,"+p%d*%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9072:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   9073:                          }else{ /* Vn is dummy and Vm is quanti */
                   9074:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9075:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9076:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9077:                          }
                   9078:                        }else{ /* Vn*Vm Vn is quanti */
                   9079:                          if(DummyV[Tvard[ijp][2]]==0){
                   9080:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   9081:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   9082:                          }else{ /* Both quanti */
                   9083:                            fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9084:                            /* fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9085:                          } 
                   9086:                        }
                   9087:                        ijp++;
                   9088:                      }
                   9089:                    } /* end Tprod */
                   9090:                  } /* end if */
                   9091:                  break;
                   9092:                case 0: 
                   9093:                  /* simple covariate */
                   9094:                  /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
                   9095:                  if(Dummy[j]==0){
                   9096:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   9097:                    fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]); /*  */
                   9098:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   9099:                  }else{ /* quantitative */
                   9100:                    fprintf(ficgp,"+p%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* */
                   9101:                    /* fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* *\/ */
                   9102:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9103:                  }
                   9104:                  /* end simple */
                   9105:                  /* fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);/\* Valgrind bug nbcode *\/ */
                   9106:                  break;
                   9107:                default:
                   9108:                  break;
                   9109:                } /* end switch */
1.223     brouard  9110:              }
                   9111:              fprintf(ficgp,")");
                   9112:            }
                   9113:            fprintf(ficgp,")");
                   9114:            if(ng ==2)
1.276     brouard  9115:              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  9116:            else /* ng= 3 */
1.276     brouard  9117:              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  9118:           }else{ /* end ng <> 1 */
1.223     brouard  9119:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  9120:              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  9121:          }
                   9122:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   9123:            fprintf(ficgp,",");
                   9124:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   9125:            fprintf(ficgp,",");
                   9126:          i=i+ncovmodel;
                   9127:        } /* end k */
                   9128:       } /* end k2 */
1.276     brouard  9129:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   9130:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.337     brouard  9131:     } /* end resultline */
1.223     brouard  9132:   } /* end ng */
                   9133:   /* avoid: */
                   9134:   fflush(ficgp); 
1.126     brouard  9135: }  /* end gnuplot */
                   9136: 
                   9137: 
                   9138: /*************** Moving average **************/
1.219     brouard  9139: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  9140:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  9141:    
1.222     brouard  9142:    int i, cpt, cptcod;
                   9143:    int modcovmax =1;
                   9144:    int mobilavrange, mob;
                   9145:    int iage=0;
1.288     brouard  9146:    int firstA1=0, firstA2=0;
1.222     brouard  9147: 
1.266     brouard  9148:    double sum=0., sumr=0.;
1.222     brouard  9149:    double age;
1.266     brouard  9150:    double *sumnewp, *sumnewm, *sumnewmr;
                   9151:    double *agemingood, *agemaxgood; 
                   9152:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  9153:   
                   9154:   
1.278     brouard  9155:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   9156:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  9157: 
                   9158:    sumnewp = vector(1,ncovcombmax);
                   9159:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  9160:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  9161:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  9162:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  9163:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  9164:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  9165: 
                   9166:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  9167:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  9168:      sumnewp[cptcod]=0.;
1.266     brouard  9169:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   9170:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  9171:    }
                   9172:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   9173:   
1.266     brouard  9174:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   9175:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  9176:      else mobilavrange=mobilav;
                   9177:      for (age=bage; age<=fage; age++)
                   9178:        for (i=1; i<=nlstate;i++)
                   9179:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   9180:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9181:      /* We keep the original values on the extreme ages bage, fage and for 
                   9182:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   9183:        we use a 5 terms etc. until the borders are no more concerned. 
                   9184:      */ 
                   9185:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   9186:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  9187:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   9188:           sumnewm[cptcod]=0.;
                   9189:           for (i=1; i<=nlstate;i++){
1.222     brouard  9190:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   9191:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   9192:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   9193:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   9194:             }
                   9195:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  9196:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9197:           } /* end i */
                   9198:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   9199:         } /* end cptcod */
1.222     brouard  9200:        }/* end age */
                   9201:      }/* end mob */
1.266     brouard  9202:    }else{
                   9203:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  9204:      return -1;
1.266     brouard  9205:    }
                   9206: 
                   9207:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  9208:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   9209:      if(invalidvarcomb[cptcod]){
                   9210:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   9211:        continue;
                   9212:      }
1.219     brouard  9213: 
1.266     brouard  9214:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   9215:        sumnewm[cptcod]=0.;
                   9216:        sumnewmr[cptcod]=0.;
                   9217:        for (i=1; i<=nlstate;i++){
                   9218:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9219:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9220:        }
                   9221:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9222:         agemingoodr[cptcod]=age;
                   9223:        }
                   9224:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9225:           agemingood[cptcod]=age;
                   9226:        }
                   9227:      } /* age */
                   9228:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  9229:        sumnewm[cptcod]=0.;
1.266     brouard  9230:        sumnewmr[cptcod]=0.;
1.222     brouard  9231:        for (i=1; i<=nlstate;i++){
                   9232:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9233:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9234:        }
                   9235:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9236:         agemaxgoodr[cptcod]=age;
1.222     brouard  9237:        }
                   9238:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  9239:         agemaxgood[cptcod]=age;
                   9240:        }
                   9241:      } /* age */
                   9242:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   9243:      /* but they will change */
1.288     brouard  9244:      firstA1=0;firstA2=0;
1.266     brouard  9245:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   9246:        sumnewm[cptcod]=0.;
                   9247:        sumnewmr[cptcod]=0.;
                   9248:        for (i=1; i<=nlstate;i++){
                   9249:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9250:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9251:        }
                   9252:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9253:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9254:           agemaxgoodr[cptcod]=age;  /* age min */
                   9255:           for (i=1; i<=nlstate;i++)
                   9256:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9257:         }else{ /* bad we change the value with the values of good ages */
                   9258:           for (i=1; i<=nlstate;i++){
                   9259:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   9260:           } /* i */
                   9261:         } /* end bad */
                   9262:        }else{
                   9263:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9264:           agemaxgood[cptcod]=age;
                   9265:         }else{ /* bad we change the value with the values of good ages */
                   9266:           for (i=1; i<=nlstate;i++){
                   9267:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   9268:           } /* i */
                   9269:         } /* end bad */
                   9270:        }/* end else */
                   9271:        sum=0.;sumr=0.;
                   9272:        for (i=1; i<=nlstate;i++){
                   9273:         sum+=mobaverage[(int)age][i][cptcod];
                   9274:         sumr+=probs[(int)age][i][cptcod];
                   9275:        }
                   9276:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  9277:         if(!firstA1){
                   9278:           firstA1=1;
                   9279:           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);
                   9280:         }
                   9281:         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  9282:        } /* end bad */
                   9283:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9284:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  9285:         if(!firstA2){
                   9286:           firstA2=1;
                   9287:           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);
                   9288:         }
                   9289:         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  9290:        } /* end bad */
                   9291:      }/* age */
1.266     brouard  9292: 
                   9293:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  9294:        sumnewm[cptcod]=0.;
1.266     brouard  9295:        sumnewmr[cptcod]=0.;
1.222     brouard  9296:        for (i=1; i<=nlstate;i++){
                   9297:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9298:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9299:        } 
                   9300:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9301:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   9302:           agemingoodr[cptcod]=age;
                   9303:           for (i=1; i<=nlstate;i++)
                   9304:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9305:         }else{ /* bad we change the value with the values of good ages */
                   9306:           for (i=1; i<=nlstate;i++){
                   9307:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   9308:           } /* i */
                   9309:         } /* end bad */
                   9310:        }else{
                   9311:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9312:           agemingood[cptcod]=age;
                   9313:         }else{ /* bad */
                   9314:           for (i=1; i<=nlstate;i++){
                   9315:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   9316:           } /* i */
                   9317:         } /* end bad */
                   9318:        }/* end else */
                   9319:        sum=0.;sumr=0.;
                   9320:        for (i=1; i<=nlstate;i++){
                   9321:         sum+=mobaverage[(int)age][i][cptcod];
                   9322:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  9323:        }
1.266     brouard  9324:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  9325:         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  9326:        } /* end bad */
                   9327:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9328:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  9329:         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  9330:        } /* end bad */
                   9331:      }/* age */
1.266     brouard  9332: 
1.222     brouard  9333:                
                   9334:      for (age=bage; age<=fage; age++){
1.235     brouard  9335:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  9336:        sumnewp[cptcod]=0.;
                   9337:        sumnewm[cptcod]=0.;
                   9338:        for (i=1; i<=nlstate;i++){
                   9339:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   9340:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9341:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   9342:        }
                   9343:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   9344:      }
                   9345:      /* printf("\n"); */
                   9346:      /* } */
1.266     brouard  9347: 
1.222     brouard  9348:      /* brutal averaging */
1.266     brouard  9349:      /* for (i=1; i<=nlstate;i++){ */
                   9350:      /*   for (age=1; age<=bage; age++){ */
                   9351:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   9352:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9353:      /*   }     */
                   9354:      /*   for (age=fage; age<=AGESUP; age++){ */
                   9355:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   9356:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9357:      /*   } */
                   9358:      /* } /\* end i status *\/ */
                   9359:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   9360:      /*   for (age=1; age<=AGESUP; age++){ */
                   9361:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   9362:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   9363:      /*   } */
                   9364:      /* } */
1.222     brouard  9365:    }/* end cptcod */
1.266     brouard  9366:    free_vector(agemaxgoodr,1, ncovcombmax);
                   9367:    free_vector(agemaxgood,1, ncovcombmax);
                   9368:    free_vector(agemingood,1, ncovcombmax);
                   9369:    free_vector(agemingoodr,1, ncovcombmax);
                   9370:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  9371:    free_vector(sumnewm,1, ncovcombmax);
                   9372:    free_vector(sumnewp,1, ncovcombmax);
                   9373:    return 0;
                   9374:  }/* End movingaverage */
1.218     brouard  9375:  
1.126     brouard  9376: 
1.296     brouard  9377:  
1.126     brouard  9378: /************** Forecasting ******************/
1.296     brouard  9379: /* 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)*/
                   9380: 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){
                   9381:   /* dateintemean, mean date of interviews
                   9382:      dateprojd, year, month, day of starting projection 
                   9383:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  9384:      agemin, agemax range of age
                   9385:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   9386:   */
1.296     brouard  9387:   /* double anprojd, mprojd, jprojd; */
                   9388:   /* double anprojf, mprojf, jprojf; */
1.267     brouard  9389:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  9390:   double agec; /* generic age */
1.296     brouard  9391:   double agelim, ppij, yp,yp1,yp2;
1.126     brouard  9392:   double *popeffectif,*popcount;
                   9393:   double ***p3mat;
1.218     brouard  9394:   /* double ***mobaverage; */
1.126     brouard  9395:   char fileresf[FILENAMELENGTH];
                   9396: 
                   9397:   agelim=AGESUP;
1.211     brouard  9398:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9399:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9400:      We still use firstpass and lastpass as another selection.
                   9401:   */
1.214     brouard  9402:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9403:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  9404:  
1.201     brouard  9405:   strcpy(fileresf,"F_"); 
                   9406:   strcat(fileresf,fileresu);
1.126     brouard  9407:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   9408:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   9409:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   9410:   }
1.235     brouard  9411:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   9412:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  9413: 
1.225     brouard  9414:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  9415: 
                   9416: 
                   9417:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9418:   if (stepm<=12) stepsize=1;
                   9419:   if(estepm < stepm){
                   9420:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9421:   }
1.270     brouard  9422:   else{
                   9423:     hstepm=estepm;   
                   9424:   }
                   9425:   if(estepm > stepm){ /* Yes every two year */
                   9426:     stepsize=2;
                   9427:   }
1.296     brouard  9428:   hstepm=hstepm/stepm;
1.126     brouard  9429: 
1.296     brouard  9430:   
                   9431:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9432:   /*                              fractional in yp1 *\/ */
                   9433:   /* aintmean=yp; */
                   9434:   /* yp2=modf((yp1*12),&yp); */
                   9435:   /* mintmean=yp; */
                   9436:   /* yp1=modf((yp2*30.5),&yp); */
                   9437:   /* jintmean=yp; */
                   9438:   /* if(jintmean==0) jintmean=1; */
                   9439:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  9440: 
1.296     brouard  9441: 
                   9442:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   9443:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   9444:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.227     brouard  9445:   i1=pow(2,cptcoveff);
1.126     brouard  9446:   if (cptcovn < 1){i1=1;}
                   9447:   
1.296     brouard  9448:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  9449:   
                   9450:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  9451:   
1.126     brouard  9452: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  9453:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.332     brouard  9454:     for(k=1; k<=i1;k++){ /* We want to find the combination k corresponding to the values of the dummies given in this resut line (to be cleaned one day) */
1.253     brouard  9455:     if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  9456:       continue;
1.227     brouard  9457:     if(invalidvarcomb[k]){
                   9458:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   9459:       continue;
                   9460:     }
                   9461:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   9462:     for(j=1;j<=cptcoveff;j++) {
1.332     brouard  9463:       /* fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); */
                   9464:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.227     brouard  9465:     }
1.235     brouard  9466:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  9467:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.235     brouard  9468:     }
1.227     brouard  9469:     fprintf(ficresf," yearproj age");
                   9470:     for(j=1; j<=nlstate+ndeath;j++){ 
                   9471:       for(i=1; i<=nlstate;i++)               
                   9472:        fprintf(ficresf," p%d%d",i,j);
                   9473:       fprintf(ficresf," wp.%d",j);
                   9474:     }
1.296     brouard  9475:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  9476:       fprintf(ficresf,"\n");
1.296     brouard  9477:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  9478:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   9479:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  9480:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   9481:        nhstepm = nhstepm/hstepm; 
                   9482:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9483:        oldm=oldms;savm=savms;
1.268     brouard  9484:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  9485:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  9486:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  9487:        for (h=0; h<=nhstepm; h++){
                   9488:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  9489:            break;
                   9490:          }
                   9491:        }
                   9492:        fprintf(ficresf,"\n");
                   9493:        for(j=1;j<=cptcoveff;j++) 
1.332     brouard  9494:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Tvaraff not correct *\/ */
                   9495:          fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /* TnsdVar[Tvaraff]  correct */
1.296     brouard  9496:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  9497:        
                   9498:        for(j=1; j<=nlstate+ndeath;j++) {
                   9499:          ppij=0.;
                   9500:          for(i=1; i<=nlstate;i++) {
1.278     brouard  9501:            if (mobilav>=1)
                   9502:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   9503:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   9504:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   9505:            }
1.268     brouard  9506:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   9507:          } /* end i */
                   9508:          fprintf(ficresf," %.3f", ppij);
                   9509:        }/* end j */
1.227     brouard  9510:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9511:       } /* end agec */
1.266     brouard  9512:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   9513:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  9514:     } /* end yearp */
                   9515:   } /* end  k */
1.219     brouard  9516:        
1.126     brouard  9517:   fclose(ficresf);
1.215     brouard  9518:   printf("End of Computing forecasting \n");
                   9519:   fprintf(ficlog,"End of Computing forecasting\n");
                   9520: 
1.126     brouard  9521: }
                   9522: 
1.269     brouard  9523: /************** Back Forecasting ******************/
1.296     brouard  9524:  /* 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){ */
                   9525:  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){
                   9526:   /* back1, year, month, day of starting backprojection
1.267     brouard  9527:      agemin, agemax range of age
                   9528:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  9529:      anback2 year of end of backprojection (same day and month as back1).
                   9530:      prevacurrent and prev are prevalences.
1.267     brouard  9531:   */
                   9532:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   9533:   double agec; /* generic age */
1.302     brouard  9534:   double agelim, ppij, ppi, yp,yp1,yp2; /* ,jintmean,mintmean,aintmean;*/
1.267     brouard  9535:   double *popeffectif,*popcount;
                   9536:   double ***p3mat;
                   9537:   /* double ***mobaverage; */
                   9538:   char fileresfb[FILENAMELENGTH];
                   9539:  
1.268     brouard  9540:   agelim=AGEINF;
1.267     brouard  9541:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9542:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9543:      We still use firstpass and lastpass as another selection.
                   9544:   */
                   9545:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9546:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   9547: 
                   9548:   /*Do we need to compute prevalence again?*/
                   9549: 
                   9550:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   9551:   
                   9552:   strcpy(fileresfb,"FB_");
                   9553:   strcat(fileresfb,fileresu);
                   9554:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   9555:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   9556:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   9557:   }
                   9558:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   9559:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   9560:   
                   9561:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   9562:   
                   9563:    
                   9564:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9565:   if (stepm<=12) stepsize=1;
                   9566:   if(estepm < stepm){
                   9567:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9568:   }
1.270     brouard  9569:   else{
                   9570:     hstepm=estepm;   
                   9571:   }
                   9572:   if(estepm >= stepm){ /* Yes every two year */
                   9573:     stepsize=2;
                   9574:   }
1.267     brouard  9575:   
                   9576:   hstepm=hstepm/stepm;
1.296     brouard  9577:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9578:   /*                              fractional in yp1 *\/ */
                   9579:   /* aintmean=yp; */
                   9580:   /* yp2=modf((yp1*12),&yp); */
                   9581:   /* mintmean=yp; */
                   9582:   /* yp1=modf((yp2*30.5),&yp); */
                   9583:   /* jintmean=yp; */
                   9584:   /* if(jintmean==0) jintmean=1; */
                   9585:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  9586:   
                   9587:   i1=pow(2,cptcoveff);
                   9588:   if (cptcovn < 1){i1=1;}
                   9589:   
1.296     brouard  9590:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   9591:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  9592:   
                   9593:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   9594:   
                   9595:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9596:   for(k=1; k<=i1;k++){
                   9597:     if(i1 != 1 && TKresult[nres]!= k)
                   9598:       continue;
                   9599:     if(invalidvarcomb[k]){
                   9600:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   9601:       continue;
                   9602:     }
1.268     brouard  9603:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.267     brouard  9604:     for(j=1;j<=cptcoveff;j++) {
1.332     brouard  9605:       fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.267     brouard  9606:     }
                   9607:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   9608:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9609:     }
                   9610:     fprintf(ficresfb," yearbproj age");
                   9611:     for(j=1; j<=nlstate+ndeath;j++){
                   9612:       for(i=1; i<=nlstate;i++)
1.268     brouard  9613:        fprintf(ficresfb," b%d%d",i,j);
                   9614:       fprintf(ficresfb," b.%d",j);
1.267     brouard  9615:     }
1.296     brouard  9616:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  9617:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   9618:       fprintf(ficresfb,"\n");
1.296     brouard  9619:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  9620:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  9621:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   9622:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  9623:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  9624:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  9625:        nhstepm = nhstepm/hstepm;
                   9626:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9627:        oldm=oldms;savm=savms;
1.268     brouard  9628:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  9629:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  9630:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  9631:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   9632:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   9633:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  9634:        for (h=0; h<=nhstepm; h++){
1.268     brouard  9635:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   9636:            break;
                   9637:          }
                   9638:        }
                   9639:        fprintf(ficresfb,"\n");
                   9640:        for(j=1;j<=cptcoveff;j++)
1.332     brouard  9641:          fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.296     brouard  9642:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  9643:        for(i=1; i<=nlstate+ndeath;i++) {
                   9644:          ppij=0.;ppi=0.;
                   9645:          for(j=1; j<=nlstate;j++) {
                   9646:            /* if (mobilav==1) */
1.269     brouard  9647:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   9648:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   9649:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   9650:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  9651:              /* else { */
                   9652:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   9653:              /* } */
1.268     brouard  9654:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   9655:          } /* end j */
                   9656:          if(ppi <0.99){
                   9657:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   9658:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   9659:          }
                   9660:          fprintf(ficresfb," %.3f", ppij);
                   9661:        }/* end j */
1.267     brouard  9662:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9663:       } /* end agec */
                   9664:     } /* end yearp */
                   9665:   } /* end k */
1.217     brouard  9666:   
1.267     brouard  9667:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  9668:   
1.267     brouard  9669:   fclose(ficresfb);
                   9670:   printf("End of Computing Back forecasting \n");
                   9671:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  9672:        
1.267     brouard  9673: }
1.217     brouard  9674: 
1.269     brouard  9675: /* Variance of prevalence limit: varprlim */
                   9676:  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  9677:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  9678:  
                   9679:    char fileresvpl[FILENAMELENGTH];  
                   9680:    FILE *ficresvpl;
                   9681:    double **oldm, **savm;
                   9682:    double **varpl; /* Variances of prevalence limits by age */   
                   9683:    int i1, k, nres, j ;
                   9684:    
                   9685:     strcpy(fileresvpl,"VPL_");
                   9686:     strcat(fileresvpl,fileresu);
                   9687:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  9688:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  9689:       exit(0);
                   9690:     }
1.288     brouard  9691:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   9692:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  9693:     
                   9694:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   9695:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   9696:     
                   9697:     i1=pow(2,cptcoveff);
                   9698:     if (cptcovn < 1){i1=1;}
                   9699: 
1.337     brouard  9700:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9701:        k=TKresult[nres];
1.338     brouard  9702:        if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  9703:      /* for(k=1; k<=i1;k++){ /\* We find the combination equivalent to result line values of dummies *\/ */
1.269     brouard  9704:       if(i1 != 1 && TKresult[nres]!= k)
                   9705:        continue;
                   9706:       fprintf(ficresvpl,"\n#****** ");
                   9707:       printf("\n#****** ");
                   9708:       fprintf(ficlog,"\n#****** ");
1.337     brouard  9709:       for(j=1;j<=cptcovs;j++) {
                   9710:        fprintf(ficresvpl,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   9711:        fprintf(ficlog,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   9712:        printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   9713:        /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   9714:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.269     brouard  9715:       }
1.337     brouard  9716:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   9717:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9718:       /*       fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9719:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9720:       /* }      */
1.269     brouard  9721:       fprintf(ficresvpl,"******\n");
                   9722:       printf("******\n");
                   9723:       fprintf(ficlog,"******\n");
                   9724:       
                   9725:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9726:       oldm=oldms;savm=savms;
                   9727:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   9728:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   9729:       /*}*/
                   9730:     }
                   9731:     
                   9732:     fclose(ficresvpl);
1.288     brouard  9733:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   9734:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  9735: 
                   9736:  }
                   9737: /* Variance of back prevalence: varbprlim */
                   9738:  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){
                   9739:       /*------- Variance of back (stable) prevalence------*/
                   9740: 
                   9741:    char fileresvbl[FILENAMELENGTH];  
                   9742:    FILE  *ficresvbl;
                   9743: 
                   9744:    double **oldm, **savm;
                   9745:    double **varbpl; /* Variances of back prevalence limits by age */   
                   9746:    int i1, k, nres, j ;
                   9747: 
                   9748:    strcpy(fileresvbl,"VBL_");
                   9749:    strcat(fileresvbl,fileresu);
                   9750:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   9751:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   9752:      exit(0);
                   9753:    }
                   9754:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   9755:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   9756:    
                   9757:    
                   9758:    i1=pow(2,cptcoveff);
                   9759:    if (cptcovn < 1){i1=1;}
                   9760:    
1.337     brouard  9761:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9762:      k=TKresult[nres];
1.338     brouard  9763:      if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  9764:     /* for(k=1; k<=i1;k++){ */
                   9765:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   9766:     /*          continue; */
1.269     brouard  9767:        fprintf(ficresvbl,"\n#****** ");
                   9768:        printf("\n#****** ");
                   9769:        fprintf(ficlog,"\n#****** ");
1.337     brouard  9770:        for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */
1.338     brouard  9771:         printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   9772:         fprintf(ficresvbl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   9773:         fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
1.337     brouard  9774:        /* for(j=1;j<=cptcoveff;j++) { */
                   9775:        /*       fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   9776:        /*       fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   9777:        /*       printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   9778:        /* } */
                   9779:        /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   9780:        /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9781:        /*       fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9782:        /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
1.269     brouard  9783:        }
                   9784:        fprintf(ficresvbl,"******\n");
                   9785:        printf("******\n");
                   9786:        fprintf(ficlog,"******\n");
                   9787:        
                   9788:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9789:        oldm=oldms;savm=savms;
                   9790:        
                   9791:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   9792:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   9793:        /*}*/
                   9794:      }
                   9795:    
                   9796:    fclose(ficresvbl);
                   9797:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   9798:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   9799: 
                   9800:  } /* End of varbprlim */
                   9801: 
1.126     brouard  9802: /************** Forecasting *****not tested NB*************/
1.227     brouard  9803: /* 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  9804:   
1.227     brouard  9805: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   9806: /*   int *popage; */
                   9807: /*   double calagedatem, agelim, kk1, kk2; */
                   9808: /*   double *popeffectif,*popcount; */
                   9809: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   9810: /*   /\* double ***mobaverage; *\/ */
                   9811: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  9812: 
1.227     brouard  9813: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9814: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9815: /*   agelim=AGESUP; */
                   9816: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  9817:   
1.227     brouard  9818: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  9819:   
                   9820:   
1.227     brouard  9821: /*   strcpy(filerespop,"POP_");  */
                   9822: /*   strcat(filerespop,fileresu); */
                   9823: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   9824: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   9825: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   9826: /*   } */
                   9827: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   9828: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  9829: 
1.227     brouard  9830: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  9831: 
1.227     brouard  9832: /*   /\* if (mobilav!=0) { *\/ */
                   9833: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   9834: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   9835: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   9836: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   9837: /*   /\*   } *\/ */
                   9838: /*   /\* } *\/ */
1.126     brouard  9839: 
1.227     brouard  9840: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   9841: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  9842:   
1.227     brouard  9843: /*   agelim=AGESUP; */
1.126     brouard  9844:   
1.227     brouard  9845: /*   hstepm=1; */
                   9846: /*   hstepm=hstepm/stepm;  */
1.218     brouard  9847:        
1.227     brouard  9848: /*   if (popforecast==1) { */
                   9849: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   9850: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   9851: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   9852: /*     }  */
                   9853: /*     popage=ivector(0,AGESUP); */
                   9854: /*     popeffectif=vector(0,AGESUP); */
                   9855: /*     popcount=vector(0,AGESUP); */
1.126     brouard  9856:     
1.227     brouard  9857: /*     i=1;    */
                   9858: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  9859:     
1.227     brouard  9860: /*     imx=i; */
                   9861: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   9862: /*   } */
1.218     brouard  9863:   
1.227     brouard  9864: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   9865: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   9866: /*       k=k+1; */
                   9867: /*       fprintf(ficrespop,"\n#******"); */
                   9868: /*       for(j=1;j<=cptcoveff;j++) { */
                   9869: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   9870: /*       } */
                   9871: /*       fprintf(ficrespop,"******\n"); */
                   9872: /*       fprintf(ficrespop,"# Age"); */
                   9873: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   9874: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  9875:       
1.227     brouard  9876: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   9877: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  9878:        
1.227     brouard  9879: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   9880: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   9881: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  9882:          
1.227     brouard  9883: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9884: /*       oldm=oldms;savm=savms; */
                   9885: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  9886:          
1.227     brouard  9887: /*       for (h=0; h<=nhstepm; h++){ */
                   9888: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   9889: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   9890: /*         }  */
                   9891: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   9892: /*           kk1=0.;kk2=0; */
                   9893: /*           for(i=1; i<=nlstate;i++) {               */
                   9894: /*             if (mobilav==1)  */
                   9895: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   9896: /*             else { */
                   9897: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   9898: /*             } */
                   9899: /*           } */
                   9900: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   9901: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   9902: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   9903: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   9904: /*           } */
                   9905: /*         } */
                   9906: /*         for(i=1; i<=nlstate;i++){ */
                   9907: /*           kk1=0.; */
                   9908: /*           for(j=1; j<=nlstate;j++){ */
                   9909: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   9910: /*           } */
                   9911: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   9912: /*         } */
1.218     brouard  9913:            
1.227     brouard  9914: /*         if (h==(int)(calagedatem+12*cpt)) */
                   9915: /*           for(j=1; j<=nlstate;j++)  */
                   9916: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   9917: /*       } */
                   9918: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9919: /*     } */
                   9920: /*       } */
1.218     brouard  9921:       
1.227     brouard  9922: /*       /\******\/ */
1.218     brouard  9923:       
1.227     brouard  9924: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   9925: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   9926: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   9927: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   9928: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  9929:          
1.227     brouard  9930: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9931: /*       oldm=oldms;savm=savms; */
                   9932: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   9933: /*       for (h=0; h<=nhstepm; h++){ */
                   9934: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   9935: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   9936: /*         }  */
                   9937: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   9938: /*           kk1=0.;kk2=0; */
                   9939: /*           for(i=1; i<=nlstate;i++) {               */
                   9940: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   9941: /*           } */
                   9942: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   9943: /*         } */
                   9944: /*       } */
                   9945: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9946: /*     } */
                   9947: /*       } */
                   9948: /*     }  */
                   9949: /*   } */
1.218     brouard  9950:   
1.227     brouard  9951: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  9952:   
1.227     brouard  9953: /*   if (popforecast==1) { */
                   9954: /*     free_ivector(popage,0,AGESUP); */
                   9955: /*     free_vector(popeffectif,0,AGESUP); */
                   9956: /*     free_vector(popcount,0,AGESUP); */
                   9957: /*   } */
                   9958: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9959: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9960: /*   fclose(ficrespop); */
                   9961: /* } /\* End of popforecast *\/ */
1.218     brouard  9962:  
1.126     brouard  9963: int fileappend(FILE *fichier, char *optionfich)
                   9964: {
                   9965:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   9966:     printf("Problem with file: %s\n", optionfich);
                   9967:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   9968:     return (0);
                   9969:   }
                   9970:   fflush(fichier);
                   9971:   return (1);
                   9972: }
                   9973: 
                   9974: 
                   9975: /**************** function prwizard **********************/
                   9976: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   9977: {
                   9978: 
                   9979:   /* Wizard to print covariance matrix template */
                   9980: 
1.164     brouard  9981:   char ca[32], cb[32];
                   9982:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  9983:   int numlinepar;
                   9984: 
                   9985:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9986:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9987:   for(i=1; i <=nlstate; i++){
                   9988:     jj=0;
                   9989:     for(j=1; j <=nlstate+ndeath; j++){
                   9990:       if(j==i) continue;
                   9991:       jj++;
                   9992:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   9993:       printf("%1d%1d",i,j);
                   9994:       fprintf(ficparo,"%1d%1d",i,j);
                   9995:       for(k=1; k<=ncovmodel;k++){
                   9996:        /*        printf(" %lf",param[i][j][k]); */
                   9997:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   9998:        printf(" 0.");
                   9999:        fprintf(ficparo," 0.");
                   10000:       }
                   10001:       printf("\n");
                   10002:       fprintf(ficparo,"\n");
                   10003:     }
                   10004:   }
                   10005:   printf("# Scales (for hessian or gradient estimation)\n");
                   10006:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   10007:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   10008:   for(i=1; i <=nlstate; i++){
                   10009:     jj=0;
                   10010:     for(j=1; j <=nlstate+ndeath; j++){
                   10011:       if(j==i) continue;
                   10012:       jj++;
                   10013:       fprintf(ficparo,"%1d%1d",i,j);
                   10014:       printf("%1d%1d",i,j);
                   10015:       fflush(stdout);
                   10016:       for(k=1; k<=ncovmodel;k++){
                   10017:        /*      printf(" %le",delti3[i][j][k]); */
                   10018:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   10019:        printf(" 0.");
                   10020:        fprintf(ficparo," 0.");
                   10021:       }
                   10022:       numlinepar++;
                   10023:       printf("\n");
                   10024:       fprintf(ficparo,"\n");
                   10025:     }
                   10026:   }
                   10027:   printf("# Covariance matrix\n");
                   10028: /* # 121 Var(a12)\n\ */
                   10029: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10030: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   10031: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   10032: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   10033: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   10034: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   10035: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   10036:   fflush(stdout);
                   10037:   fprintf(ficparo,"# Covariance matrix\n");
                   10038:   /* # 121 Var(a12)\n\ */
                   10039:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10040:   /* #   ...\n\ */
                   10041:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   10042:   
                   10043:   for(itimes=1;itimes<=2;itimes++){
                   10044:     jj=0;
                   10045:     for(i=1; i <=nlstate; i++){
                   10046:       for(j=1; j <=nlstate+ndeath; j++){
                   10047:        if(j==i) continue;
                   10048:        for(k=1; k<=ncovmodel;k++){
                   10049:          jj++;
                   10050:          ca[0]= k+'a'-1;ca[1]='\0';
                   10051:          if(itimes==1){
                   10052:            printf("#%1d%1d%d",i,j,k);
                   10053:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   10054:          }else{
                   10055:            printf("%1d%1d%d",i,j,k);
                   10056:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   10057:            /*  printf(" %.5le",matcov[i][j]); */
                   10058:          }
                   10059:          ll=0;
                   10060:          for(li=1;li <=nlstate; li++){
                   10061:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   10062:              if(lj==li) continue;
                   10063:              for(lk=1;lk<=ncovmodel;lk++){
                   10064:                ll++;
                   10065:                if(ll<=jj){
                   10066:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   10067:                  if(ll<jj){
                   10068:                    if(itimes==1){
                   10069:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10070:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10071:                    }else{
                   10072:                      printf(" 0.");
                   10073:                      fprintf(ficparo," 0.");
                   10074:                    }
                   10075:                  }else{
                   10076:                    if(itimes==1){
                   10077:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   10078:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   10079:                    }else{
                   10080:                      printf(" 0.");
                   10081:                      fprintf(ficparo," 0.");
                   10082:                    }
                   10083:                  }
                   10084:                }
                   10085:              } /* end lk */
                   10086:            } /* end lj */
                   10087:          } /* end li */
                   10088:          printf("\n");
                   10089:          fprintf(ficparo,"\n");
                   10090:          numlinepar++;
                   10091:        } /* end k*/
                   10092:       } /*end j */
                   10093:     } /* end i */
                   10094:   } /* end itimes */
                   10095: 
                   10096: } /* end of prwizard */
                   10097: /******************* Gompertz Likelihood ******************************/
                   10098: double gompertz(double x[])
                   10099: { 
1.302     brouard  10100:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
1.126     brouard  10101:   int i,n=0; /* n is the size of the sample */
                   10102: 
1.220     brouard  10103:   for (i=1;i<=imx ; i++) {
1.126     brouard  10104:     sump=sump+weight[i];
                   10105:     /*    sump=sump+1;*/
                   10106:     num=num+1;
                   10107:   }
1.302     brouard  10108:   L=0.0;
                   10109:   /* agegomp=AGEGOMP; */
1.126     brouard  10110:   /* for (i=0; i<=imx; i++) 
                   10111:      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]);*/
                   10112: 
1.302     brouard  10113:   for (i=1;i<=imx ; i++) {
                   10114:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   10115:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   10116:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   10117:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   10118:      * +
                   10119:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   10120:      */
                   10121:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   10122:        if (cens[i] == 1){
                   10123:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   10124:        } else if (cens[i] == 0){
1.126     brouard  10125:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
1.302     brouard  10126:          +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   10127:       } else
                   10128:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
1.126     brouard  10129:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
1.302     brouard  10130:        L=L+A*weight[i];
1.126     brouard  10131:        /*      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  10132:      }
                   10133:   }
1.126     brouard  10134: 
1.302     brouard  10135:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
1.126     brouard  10136:  
                   10137:   return -2*L*num/sump;
                   10138: }
                   10139: 
1.136     brouard  10140: #ifdef GSL
                   10141: /******************* Gompertz_f Likelihood ******************************/
                   10142: double gompertz_f(const gsl_vector *v, void *params)
                   10143: { 
1.302     brouard  10144:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
1.136     brouard  10145:   double *x= (double *) v->data;
                   10146:   int i,n=0; /* n is the size of the sample */
                   10147: 
                   10148:   for (i=0;i<=imx-1 ; i++) {
                   10149:     sump=sump+weight[i];
                   10150:     /*    sump=sump+1;*/
                   10151:     num=num+1;
                   10152:   }
                   10153:  
                   10154:  
                   10155:   /* for (i=0; i<=imx; i++) 
                   10156:      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]);*/
                   10157:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   10158:   for (i=1;i<=imx ; i++)
                   10159:     {
                   10160:       if (cens[i] == 1 && wav[i]>1)
                   10161:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   10162:       
                   10163:       if (cens[i] == 0 && wav[i]>1)
                   10164:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   10165:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   10166:       
                   10167:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   10168:       if (wav[i] > 1 ) { /* ??? */
                   10169:        LL=LL+A*weight[i];
                   10170:        /*      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]);*/
                   10171:       }
                   10172:     }
                   10173: 
                   10174:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   10175:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   10176:  
                   10177:   return -2*LL*num/sump;
                   10178: }
                   10179: #endif
                   10180: 
1.126     brouard  10181: /******************* Printing html file ***********/
1.201     brouard  10182: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  10183:                  int lastpass, int stepm, int weightopt, char model[],\
                   10184:                  int imx,  double p[],double **matcov,double agemortsup){
                   10185:   int i,k;
                   10186: 
                   10187:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   10188:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   10189:   for (i=1;i<=2;i++) 
                   10190:     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  10191:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  10192:   fprintf(fichtm,"</ul>");
                   10193: 
                   10194: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   10195: 
                   10196:  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>");
                   10197: 
                   10198:  for (k=agegomp;k<(agemortsup-2);k++) 
                   10199:    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]);
                   10200: 
                   10201:  
                   10202:   fflush(fichtm);
                   10203: }
                   10204: 
                   10205: /******************* Gnuplot file **************/
1.201     brouard  10206: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  10207: 
                   10208:   char dirfileres[132],optfileres[132];
1.164     brouard  10209: 
1.126     brouard  10210:   int ng;
                   10211: 
                   10212: 
                   10213:   /*#ifdef windows */
                   10214:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   10215:     /*#endif */
                   10216: 
                   10217: 
                   10218:   strcpy(dirfileres,optionfilefiname);
                   10219:   strcpy(optfileres,"vpl");
1.199     brouard  10220:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  10221:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  10222:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  10223:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  10224:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   10225: 
                   10226: } 
                   10227: 
1.136     brouard  10228: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   10229: {
1.126     brouard  10230: 
1.136     brouard  10231:   /*-------- data file ----------*/
                   10232:   FILE *fic;
                   10233:   char dummy[]="                         ";
1.240     brouard  10234:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  10235:   int lstra;
1.136     brouard  10236:   int linei, month, year,iout;
1.302     brouard  10237:   int noffset=0; /* This is the offset if BOM data file */
1.136     brouard  10238:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  10239:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  10240:   char *stratrunc;
1.223     brouard  10241: 
1.240     brouard  10242:   DummyV=ivector(1,NCOVMAX); /* 1 to 3 */
                   10243:   FixedV=ivector(1,NCOVMAX); /* 1 to 3 */
1.328     brouard  10244:   for(v=1;v<NCOVMAX;v++){
                   10245:     DummyV[v]=0;
                   10246:     FixedV[v]=0;
                   10247:   }
1.126     brouard  10248: 
1.240     brouard  10249:   for(v=1; v <=ncovcol;v++){
                   10250:     DummyV[v]=0;
                   10251:     FixedV[v]=0;
                   10252:   }
                   10253:   for(v=ncovcol+1; v <=ncovcol+nqv;v++){
                   10254:     DummyV[v]=1;
                   10255:     FixedV[v]=0;
                   10256:   }
                   10257:   for(v=ncovcol+nqv+1; v <=ncovcol+nqv+ntv;v++){
                   10258:     DummyV[v]=0;
                   10259:     FixedV[v]=1;
                   10260:   }
                   10261:   for(v=ncovcol+nqv+ntv+1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   10262:     DummyV[v]=1;
                   10263:     FixedV[v]=1;
                   10264:   }
                   10265:   for(v=1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   10266:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   10267:     fprintf(ficlog,"Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   10268:   }
1.339     brouard  10269:   
                   10270:   ncovcolt=ncovcol+nqv+ntv+nqtv; /* total of covariates in the data, not in the model equation */
                   10271:   
1.136     brouard  10272:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  10273:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10274:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  10275:   }
1.126     brouard  10276: 
1.302     brouard  10277:     /* Is it a BOM UTF-8 Windows file? */
                   10278:   /* First data line */
                   10279:   linei=0;
                   10280:   while(fgets(line, MAXLINE, fic)) {
                   10281:     noffset=0;
                   10282:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   10283:     {
                   10284:       noffset=noffset+3;
                   10285:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   10286:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   10287:       fflush(ficlog); return 1;
                   10288:     }
                   10289:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   10290:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   10291:     {
                   10292:       noffset=noffset+2;
1.304     brouard  10293:       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);
                   10294:       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  10295:       fflush(ficlog); return 1;
                   10296:     }
                   10297:     else if( line[0] == 0 && line[1] == 0)
                   10298:     {
                   10299:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   10300:        noffset=noffset+4;
1.304     brouard  10301:        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);
                   10302:        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  10303:        fflush(ficlog); return 1;
                   10304:       }
                   10305:     } else{
                   10306:       ;/*printf(" Not a BOM file\n");*/
                   10307:     }
                   10308:         /* If line starts with a # it is a comment */
                   10309:     if (line[noffset] == '#') {
                   10310:       linei=linei+1;
                   10311:       break;
                   10312:     }else{
                   10313:       break;
                   10314:     }
                   10315:   }
                   10316:   fclose(fic);
                   10317:   if((fic=fopen(datafile,"r"))==NULL)    {
                   10318:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10319:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   10320:   }
                   10321:   /* Not a Bom file */
                   10322:   
1.136     brouard  10323:   i=1;
                   10324:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   10325:     linei=linei+1;
                   10326:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   10327:       if(line[j] == '\t')
                   10328:        line[j] = ' ';
                   10329:     }
                   10330:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   10331:       ;
                   10332:     };
                   10333:     line[j+1]=0;  /* Trims blanks at end of line */
                   10334:     if(line[0]=='#'){
                   10335:       fprintf(ficlog,"Comment line\n%s\n",line);
                   10336:       printf("Comment line\n%s\n",line);
                   10337:       continue;
                   10338:     }
                   10339:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  10340:     strcpy(line, linetmp);
1.223     brouard  10341:     
                   10342:     /* Loops on waves */
                   10343:     for (j=maxwav;j>=1;j--){
                   10344:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  10345:        cutv(stra, strb, line, ' '); 
                   10346:        if(strb[0]=='.') { /* Missing value */
                   10347:          lval=-1;
                   10348:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
                   10349:          cotvar[j][ntv+iv][i]=-1; /* For performance reasons */
                   10350:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   10351:            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);
                   10352:            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);
                   10353:            return 1;
                   10354:          }
                   10355:        }else{
                   10356:          errno=0;
                   10357:          /* what_kind_of_number(strb); */
                   10358:          dval=strtod(strb,&endptr); 
                   10359:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   10360:          /* if(strb != endptr && *endptr == '\0') */
                   10361:          /*    dval=dlval; */
                   10362:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10363:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10364:            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);
                   10365:            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);
                   10366:            return 1;
                   10367:          }
                   10368:          cotqvar[j][iv][i]=dval; 
                   10369:          cotvar[j][ntv+iv][i]=dval; 
                   10370:        }
                   10371:        strcpy(line,stra);
1.223     brouard  10372:       }/* end loop ntqv */
1.225     brouard  10373:       
1.223     brouard  10374:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  10375:        cutv(stra, strb, line, ' '); 
                   10376:        if(strb[0]=='.') { /* Missing value */
                   10377:          lval=-1;
                   10378:        }else{
                   10379:          errno=0;
                   10380:          lval=strtol(strb,&endptr,10); 
                   10381:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   10382:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10383:            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);
                   10384:            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);
                   10385:            return 1;
                   10386:          }
                   10387:        }
                   10388:        if(lval <-1 || lval >1){
                   10389:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10390:  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  10391:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10392:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10393:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10394:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10395:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10396:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10397:  Exiting.\n",lval,linei, i,line,iv,j);
1.238     brouard  10398:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10399:  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  10400:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10401:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10402:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10403:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10404:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10405:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10406:  Exiting.\n",lval,linei, i,line,iv,j);fflush(ficlog);
1.238     brouard  10407:          return 1;
                   10408:        }
                   10409:        cotvar[j][iv][i]=(double)(lval);
                   10410:        strcpy(line,stra);
1.223     brouard  10411:       }/* end loop ntv */
1.225     brouard  10412:       
1.223     brouard  10413:       /* Statuses  at wave */
1.137     brouard  10414:       cutv(stra, strb, line, ' '); 
1.223     brouard  10415:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  10416:        lval=-1;
1.136     brouard  10417:       }else{
1.238     brouard  10418:        errno=0;
                   10419:        lval=strtol(strb,&endptr,10); 
                   10420:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   10421:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10422:          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);
                   10423:          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);
                   10424:          return 1;
                   10425:        }
1.136     brouard  10426:       }
1.225     brouard  10427:       
1.136     brouard  10428:       s[j][i]=lval;
1.225     brouard  10429:       
1.223     brouard  10430:       /* Date of Interview */
1.136     brouard  10431:       strcpy(line,stra);
                   10432:       cutv(stra, strb,line,' ');
1.169     brouard  10433:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10434:       }
1.169     brouard  10435:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  10436:        month=99;
                   10437:        year=9999;
1.136     brouard  10438:       }else{
1.225     brouard  10439:        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);
                   10440:        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);
                   10441:        return 1;
1.136     brouard  10442:       }
                   10443:       anint[j][i]= (double) year; 
1.302     brouard  10444:       mint[j][i]= (double)month;
                   10445:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   10446:       /*       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]); */
                   10447:       /*       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]); */
                   10448:       /* } */
1.136     brouard  10449:       strcpy(line,stra);
1.223     brouard  10450:     } /* End loop on waves */
1.225     brouard  10451:     
1.223     brouard  10452:     /* Date of death */
1.136     brouard  10453:     cutv(stra, strb,line,' '); 
1.169     brouard  10454:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10455:     }
1.169     brouard  10456:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  10457:       month=99;
                   10458:       year=9999;
                   10459:     }else{
1.141     brouard  10460:       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  10461:       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);
                   10462:       return 1;
1.136     brouard  10463:     }
                   10464:     andc[i]=(double) year; 
                   10465:     moisdc[i]=(double) month; 
                   10466:     strcpy(line,stra);
                   10467:     
1.223     brouard  10468:     /* Date of birth */
1.136     brouard  10469:     cutv(stra, strb,line,' '); 
1.169     brouard  10470:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10471:     }
1.169     brouard  10472:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  10473:       month=99;
                   10474:       year=9999;
                   10475:     }else{
1.141     brouard  10476:       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);
                   10477:       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  10478:       return 1;
1.136     brouard  10479:     }
                   10480:     if (year==9999) {
1.141     brouard  10481:       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);
                   10482:       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  10483:       return 1;
                   10484:       
1.136     brouard  10485:     }
                   10486:     annais[i]=(double)(year);
1.302     brouard  10487:     moisnais[i]=(double)(month);
                   10488:     for (j=1;j<=maxwav;j++){
                   10489:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   10490:        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]);
                   10491:        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]);
                   10492:       }
                   10493:     }
                   10494: 
1.136     brouard  10495:     strcpy(line,stra);
1.225     brouard  10496:     
1.223     brouard  10497:     /* Sample weight */
1.136     brouard  10498:     cutv(stra, strb,line,' '); 
                   10499:     errno=0;
                   10500:     dval=strtod(strb,&endptr); 
                   10501:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  10502:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   10503:       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  10504:       fflush(ficlog);
                   10505:       return 1;
                   10506:     }
                   10507:     weight[i]=dval; 
                   10508:     strcpy(line,stra);
1.225     brouard  10509:     
1.223     brouard  10510:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   10511:       cutv(stra, strb, line, ' '); 
                   10512:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  10513:        lval=-1;
1.311     brouard  10514:        coqvar[iv][i]=NAN; 
                   10515:        covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  10516:       }else{
1.225     brouard  10517:        errno=0;
                   10518:        /* what_kind_of_number(strb); */
                   10519:        dval=strtod(strb,&endptr);
                   10520:        /* if(strb != endptr && *endptr == '\0') */
                   10521:        /*   dval=dlval; */
                   10522:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10523:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10524:          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);
                   10525:          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);
                   10526:          return 1;
                   10527:        }
                   10528:        coqvar[iv][i]=dval; 
1.226     brouard  10529:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  10530:       }
                   10531:       strcpy(line,stra);
                   10532:     }/* end loop nqv */
1.136     brouard  10533:     
1.223     brouard  10534:     /* Covariate values */
1.136     brouard  10535:     for (j=ncovcol;j>=1;j--){
                   10536:       cutv(stra, strb,line,' '); 
1.223     brouard  10537:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  10538:        lval=-1;
1.136     brouard  10539:       }else{
1.225     brouard  10540:        errno=0;
                   10541:        lval=strtol(strb,&endptr,10); 
                   10542:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10543:          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);
                   10544:          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);
                   10545:          return 1;
                   10546:        }
1.136     brouard  10547:       }
                   10548:       if(lval <-1 || lval >1){
1.225     brouard  10549:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  10550:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   10551:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  10552:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10553:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10554:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  10555:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  10556:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  10557:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  10558:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  10559:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   10560:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  10561:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10562:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10563:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  10564:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  10565:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  10566:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  10567:        return 1;
1.136     brouard  10568:       }
                   10569:       covar[j][i]=(double)(lval);
                   10570:       strcpy(line,stra);
                   10571:     }  
                   10572:     lstra=strlen(stra);
1.225     brouard  10573:     
1.136     brouard  10574:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   10575:       stratrunc = &(stra[lstra-9]);
                   10576:       num[i]=atol(stratrunc);
                   10577:     }
                   10578:     else
                   10579:       num[i]=atol(stra);
                   10580:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   10581:       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;}*/
                   10582:     
                   10583:     i=i+1;
                   10584:   } /* End loop reading  data */
1.225     brouard  10585:   
1.136     brouard  10586:   *imax=i-1; /* Number of individuals */
                   10587:   fclose(fic);
1.225     brouard  10588:   
1.136     brouard  10589:   return (0);
1.164     brouard  10590:   /* endread: */
1.225     brouard  10591:   printf("Exiting readdata: ");
                   10592:   fclose(fic);
                   10593:   return (1);
1.223     brouard  10594: }
1.126     brouard  10595: 
1.234     brouard  10596: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  10597:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  10598:   while (*p2 == ' ')
1.234     brouard  10599:     p2++; 
                   10600:   /* while ((*p1++ = *p2++) !=0) */
                   10601:   /*   ; */
                   10602:   /* do */
                   10603:   /*   while (*p2 == ' ') */
                   10604:   /*     p2++; */
                   10605:   /* while (*p1++ == *p2++); */
                   10606:   *stri=p2; 
1.145     brouard  10607: }
                   10608: 
1.330     brouard  10609: int decoderesult( char resultline[], int nres)
1.230     brouard  10610: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   10611: {
1.235     brouard  10612:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  10613:   char resultsav[MAXLINE];
1.330     brouard  10614:   /* int resultmodel[MAXLINE]; */
1.334     brouard  10615:   /* int modelresult[MAXLINE]; */
1.230     brouard  10616:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   10617: 
1.234     brouard  10618:   removefirstspace(&resultline);
1.332     brouard  10619:   printf("decoderesult:%s\n",resultline);
1.230     brouard  10620: 
1.332     brouard  10621:   strcpy(resultsav,resultline);
                   10622:   printf("Decoderesult resultsav=\"%s\" resultline=\"%s\"\n", resultsav, resultline);
1.230     brouard  10623:   if (strlen(resultsav) >1){
1.334     brouard  10624:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' in this resultline */
1.230     brouard  10625:   }
1.253     brouard  10626:   if(j == 0){ /* Resultline but no = */
                   10627:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   10628:     return (0);
                   10629:   }
1.234     brouard  10630:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
1.334     brouard  10631:     printf("ERROR: the number of variables in the resultline which is %d, differs from the number %d of single variables used in the model line, %s.\n",j, cptcovs, model);
                   10632:     fprintf(ficlog,"ERROR: the number of variables in the resultline which is %d, differs from the number %d of single variables used in the model line, %s.\n",j, cptcovs, model);
1.332     brouard  10633:     /* return 1;*/
1.234     brouard  10634:   }
1.334     brouard  10635:   for(k=1; k<=j;k++){ /* Loop on any covariate of the RESULT LINE */
1.234     brouard  10636:     if(nbocc(resultsav,'=') >1){
1.318     brouard  10637:       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  10638:       /* 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  10639:       cutl(strc,strd,strb,'=');  /* strb:"V4=1" strc="1" strd="V4" */
1.332     brouard  10640:       /* If a blank, then strc="V4=" and strd='\0' */
                   10641:       if(strc[0]=='\0'){
                   10642:       printf("Error in resultline, probably a blank after the \"%s\", \"result:%s\", stra=\"%s\" resultsav=\"%s\"\n",strb,resultline, stra, resultsav);
                   10643:        fprintf(ficlog,"Error in resultline, probably a blank after the \"V%s=\", resultline=%s\n",strb,resultline);
                   10644:        return 1;
                   10645:       }
1.234     brouard  10646:     }else
                   10647:       cutl(strc,strd,resultsav,'=');
1.318     brouard  10648:     Tvalsel[k]=atof(strc); /* 1 */ /* Tvalsel of k is the float value of the kth covariate appearing in this result line */
1.234     brouard  10649:     
1.230     brouard  10650:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
1.318     brouard  10651:     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  10652:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   10653:     /* cptcovsel++;     */
                   10654:     if (nbocc(stra,'=') >0)
                   10655:       strcpy(resultsav,stra); /* and analyzes it */
                   10656:   }
1.235     brouard  10657:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  10658:   /* 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  10659:   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  10660:     if(Typevar[k1]==0){ /* Single covariate in model */
                   10661:       /* 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.234     brouard  10662:       match=0;
1.318     brouard  10663:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10664:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  10665:          modelresult[nres][k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.318     brouard  10666:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
1.234     brouard  10667:          break;
                   10668:        }
                   10669:       }
                   10670:       if(match == 0){
1.338     brouard  10671:        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]);
                   10672:        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  10673:        return 1;
1.234     brouard  10674:       }
1.332     brouard  10675:     }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*/
                   10676:       /* We feed resultmodel[k1]=k2; */
                   10677:       match=0;
                   10678:       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 */
                   10679:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  10680:          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  10681:          resultmodel[nres][k1]=k2; /* Added here */
                   10682:          printf("Decoderesult first modelresult[k2=%d]=%d (k1) V%d*AGE\n",k2,k1,Tvar[k1]);
                   10683:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10684:          break;
                   10685:        }
                   10686:       }
                   10687:       if(match == 0){
1.338     brouard  10688:        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]);
                   10689:        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  10690:       return 1;
                   10691:       }
                   10692:     }else if(Typevar[k1]==2){ /* Product No age We want to get the position in the resultline of the product in the model line*/
                   10693:       /* resultmodel[nres][of such a Vn * Vm product k1] is not unique, so can't exist, we feed Tvard[k1][1] and [2] */ 
                   10694:       match=0;
                   10695:       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]);
                   10696:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10697:        if(Tvardk[k1][1]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   10698:          /* modelresult[k2]=k1; */
                   10699:          printf("Decoderesult first Product modelresult[k2=%d]=%d (k1) V%d * \n",k2,k1,Tvarsel[k2]);
                   10700:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10701:        }
                   10702:       }
                   10703:       if(match == 0){
1.338     brouard  10704:        printf("Error in result line (Product without age first variable): V%d is missing in result: %s according to model=1+age+%s\n",Tvardk[k1][1], resultline, model);
                   10705:        fprintf(ficlog,"Error in result line (Product without age first variable): V%d is missing in result: %s according to model=1+age+%s\n",Tvardk[k1][1], resultline, model);
1.332     brouard  10706:        return 1;
                   10707:       }
                   10708:       match=0;
                   10709:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10710:        if(Tvardk[k1][2]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   10711:          /* modelresult[k2]=k1;*/
                   10712:          printf("Decoderesult second Product modelresult[k2=%d]=%d (k1) * V%d \n ",k2,k1,Tvarsel[k2]);
                   10713:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10714:          break;
                   10715:        }
                   10716:       }
                   10717:       if(match == 0){
1.338     brouard  10718:        printf("Error in result line (Product without age second variable): V%d is missing in result: %s according to model=1+age+%s\n",Tvardk[k1][2], resultline, model);
                   10719:        fprintf(ficlog,"Error in result line (Product without age second variable): V%d is missing in result : %s according to model=1+age+%s\n",Tvardk[k1][2], resultline, model);
1.332     brouard  10720:        return 1;
                   10721:       }
                   10722:     }/* End of testing */
1.333     brouard  10723:   }/* End loop cptcovt */
1.235     brouard  10724:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  10725:   /* Feeds resultmodel[nres][k1]=k2 for single covariate (k1) in the model equation */
1.334     brouard  10726:   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)
                   10727:                           * Loop on resultline variables: result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  10728:     match=0;
1.318     brouard  10729:     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  10730:       if(Typevar[k1]==0){ /* Single only */
1.237     brouard  10731:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4   */
1.330     brouard  10732:          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  10733:          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  10734:          ++match;
                   10735:        }
                   10736:       }
                   10737:     }
                   10738:     if(match == 0){
1.338     brouard  10739:       printf("Error in result line: variable V%d is missing in model; result: %s, model=1+age+%s\n",Tvarsel[k2], resultline, model);
                   10740:       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  10741:       return 1;
1.234     brouard  10742:     }else if(match > 1){
1.338     brouard  10743:       printf("Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
                   10744:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
1.310     brouard  10745:       return 1;
1.234     brouard  10746:     }
                   10747:   }
1.334     brouard  10748:   /* cptcovres=j /\* Number of variables in the resultline is equal to cptcovs and thus useless *\/     */
1.234     brouard  10749:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  10750:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.330     brouard  10751:   /* nres=1st result line: V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   10752:   /* 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*/
                   10753:   /* nres=2nd result line: V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.235     brouard  10754:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   10755:   /*    1 0 0 0 */
                   10756:   /*    2 1 0 0 */
                   10757:   /*    3 0 1 0 */ 
1.330     brouard  10758:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 (nres=2)*/
1.235     brouard  10759:   /*    5 0 0 1 */
1.330     brouard  10760:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 (nres=1)*/
1.235     brouard  10761:   /*    7 0 1 1 */
                   10762:   /*    8 1 1 1 */
1.237     brouard  10763:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   10764:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   10765:   /* V5*age V5 known which value for nres?  */
                   10766:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.334     brouard  10767:   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.
                   10768:                                                   * loop on position k1 in the MODEL LINE */
1.331     brouard  10769:     /* k counting number of combination of single dummies in the equation model */
                   10770:     /* k4 counting single dummies in the equation model */
                   10771:     /* k4q counting single quantitatives in the equation model */
1.334     brouard  10772:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Dummy and Single, k1 is sorting according to MODEL, but k3 to resultline */
                   10773:        /* 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  10774:       /* 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  10775:       /* Value in the (current nres) resultline of the variable at the k1th position in the model equation resultmodel[nres][k1]= k3 */
1.332     brouard  10776:       /* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline                        */
                   10777:       /*      k3 is the position in the nres result line of the k1th variable of the model equation                                  */
                   10778:       /* Tvarsel[k3]: Name of the variable at the k3th position in the result line.                                                  */
                   10779:       /* Tvalsel[k3]: Value of the variable at the k3th position in the result line.                                                 */
                   10780:       /* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline                   */
1.334     brouard  10781:       /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline                     */
1.332     brouard  10782:       /* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line                                        */
1.330     brouard  10783:       /* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line                                                      */
1.332     brouard  10784:       k3= resultmodel[nres][k1]; /* From position k1 in model get position k3 in result line */
                   10785:       /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   10786:       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  10787:       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  10788:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][Name]=Value; stores the value into the name of the variable. */
1.332     brouard  10789:       /* Tinvresult[nres][4]=1 */
1.334     brouard  10790:       /* Tresult[nres][k4+1]=Tvalsel[k3];/\* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) *\/ */
                   10791:       Tresult[nres][k3]=Tvalsel[k3];/* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) */
                   10792:       /* Tvresult[nres][k4+1]=(int)Tvarsel[k3];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   10793:       Tvresult[nres][k3]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
1.237     brouard  10794:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.334     brouard  10795:       precov[nres][k1]=Tvalsel[k3]; /* Value from resultline of the variable at the k1 position in the model */
1.332     brouard  10796:       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  10797:       k4++;;
1.331     brouard  10798:     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Quantitative and single */
1.330     brouard  10799:       /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 */
1.332     brouard  10800:       /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline                                 */
1.330     brouard  10801:       /* Tqinvresult[nres][Name of a quantitative variable]= value of the variable in the result line                                                      */
1.332     brouard  10802:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 5 =k3q */
                   10803:       k2q=(int)Tvarsel[k3q]; /*  Name of variable at k3q th position in the resultline */
                   10804:       /* Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  10805:       /* Tqresult[nres][k4q+1]=Tvalsel[k3q]; /\* Tqresult[nres][1]=25.1 *\/ */
                   10806:       /* Tvresult[nres][k4q+1]=(int)Tvarsel[k3q];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   10807:       /* Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /\* Tvqresult[nres][1]=5 *\/ */
                   10808:       Tqresult[nres][k3q]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   10809:       Tvresult[nres][k3q]=(int)Tvarsel[k3q];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   10810:       Tvqresult[nres][k3q]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
1.237     brouard  10811:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.330     brouard  10812:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.332     brouard  10813:       precov[nres][k1]=Tvalsel[k3q];
                   10814:       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  10815:       k4q++;;
1.331     brouard  10816:     }else if( Dummy[k1]==2 ){ /* For dummy with age product */
                   10817:       /* Tvar[k1]; */ /* Age variable */
1.332     brouard  10818:       /* Wrong we want the value of variable name Tvar[k1] */
                   10819:       
                   10820:       k3= resultmodel[nres][k1]; /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
1.331     brouard  10821:       k2=(int)Tvarsel[k3]; /* nres=1 k1=2=>k3=1 Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 (V4); k1=3=>k3=2 Tvarsel[2]=3 (V3)*/
1.334     brouard  10822:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][4]=1 */
1.332     brouard  10823:       precov[nres][k1]=Tvalsel[k3];
                   10824:       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  10825:     }else if( Dummy[k1]==3 ){ /* For quant with age product */
1.332     brouard  10826:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 25.1=k3q */
1.331     brouard  10827:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  10828:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* TinvDoQresult[nres][5]=25.1 */
1.332     brouard  10829:       precov[nres][k1]=Tvalsel[k3q];
1.334     brouard  10830:       printf("Decoderesult Quantitative with age nres=%d, k1=%d, precov[nres=%d][k1=%d]=%f Tvar[%d]=V%d V(k2q=%d)= Tvarsel[%d]=%d, Tvalsel[%d]=%f\n",nres, k1, nres, k1,precov[nres][k1], k1,  Tvar[k1], k2q, k3q, Tvarsel[k3q], k3q, Tvalsel[k3q]);
1.331     brouard  10831:     }else if(Typevar[k1]==2 ){ /* For product quant or dummy (not with age) */
1.332     brouard  10832:       precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
                   10833:       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  10834:     }else{
1.332     brouard  10835:       printf("Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
                   10836:       fprintf(ficlog,"Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
1.235     brouard  10837:     }
                   10838:   }
1.234     brouard  10839:   
1.334     brouard  10840:   TKresult[nres]=++k; /* Number of combinations of dummies for the nresult and the model =Tvalsel[k3]*pow(2,k4) + 1*/
1.230     brouard  10841:   return (0);
                   10842: }
1.235     brouard  10843: 
1.230     brouard  10844: int decodemodel( char model[], int lastobs)
                   10845:  /**< This routine decodes the model and returns:
1.224     brouard  10846:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   10847:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   10848:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   10849:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   10850:        * - cptcovage number of covariates with age*products =2
                   10851:        * - cptcovs number of simple covariates
1.339     brouard  10852:        * ncovcolt=ncovcol+nqv+ntv+nqtv total of covariates in the data, not in the model equation
1.224     brouard  10853:        * - 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  10854:        *     which is a new column after the 9 (ncovcol+nqv+ntv+nqtv) variables. 
1.319     brouard  10855:        * - if k is a product Vn*Vm, covar[k][i] is filled with correct values for each individual
1.224     brouard  10856:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   10857:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   10858:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   10859:        */
1.319     brouard  10860: /* 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  10861: {
1.238     brouard  10862:   int i, j, k, ks, v;
1.227     brouard  10863:   int  j1, k1, k2, k3, k4;
1.136     brouard  10864:   char modelsav[80];
1.145     brouard  10865:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  10866:   char *strpt;
1.136     brouard  10867: 
1.145     brouard  10868:   /*removespace(model);*/
1.136     brouard  10869:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  10870:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  10871:     if (strstr(model,"AGE") !=0){
1.192     brouard  10872:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   10873:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  10874:       return 1;
                   10875:     }
1.141     brouard  10876:     if (strstr(model,"v") !=0){
1.338     brouard  10877:       printf("Error. 'v' must be in upper case 'V' model=1+age+%s ",model);
                   10878:       fprintf(ficlog,"Error. 'v' must be in upper case model=1+age+%s ",model);fflush(ficlog);
1.141     brouard  10879:       return 1;
                   10880:     }
1.187     brouard  10881:     strcpy(modelsav,model); 
                   10882:     if ((strpt=strstr(model,"age*age")) !=0){
1.338     brouard  10883:       printf(" strpt=%s, model=1+age+%s\n",strpt, model);
1.187     brouard  10884:       if(strpt != model){
1.338     brouard  10885:        printf("Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  10886:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  10887:  corresponding column of parameters.\n",model);
1.338     brouard  10888:        fprintf(ficlog,"Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  10889:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  10890:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  10891:        return 1;
1.225     brouard  10892:       }
1.187     brouard  10893:       nagesqr=1;
                   10894:       if (strstr(model,"+age*age") !=0)
1.234     brouard  10895:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  10896:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  10897:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  10898:       else 
1.234     brouard  10899:        substrchaine(modelsav, model, "age*age");
1.187     brouard  10900:     }else
                   10901:       nagesqr=0;
                   10902:     if (strlen(modelsav) >1){
                   10903:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   10904:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224     brouard  10905:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  10906:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  10907:                     * cst, age and age*age 
                   10908:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   10909:       /* including age products which are counted in cptcovage.
                   10910:        * but the covariates which are products must be treated 
                   10911:        * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  10912:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   10913:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.225     brouard  10914:       
                   10915:       
1.187     brouard  10916:       /*   Design
                   10917:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   10918:        *  <          ncovcol=8                >
                   10919:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   10920:        *   k=  1    2      3       4     5       6      7        8
                   10921:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   10922:        *  covar[k,i], value of kth covariate if not including age for individual i:
1.224     brouard  10923:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   10924:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  10925:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   10926:        *  Tage[++cptcovage]=k
                   10927:        *       if products, new covar are created after ncovcol with k1
                   10928:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   10929:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   10930:        *  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
                   10931:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   10932:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   10933:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   10934:        *  <          ncovcol=8                >
                   10935:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   10936:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   10937:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
1.319     brouard  10938:        * p Tvar[1]@12={2,   1,     3,      3,  11,     10,     8,       8,   7,   8,   5,  6}
1.187     brouard  10939:        * p Tprod[1]@2={                         6, 5}
                   10940:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   10941:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   10942:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1.319     brouard  10943:        *How to reorganize? Tvars(orted)
1.187     brouard  10944:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   10945:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   10946:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   10947:        * Struct []
                   10948:        */
1.225     brouard  10949:       
1.187     brouard  10950:       /* This loop fills the array Tvar from the string 'model'.*/
                   10951:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   10952:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   10953:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   10954:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   10955:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   10956:       /*       k=1 Tvar[1]=2 (from V2) */
                   10957:       /*       k=5 Tvar[5] */
                   10958:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  10959:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  10960:       /*       } */
1.198     brouard  10961:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  10962:       /*
                   10963:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  10964:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   10965:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   10966:       }
1.187     brouard  10967:       cptcovage=0;
1.319     brouard  10968:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model line */
                   10969:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' cutl from left to right
                   10970:                                         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" */
                   10971:        if (nbocc(modelsav,'+')==0)
                   10972:          strcpy(strb,modelsav); /* and analyzes it */
1.234     brouard  10973:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   10974:        /*scanf("%d",i);*/
1.319     brouard  10975:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V5*age+ V4+V3*age strb=V3*age */
                   10976:          cutl(strc,strd,strb,'*'); /**< k=1 strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
1.234     brouard  10977:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   10978:            /* covar is not filled and then is empty */
                   10979:            cptcovprod--;
                   10980:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
1.319     brouard  10981:            Tvar[k]=atoi(stre);  /* V2+V1+V5*age+V4+V3*age Tvar[5]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
1.234     brouard  10982:            Typevar[k]=1;  /* 1 for age product */
1.319     brouard  10983:            cptcovage++; /* Counts the number of covariates which include age as a product */
                   10984:            Tage[cptcovage]=k;  /*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
1.234     brouard  10985:            /*printf("stre=%s ", stre);*/
                   10986:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   10987:            cptcovprod--;
                   10988:            cutl(stre,strb,strc,'V');
                   10989:            Tvar[k]=atoi(stre);
                   10990:            Typevar[k]=1;  /* 1 for age product */
                   10991:            cptcovage++;
                   10992:            Tage[cptcovage]=k;
                   10993:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   10994:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   10995:            cptcovn++;
                   10996:            cptcovprodnoage++;k1++;
                   10997:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
1.339     brouard  10998:            Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* ncovcolt+k1; For model-covariate k tells which data-covariate to use but
1.234     brouard  10999:                                                because this model-covariate is a construction we invent a new column
                   11000:                                                which is after existing variables ncovcol+nqv+ntv+nqtv + k1
1.335     brouard  11001:                                                If already ncovcol=4 and model= V2 + V1 + V1*V4 + age*V3 + V3*V2
1.319     brouard  11002:                                                thus after V4 we invent V5 and V6 because age*V3 will be computed in 4
1.339     brouard  11003:                                                Tvar[3=V1*V4]=4+1=5 Tvar[5=V3*V2]=4 + 2= 6, Tvar[4=age*V3]=3 etc */
1.335     brouard  11004:            /* Please remark that the new variables are model dependent */
                   11005:            /* If we have 4 variable but the model uses only 3, like in
                   11006:             * model= V1 + age*V1 + V2 + V3 + age*V2 + age*V3 + V1*V2 + V1*V3
                   11007:             *  k=     1     2       3   4     5        6        7       8
                   11008:             * Tvar[k]=1     1       2   3     2        3       (5       6) (and not 4 5 because of V4 missing)
                   11009:             * Tage[kk]    [1]= 2           [2]=5      [3]=6                  kk=1 to cptcovage=3
                   11010:             * Tvar[Tage[kk]][1]=2          [2]=2      [3]=3
                   11011:             */
1.339     brouard  11012:            Typevar[k]=2;  /* 2 for product */
1.234     brouard  11013:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   11014:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
1.319     brouard  11015:            Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 */
1.234     brouard  11016:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
1.330     brouard  11017:            Tvardk[k][1] =atoi(strc); /* m 1 for V1*/
1.234     brouard  11018:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
1.330     brouard  11019:            Tvardk[k][2] =atoi(stre); /* n 4 for V4*/
1.234     brouard  11020:            k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   11021:            /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   11022:            /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
1.225     brouard  11023:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
1.234     brouard  11024:            /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
1.339     brouard  11025:            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 */
                   11026:              for (i=1; i<=lastobs;i++){/* For fixed product */
1.234     brouard  11027:              /* Computes the new covariate which is a product of
                   11028:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
1.339     brouard  11029:              covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   11030:              }
                   11031:            } /*End of FixedV */
1.234     brouard  11032:          } /* End age is not in the model */
                   11033:        } /* End if model includes a product */
1.319     brouard  11034:        else { /* not a product */
1.234     brouard  11035:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   11036:          /*  scanf("%d",i);*/
                   11037:          cutl(strd,strc,strb,'V');
                   11038:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   11039:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   11040:          Tvar[k]=atoi(strd);
                   11041:          Typevar[k]=0;  /* 0 for simple covariates */
                   11042:        }
                   11043:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  11044:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  11045:                                  scanf("%d",i);*/
1.187     brouard  11046:       } /* end of loop + on total covariates */
                   11047:     } /* end if strlen(modelsave == 0) age*age might exist */
                   11048:   } /* end if strlen(model == 0) */
1.136     brouard  11049:   
                   11050:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   11051:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  11052:   
1.136     brouard  11053:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  11054:      printf("cptcovprod=%d ", cptcovprod);
                   11055:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   11056:      scanf("%d ",i);*/
                   11057: 
                   11058: 
1.230     brouard  11059: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   11060:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  11061: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   11062:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   11063:    k =           1    2   3     4       5       6      7      8        9
                   11064:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
1.319     brouard  11065:    Typevar[k]=   0    0   0     2       1       0      2      1        0
1.227     brouard  11066:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   11067:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   11068:          Tmodelind[combination of covar]=k;
1.225     brouard  11069: */  
                   11070: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  11071:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  11072:   /* 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  11073:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.318     brouard  11074:   printf("Model=1+age+%s\n\
1.227     brouard  11075: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   11076: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   11077: 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  11078:   fprintf(ficlog,"Model=1+age+%s\n\
1.227     brouard  11079: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   11080: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   11081: 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.285     brouard  11082:   for(k=-1;k<=cptcovt; k++){ Fixed[k]=0; Dummy[k]=0;}
1.339     brouard  11083:   for(k=1, ncovf=0, nsd=0, nsq=0, ncovv=0, ncova=0, ncoveff=0, nqfveff=0, ntveff=0, nqtveff=0, ncovvt=0;k<=cptcovt; k++){ /* or cptocvt */
1.234     brouard  11084:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  11085:       Fixed[k]= 0;
                   11086:       Dummy[k]= 0;
1.225     brouard  11087:       ncoveff++;
1.232     brouard  11088:       ncovf++;
1.234     brouard  11089:       nsd++;
                   11090:       modell[k].maintype= FTYPE;
                   11091:       TvarsD[nsd]=Tvar[k];
                   11092:       TvarsDind[nsd]=k;
1.330     brouard  11093:       TnsdVar[Tvar[k]]=nsd;
1.234     brouard  11094:       TvarF[ncovf]=Tvar[k];
                   11095:       TvarFind[ncovf]=k;
                   11096:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   11097:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.339     brouard  11098:     /* }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /\* Product of fixed dummy (<=ncovcol) covariates For a fixed product k is higher than ncovcol *\/ */
                   11099:     }else if( Tposprod[k]>0  &&  Typevar[k]==2 && FixedV[Tvardk[k][1]] == 0 && FixedV[Tvardk[k][2]] == 0){ /* Needs a fixed product Product of fixed dummy (<=ncovcol) covariates For a fixed product k is higher than ncovcol */
1.234     brouard  11100:       Fixed[k]= 0;
                   11101:       Dummy[k]= 0;
                   11102:       ncoveff++;
                   11103:       ncovf++;
                   11104:       modell[k].maintype= FTYPE;
                   11105:       TvarF[ncovf]=Tvar[k];
1.330     brouard  11106:       /* TnsdVar[Tvar[k]]=nsd; */ /* To be done */
1.234     brouard  11107:       TvarFind[ncovf]=k;
1.230     brouard  11108:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  11109:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.240     brouard  11110:     }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  11111:       Fixed[k]= 0;
                   11112:       Dummy[k]= 1;
1.230     brouard  11113:       nqfveff++;
1.234     brouard  11114:       modell[k].maintype= FTYPE;
                   11115:       modell[k].subtype= FQ;
                   11116:       nsq++;
1.334     brouard  11117:       TvarsQ[nsq]=Tvar[k]; /* Gives the variable name (extended to products) of first nsq simple quantitative covariates (fixed or time vary see below */
                   11118:       TvarsQind[nsq]=k;    /* Gives the position in the model equation of the first nsq simple quantitative covariates (fixed or time vary) */
1.232     brouard  11119:       ncovf++;
1.234     brouard  11120:       TvarF[ncovf]=Tvar[k];
                   11121:       TvarFind[ncovf]=k;
1.231     brouard  11122:       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  11123:       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  11124:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.339     brouard  11125:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11126:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11127:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11128:       ncovvt++;
                   11129:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11130:       TvarVVind[ncovvt]=k;    /*  TvarVVind[1]=2 (second position in the model equation  */
                   11131: 
1.227     brouard  11132:       Fixed[k]= 1;
                   11133:       Dummy[k]= 0;
1.225     brouard  11134:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  11135:       modell[k].maintype= VTYPE;
                   11136:       modell[k].subtype= VD;
                   11137:       nsd++;
                   11138:       TvarsD[nsd]=Tvar[k];
                   11139:       TvarsDind[nsd]=k;
1.330     brouard  11140:       TnsdVar[Tvar[k]]=nsd; /* To be verified */
1.234     brouard  11141:       ncovv++; /* Only simple time varying variables */
                   11142:       TvarV[ncovv]=Tvar[k];
1.242     brouard  11143:       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  11144:       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 */
                   11145:       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  11146:       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);
                   11147:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  11148:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.339     brouard  11149:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11150:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11151:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11152:       ncovvt++;
                   11153:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11154:       TvarVVind[ncovvt]=k;  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11155:       
1.234     brouard  11156:       Fixed[k]= 1;
                   11157:       Dummy[k]= 1;
                   11158:       nqtveff++;
                   11159:       modell[k].maintype= VTYPE;
                   11160:       modell[k].subtype= VQ;
                   11161:       ncovv++; /* Only simple time varying variables */
                   11162:       nsq++;
1.334     brouard  11163:       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) */
                   11164:       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  11165:       TvarV[ncovv]=Tvar[k];
1.242     brouard  11166:       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  11167:       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 */
                   11168:       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  11169:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   11170:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
                   11171:       printf("Quasi TmodelQind[%d]=%d,Tvar[TmodelQind[%d]]=V%d, ncovcol=%d, nqv=%d, ntv=%d,Tvar[k]- ncovcol-nqv-ntv=%d\n",nqtveff,k,nqtveff,Tvar[k], ncovcol, nqv, ntv, Tvar[k]- ncovcol-nqv-ntv);
1.228     brouard  11172:       printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv);
1.227     brouard  11173:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  11174:       ncova++;
                   11175:       TvarA[ncova]=Tvar[k];
                   11176:       TvarAind[ncova]=k;
1.231     brouard  11177:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  11178:        Fixed[k]= 2;
                   11179:        Dummy[k]= 2;
                   11180:        modell[k].maintype= ATYPE;
                   11181:        modell[k].subtype= APFD;
                   11182:        /* ncoveff++; */
1.227     brouard  11183:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  11184:        Fixed[k]= 2;
                   11185:        Dummy[k]= 3;
                   11186:        modell[k].maintype= ATYPE;
                   11187:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   11188:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  11189:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  11190:        Fixed[k]= 3;
                   11191:        Dummy[k]= 2;
                   11192:        modell[k].maintype= ATYPE;
                   11193:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   11194:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  11195:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  11196:        Fixed[k]= 3;
                   11197:        Dummy[k]= 3;
                   11198:        modell[k].maintype= ATYPE;
                   11199:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   11200:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  11201:       }
1.339     brouard  11202:     }else if (Typevar[k] == 2) {  /* product Vn * Vm without age, V1+V3+age*V1+age*V3+V1*V3 looking at V1*V3, Typevar={0, 0, 1, 1, 2}, k=5, V1 is fixed, V3 is timevary, V5 is a product  */
                   11203:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11204:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11205:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11206:       k1=Tposprod[k];  /* Position in the products of product k, Tposprod={0, 0, 0, 0, 1} k1=1 first product but second time varying because of V3 */
                   11207:       ncovvt++;
                   11208:       TvarVV[ncovvt]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
                   11209:       TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   11210:       ncovvt++;
                   11211:       TvarVV[ncovvt]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
                   11212:       TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   11213: 
                   11214: 
                   11215:       if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   11216:        if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
1.240     brouard  11217:          Fixed[k]= 1;
                   11218:          Dummy[k]= 0;
                   11219:          modell[k].maintype= FTYPE;
                   11220:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
                   11221:          ncovf++; /* Fixed variables without age */
                   11222:          TvarF[ncovf]=Tvar[k];
                   11223:          TvarFind[ncovf]=k;
1.339     brouard  11224:        }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
                   11225:          Fixed[k]= 0;  /* Fixed product */
1.240     brouard  11226:          Dummy[k]= 1;
                   11227:          modell[k].maintype= FTYPE;
                   11228:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
                   11229:          ncovf++; /* Varying variables without age */
                   11230:          TvarF[ncovf]=Tvar[k];
                   11231:          TvarFind[ncovf]=k;
1.339     brouard  11232:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
1.240     brouard  11233:          Fixed[k]= 1;
                   11234:          Dummy[k]= 0;
                   11235:          modell[k].maintype= VTYPE;
                   11236:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
                   11237:          ncovv++; /* Varying variables without age */
1.339     brouard  11238:          TvarV[ncovv]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
                   11239:          TvarVind[ncovv]=k;/* TvarVind[1]=5 */ 
                   11240:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
1.240     brouard  11241:          Fixed[k]= 1;
                   11242:          Dummy[k]= 1;
                   11243:          modell[k].maintype= VTYPE;
                   11244:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
                   11245:          ncovv++; /* Varying variables without age */
                   11246:          TvarV[ncovv]=Tvar[k];
                   11247:          TvarVind[ncovv]=k;
                   11248:        }
1.339     brouard  11249:       }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   11250:        if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
                   11251:          Fixed[k]= 0;  /*  Fixed product */
1.240     brouard  11252:          Dummy[k]= 1;
                   11253:          modell[k].maintype= FTYPE;
                   11254:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
                   11255:          ncovf++; /* Fixed variables without age */
                   11256:          TvarF[ncovf]=Tvar[k];
                   11257:          TvarFind[ncovf]=k;
1.339     brouard  11258:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
1.240     brouard  11259:          Fixed[k]= 1;
                   11260:          Dummy[k]= 1;
                   11261:          modell[k].maintype= VTYPE;
                   11262:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
                   11263:          ncovv++; /* Varying variables without age */
                   11264:          TvarV[ncovv]=Tvar[k];
                   11265:          TvarVind[ncovv]=k;
1.339     brouard  11266:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
1.240     brouard  11267:          Fixed[k]= 1;
                   11268:          Dummy[k]= 1;
                   11269:          modell[k].maintype= VTYPE;
                   11270:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
                   11271:          ncovv++; /* Varying variables without age */
                   11272:          TvarV[ncovv]=Tvar[k];
                   11273:          TvarVind[ncovv]=k;
                   11274:          ncovv++; /* Varying variables without age */
                   11275:          TvarV[ncovv]=Tvar[k];
                   11276:          TvarVind[ncovv]=k;
                   11277:        }
1.339     brouard  11278:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
1.240     brouard  11279:        if(Tvard[k1][2] <=ncovcol){
                   11280:          Fixed[k]= 1;
                   11281:          Dummy[k]= 1;
                   11282:          modell[k].maintype= VTYPE;
                   11283:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
                   11284:          ncovv++; /* Varying variables without age */
                   11285:          TvarV[ncovv]=Tvar[k];
                   11286:          TvarVind[ncovv]=k;
                   11287:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   11288:          Fixed[k]= 1;
                   11289:          Dummy[k]= 1;
                   11290:          modell[k].maintype= VTYPE;
                   11291:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
                   11292:          ncovv++; /* Varying variables without age */
                   11293:          TvarV[ncovv]=Tvar[k];
                   11294:          TvarVind[ncovv]=k;
                   11295:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   11296:          Fixed[k]= 1;
                   11297:          Dummy[k]= 0;
                   11298:          modell[k].maintype= VTYPE;
                   11299:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
                   11300:          ncovv++; /* Varying variables without age */
                   11301:          TvarV[ncovv]=Tvar[k];
                   11302:          TvarVind[ncovv]=k;
                   11303:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   11304:          Fixed[k]= 1;
                   11305:          Dummy[k]= 1;
                   11306:          modell[k].maintype= VTYPE;
                   11307:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
                   11308:          ncovv++; /* Varying variables without age */
                   11309:          TvarV[ncovv]=Tvar[k];
                   11310:          TvarVind[ncovv]=k;
                   11311:        }
1.339     brouard  11312:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
1.240     brouard  11313:        if(Tvard[k1][2] <=ncovcol){
                   11314:          Fixed[k]= 1;
                   11315:          Dummy[k]= 1;
                   11316:          modell[k].maintype= VTYPE;
                   11317:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
                   11318:          ncovv++; /* Varying variables without age */
                   11319:          TvarV[ncovv]=Tvar[k];
                   11320:          TvarVind[ncovv]=k;
                   11321:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   11322:          Fixed[k]= 1;
                   11323:          Dummy[k]= 1;
                   11324:          modell[k].maintype= VTYPE;
                   11325:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
                   11326:          ncovv++; /* Varying variables without age */
                   11327:          TvarV[ncovv]=Tvar[k];
                   11328:          TvarVind[ncovv]=k;
                   11329:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   11330:          Fixed[k]= 1;
                   11331:          Dummy[k]= 1;
                   11332:          modell[k].maintype= VTYPE;
                   11333:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
                   11334:          ncovv++; /* Varying variables without age */
                   11335:          TvarV[ncovv]=Tvar[k];
                   11336:          TvarVind[ncovv]=k;
                   11337:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   11338:          Fixed[k]= 1;
                   11339:          Dummy[k]= 1;
                   11340:          modell[k].maintype= VTYPE;
                   11341:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
                   11342:          ncovv++; /* Varying variables without age */
                   11343:          TvarV[ncovv]=Tvar[k];
                   11344:          TvarVind[ncovv]=k;
                   11345:        }
1.227     brouard  11346:       }else{
1.240     brouard  11347:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   11348:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   11349:       } /*end k1*/
1.225     brouard  11350:     }else{
1.226     brouard  11351:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   11352:       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  11353:     }
1.227     brouard  11354:     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]);
1.231     brouard  11355:     printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype);
1.227     brouard  11356:     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]);
                   11357:   }
                   11358:   /* Searching for doublons in the model */
                   11359:   for(k1=1; k1<= cptcovt;k1++){
                   11360:     for(k2=1; k2 <k1;k2++){
1.285     brouard  11361:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   11362:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  11363:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   11364:          if(Tvar[k1]==Tvar[k2]){
1.338     brouard  11365:            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]);
                   11366:            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  11367:            return(1);
                   11368:          }
                   11369:        }else if (Typevar[k1] ==2){
                   11370:          k3=Tposprod[k1];
                   11371:          k4=Tposprod[k2];
                   11372:          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  11373:            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]]);
                   11374:            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  11375:            return(1);
                   11376:          }
                   11377:        }
1.227     brouard  11378:       }
                   11379:     }
1.225     brouard  11380:   }
                   11381:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   11382:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  11383:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   11384:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.137     brouard  11385:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  11386:   /*endread:*/
1.225     brouard  11387:   printf("Exiting decodemodel: ");
                   11388:   return (1);
1.136     brouard  11389: }
                   11390: 
1.169     brouard  11391: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  11392: {/* Check ages at death */
1.136     brouard  11393:   int i, m;
1.218     brouard  11394:   int firstone=0;
                   11395:   
1.136     brouard  11396:   for (i=1; i<=imx; i++) {
                   11397:     for(m=2; (m<= maxwav); m++) {
                   11398:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   11399:        anint[m][i]=9999;
1.216     brouard  11400:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   11401:          s[m][i]=-1;
1.136     brouard  11402:       }
                   11403:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  11404:        *nberr = *nberr + 1;
1.218     brouard  11405:        if(firstone == 0){
                   11406:          firstone=1;
1.260     brouard  11407:        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  11408:        }
1.262     brouard  11409:        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  11410:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  11411:       }
                   11412:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  11413:        (*nberr)++;
1.259     brouard  11414:        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  11415:        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  11416:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  11417:       }
                   11418:     }
                   11419:   }
                   11420: 
                   11421:   for (i=1; i<=imx; i++)  {
                   11422:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   11423:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  11424:       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  11425:        if (s[m][i] >= nlstate+1) {
1.169     brouard  11426:          if(agedc[i]>0){
                   11427:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  11428:              agev[m][i]=agedc[i];
1.214     brouard  11429:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  11430:            }else {
1.136     brouard  11431:              if ((int)andc[i]!=9999){
                   11432:                nbwarn++;
                   11433:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   11434:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   11435:                agev[m][i]=-1;
                   11436:              }
                   11437:            }
1.169     brouard  11438:          } /* agedc > 0 */
1.214     brouard  11439:        } /* end if */
1.136     brouard  11440:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   11441:                                 years but with the precision of a month */
                   11442:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   11443:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   11444:            agev[m][i]=1;
                   11445:          else if(agev[m][i] < *agemin){ 
                   11446:            *agemin=agev[m][i];
                   11447:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   11448:          }
                   11449:          else if(agev[m][i] >*agemax){
                   11450:            *agemax=agev[m][i];
1.156     brouard  11451:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  11452:          }
                   11453:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   11454:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  11455:        } /* en if 9*/
1.136     brouard  11456:        else { /* =9 */
1.214     brouard  11457:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  11458:          agev[m][i]=1;
                   11459:          s[m][i]=-1;
                   11460:        }
                   11461:       }
1.214     brouard  11462:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  11463:        agev[m][i]=1;
1.214     brouard  11464:       else{
                   11465:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   11466:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   11467:        agev[m][i]=0;
                   11468:       }
                   11469:     } /* End for lastpass */
                   11470:   }
1.136     brouard  11471:     
                   11472:   for (i=1; i<=imx; i++)  {
                   11473:     for(m=firstpass; (m<=lastpass); m++){
                   11474:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  11475:        (*nberr)++;
1.136     brouard  11476:        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);     
                   11477:        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);     
                   11478:        return 1;
                   11479:       }
                   11480:     }
                   11481:   }
                   11482: 
                   11483:   /*for (i=1; i<=imx; i++){
                   11484:   for (m=firstpass; (m<lastpass); m++){
                   11485:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   11486: }
                   11487: 
                   11488: }*/
                   11489: 
                   11490: 
1.139     brouard  11491:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   11492:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  11493: 
                   11494:   return (0);
1.164     brouard  11495:  /* endread:*/
1.136     brouard  11496:     printf("Exiting calandcheckages: ");
                   11497:     return (1);
                   11498: }
                   11499: 
1.172     brouard  11500: #if defined(_MSC_VER)
                   11501: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   11502: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   11503: //#include "stdafx.h"
                   11504: //#include <stdio.h>
                   11505: //#include <tchar.h>
                   11506: //#include <windows.h>
                   11507: //#include <iostream>
                   11508: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   11509: 
                   11510: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   11511: 
                   11512: BOOL IsWow64()
                   11513: {
                   11514:        BOOL bIsWow64 = FALSE;
                   11515: 
                   11516:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   11517:        //  (HANDLE, PBOOL);
                   11518: 
                   11519:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   11520: 
                   11521:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   11522:        const char funcName[] = "IsWow64Process";
                   11523:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   11524:                GetProcAddress(module, funcName);
                   11525: 
                   11526:        if (NULL != fnIsWow64Process)
                   11527:        {
                   11528:                if (!fnIsWow64Process(GetCurrentProcess(),
                   11529:                        &bIsWow64))
                   11530:                        //throw std::exception("Unknown error");
                   11531:                        printf("Unknown error\n");
                   11532:        }
                   11533:        return bIsWow64 != FALSE;
                   11534: }
                   11535: #endif
1.177     brouard  11536: 
1.191     brouard  11537: void syscompilerinfo(int logged)
1.292     brouard  11538: {
                   11539: #include <stdint.h>
                   11540: 
                   11541:   /* #include "syscompilerinfo.h"*/
1.185     brouard  11542:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   11543:    /* /GS /W3 /Gy
                   11544:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   11545:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   11546:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  11547:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   11548:    */ 
                   11549:    /* 64 bits */
1.185     brouard  11550:    /*
                   11551:      /GS /W3 /Gy
                   11552:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   11553:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   11554:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   11555:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   11556:    /* Optimization are useless and O3 is slower than O2 */
                   11557:    /*
                   11558:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   11559:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   11560:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   11561:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   11562:    */
1.186     brouard  11563:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  11564:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   11565:       /PDB:"visual studio
                   11566:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   11567:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   11568:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   11569:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   11570:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   11571:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   11572:       uiAccess='false'"
                   11573:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   11574:       /NOLOGO /TLBID:1
                   11575:    */
1.292     brouard  11576: 
                   11577: 
1.177     brouard  11578: #if defined __INTEL_COMPILER
1.178     brouard  11579: #if defined(__GNUC__)
                   11580:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   11581: #endif
1.177     brouard  11582: #elif defined(__GNUC__) 
1.179     brouard  11583: #ifndef  __APPLE__
1.174     brouard  11584: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  11585: #endif
1.177     brouard  11586:    struct utsname sysInfo;
1.178     brouard  11587:    int cross = CROSS;
                   11588:    if (cross){
                   11589:           printf("Cross-");
1.191     brouard  11590:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  11591:    }
1.174     brouard  11592: #endif
                   11593: 
1.191     brouard  11594:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  11595: #if defined(__clang__)
1.191     brouard  11596:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  11597: #endif
                   11598: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  11599:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  11600: #endif
                   11601: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  11602:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  11603: #endif
                   11604: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  11605:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  11606: #endif
                   11607: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  11608:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  11609: #endif
                   11610: #if defined(_MSC_VER)
1.191     brouard  11611:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  11612: #endif
                   11613: #if defined(__PGI)
1.191     brouard  11614:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  11615: #endif
                   11616: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  11617:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  11618: #endif
1.191     brouard  11619:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  11620:    
1.167     brouard  11621: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   11622: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   11623:     // Windows (x64 and x86)
1.191     brouard  11624:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  11625: #elif __unix__ // all unices, not all compilers
                   11626:     // Unix
1.191     brouard  11627:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  11628: #elif __linux__
                   11629:     // linux
1.191     brouard  11630:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  11631: #elif __APPLE__
1.174     brouard  11632:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  11633:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  11634: #endif
                   11635: 
                   11636: /*  __MINGW32__          */
                   11637: /*  __CYGWIN__  */
                   11638: /* __MINGW64__  */
                   11639: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   11640: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   11641: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   11642: /* _WIN64  // Defined for applications for Win64. */
                   11643: /* _M_X64 // Defined for compilations that target x64 processors. */
                   11644: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  11645: 
1.167     brouard  11646: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  11647:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  11648: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  11649:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  11650: #else
1.191     brouard  11651:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  11652: #endif
                   11653: 
1.169     brouard  11654: #if defined(__GNUC__)
                   11655: # if defined(__GNUC_PATCHLEVEL__)
                   11656: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   11657:                             + __GNUC_MINOR__ * 100 \
                   11658:                             + __GNUC_PATCHLEVEL__)
                   11659: # else
                   11660: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   11661:                             + __GNUC_MINOR__ * 100)
                   11662: # endif
1.174     brouard  11663:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  11664:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  11665: 
                   11666:    if (uname(&sysInfo) != -1) {
                   11667:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  11668:         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  11669:    }
                   11670:    else
                   11671:       perror("uname() error");
1.179     brouard  11672:    //#ifndef __INTEL_COMPILER 
                   11673: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  11674:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  11675:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  11676: #endif
1.169     brouard  11677: #endif
1.172     brouard  11678: 
1.286     brouard  11679:    //   void main ()
1.172     brouard  11680:    //   {
1.169     brouard  11681: #if defined(_MSC_VER)
1.174     brouard  11682:    if (IsWow64()){
1.191     brouard  11683:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   11684:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  11685:    }
                   11686:    else{
1.191     brouard  11687:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   11688:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  11689:    }
1.172     brouard  11690:    //     printf("\nPress Enter to continue...");
                   11691:    //     getchar();
                   11692:    //   }
                   11693: 
1.169     brouard  11694: #endif
                   11695:    
1.167     brouard  11696: 
1.219     brouard  11697: }
1.136     brouard  11698: 
1.219     brouard  11699: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  11700:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.332     brouard  11701:   /* Computes the prevalence limit for each combination of the dummy covariates */
1.235     brouard  11702:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  11703:   /* double ftolpl = 1.e-10; */
1.180     brouard  11704:   double age, agebase, agelim;
1.203     brouard  11705:   double tot;
1.180     brouard  11706: 
1.202     brouard  11707:   strcpy(filerespl,"PL_");
                   11708:   strcat(filerespl,fileresu);
                   11709:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  11710:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   11711:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  11712:   }
1.288     brouard  11713:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   11714:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  11715:   pstamp(ficrespl);
1.288     brouard  11716:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  11717:   fprintf(ficrespl,"#Age ");
                   11718:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   11719:   fprintf(ficrespl,"\n");
1.180     brouard  11720:   
1.219     brouard  11721:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  11722: 
1.219     brouard  11723:   agebase=ageminpar;
                   11724:   agelim=agemaxpar;
1.180     brouard  11725: 
1.227     brouard  11726:   /* i1=pow(2,ncoveff); */
1.234     brouard  11727:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  11728:   if (cptcovn < 1){i1=1;}
1.180     brouard  11729: 
1.337     brouard  11730:   /* for(k=1; k<=i1;k++){ /\* For each combination k of dummy covariates in the model *\/ */
1.238     brouard  11731:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  11732:       k=TKresult[nres];
1.338     brouard  11733:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  11734:       /* if(i1 != 1 && TKresult[nres]!= k) /\* We found the combination k corresponding to the resultline value of dummies *\/ */
                   11735:       /*       continue; */
1.235     brouard  11736: 
1.238     brouard  11737:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11738:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   11739:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   11740:       /* k=k+1; */
                   11741:       /* to clean */
1.332     brouard  11742:       /*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*/
1.238     brouard  11743:       fprintf(ficrespl,"#******");
                   11744:       printf("#******");
                   11745:       fprintf(ficlog,"#******");
1.337     brouard  11746:       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  11747:        /* fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Here problem for varying dummy*\/ */
1.337     brouard  11748:        /* printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11749:        /* fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11750:        fprintf(ficrespl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11751:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11752:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11753:       }
                   11754:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   11755:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11756:       /*       fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11757:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11758:       /* } */
1.238     brouard  11759:       fprintf(ficrespl,"******\n");
                   11760:       printf("******\n");
                   11761:       fprintf(ficlog,"******\n");
                   11762:       if(invalidvarcomb[k]){
                   11763:        printf("\nCombination (%d) ignored because no case \n",k); 
                   11764:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   11765:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   11766:        continue;
                   11767:       }
1.219     brouard  11768: 
1.238     brouard  11769:       fprintf(ficrespl,"#Age ");
1.337     brouard  11770:       /* for(j=1;j<=cptcoveff;j++) { */
                   11771:       /*       fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11772:       /* } */
                   11773:       for(j=1;j<=cptcovs;j++) { /* New the quanti variable is added */
                   11774:        fprintf(ficrespl,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  11775:       }
                   11776:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   11777:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  11778:     
1.238     brouard  11779:       for (age=agebase; age<=agelim; age++){
                   11780:        /* for (age=agebase; age<=agebase; age++){ */
1.337     brouard  11781:        /**< Computes the prevalence limit in each live state at age x and for covariate combination (k and) nres */
                   11782:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres); /* Nicely done */
1.238     brouard  11783:        fprintf(ficrespl,"%.0f ",age );
1.337     brouard  11784:        /* for(j=1;j<=cptcoveff;j++) */
                   11785:        /*   fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11786:        for(j=1;j<=cptcovs;j++)
                   11787:          fprintf(ficrespl,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  11788:        tot=0.;
                   11789:        for(i=1; i<=nlstate;i++){
                   11790:          tot +=  prlim[i][i];
                   11791:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   11792:        }
                   11793:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   11794:       } /* Age */
                   11795:       /* was end of cptcod */
1.337     brouard  11796:     } /* nres */
                   11797:   /* } /\* for each combination *\/ */
1.219     brouard  11798:   return 0;
1.180     brouard  11799: }
                   11800: 
1.218     brouard  11801: 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  11802:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  11803:        
                   11804:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   11805:    * at any age between ageminpar and agemaxpar
                   11806:         */
1.235     brouard  11807:   int i, j, k, i1, nres=0 ;
1.217     brouard  11808:   /* double ftolpl = 1.e-10; */
                   11809:   double age, agebase, agelim;
                   11810:   double tot;
1.218     brouard  11811:   /* double ***mobaverage; */
                   11812:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  11813: 
                   11814:   strcpy(fileresplb,"PLB_");
                   11815:   strcat(fileresplb,fileresu);
                   11816:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  11817:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   11818:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  11819:   }
1.288     brouard  11820:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   11821:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  11822:   pstamp(ficresplb);
1.288     brouard  11823:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  11824:   fprintf(ficresplb,"#Age ");
                   11825:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   11826:   fprintf(ficresplb,"\n");
                   11827:   
1.218     brouard  11828:   
                   11829:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   11830:   
                   11831:   agebase=ageminpar;
                   11832:   agelim=agemaxpar;
                   11833:   
                   11834:   
1.227     brouard  11835:   i1=pow(2,cptcoveff);
1.218     brouard  11836:   if (cptcovn < 1){i1=1;}
1.227     brouard  11837:   
1.238     brouard  11838:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.338     brouard  11839:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   11840:       k=TKresult[nres];
                   11841:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   11842:      /* if(i1 != 1 && TKresult[nres]!= k) */
                   11843:      /*        continue; */
                   11844:      /* /\*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*\/ */
1.238     brouard  11845:       fprintf(ficresplb,"#******");
                   11846:       printf("#******");
                   11847:       fprintf(ficlog,"#******");
1.338     brouard  11848:       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) */
                   11849:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11850:        fprintf(ficresplb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11851:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  11852:       }
1.338     brouard  11853:       /* for(j=1;j<=cptcoveff ;j++) {/\* all covariates *\/ */
                   11854:       /*       fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11855:       /*       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11856:       /*       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11857:       /* } */
                   11858:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   11859:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   11860:       /*       fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   11861:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   11862:       /* } */
1.238     brouard  11863:       fprintf(ficresplb,"******\n");
                   11864:       printf("******\n");
                   11865:       fprintf(ficlog,"******\n");
                   11866:       if(invalidvarcomb[k]){
                   11867:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   11868:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   11869:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   11870:        continue;
                   11871:       }
1.218     brouard  11872:     
1.238     brouard  11873:       fprintf(ficresplb,"#Age ");
1.338     brouard  11874:       for(j=1;j<=cptcovs;j++) {
                   11875:        fprintf(ficresplb,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  11876:       }
                   11877:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   11878:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  11879:     
                   11880:     
1.238     brouard  11881:       for (age=agebase; age<=agelim; age++){
                   11882:        /* for (age=agebase; age<=agebase; age++){ */
                   11883:        if(mobilavproj > 0){
                   11884:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   11885:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  11886:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  11887:        }else if (mobilavproj == 0){
                   11888:          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);
                   11889:          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);
                   11890:          exit(1);
                   11891:        }else{
                   11892:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  11893:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  11894:          /* printf("TOTOT\n"); */
                   11895:           /* exit(1); */
1.238     brouard  11896:        }
                   11897:        fprintf(ficresplb,"%.0f ",age );
1.338     brouard  11898:        for(j=1;j<=cptcovs;j++)
                   11899:          fprintf(ficresplb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  11900:        tot=0.;
                   11901:        for(i=1; i<=nlstate;i++){
                   11902:          tot +=  bprlim[i][i];
                   11903:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   11904:        }
                   11905:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   11906:       } /* Age */
                   11907:       /* was end of cptcod */
1.255     brouard  11908:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.338     brouard  11909:     /* } /\* end of any combination *\/ */
1.238     brouard  11910:   } /* end of nres */  
1.218     brouard  11911:   /* hBijx(p, bage, fage); */
                   11912:   /* fclose(ficrespijb); */
                   11913:   
                   11914:   return 0;
1.217     brouard  11915: }
1.218     brouard  11916:  
1.180     brouard  11917: int hPijx(double *p, int bage, int fage){
                   11918:     /*------------- h Pij x at various ages ------------*/
1.336     brouard  11919:   /* to be optimized with precov */
1.180     brouard  11920:   int stepsize;
                   11921:   int agelim;
                   11922:   int hstepm;
                   11923:   int nhstepm;
1.235     brouard  11924:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  11925: 
                   11926:   double agedeb;
                   11927:   double ***p3mat;
                   11928: 
1.337     brouard  11929:   strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
                   11930:   if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   11931:     printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   11932:     fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   11933:   }
                   11934:   printf("Computing pij: result on file '%s' \n", filerespij);
                   11935:   fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   11936:   
                   11937:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   11938:   /*if (stepm<=24) stepsize=2;*/
                   11939:   
                   11940:   agelim=AGESUP;
                   11941:   hstepm=stepsize*YEARM; /* Every year of age */
                   11942:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   11943:   
                   11944:   /* hstepm=1;   aff par mois*/
                   11945:   pstamp(ficrespij);
                   11946:   fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   11947:   i1= pow(2,cptcoveff);
                   11948:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11949:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   11950:   /*   k=k+1;  */
                   11951:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11952:     k=TKresult[nres];
1.338     brouard  11953:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  11954:     /* for(k=1; k<=i1;k++){ */
                   11955:     /* if(i1 != 1 && TKresult[nres]!= k) */
                   11956:     /*         continue; */
                   11957:     fprintf(ficrespij,"\n#****** ");
                   11958:     for(j=1;j<=cptcovs;j++){
                   11959:       fprintf(ficrespij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11960:       /* fprintf(ficrespij,"@wV%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11961:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   11962:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11963:       /*       fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11964:     }
                   11965:     fprintf(ficrespij,"******\n");
                   11966:     
                   11967:     for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   11968:       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   11969:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   11970:       
                   11971:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   11972:       
                   11973:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11974:       oldm=oldms;savm=savms;
                   11975:       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
                   11976:       fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   11977:       for(i=1; i<=nlstate;i++)
                   11978:        for(j=1; j<=nlstate+ndeath;j++)
                   11979:          fprintf(ficrespij," %1d-%1d",i,j);
                   11980:       fprintf(ficrespij,"\n");
                   11981:       for (h=0; h<=nhstepm; h++){
                   11982:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   11983:        fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.183     brouard  11984:        for(i=1; i<=nlstate;i++)
                   11985:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  11986:            fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.183     brouard  11987:        fprintf(ficrespij,"\n");
                   11988:       }
1.337     brouard  11989:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11990:       fprintf(ficrespij,"\n");
1.180     brouard  11991:     }
1.337     brouard  11992:   }
                   11993:   /*}*/
                   11994:   return 0;
1.180     brouard  11995: }
1.218     brouard  11996:  
                   11997:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  11998:     /*------------- h Bij x at various ages ------------*/
1.336     brouard  11999:     /* To be optimized with precov */
1.217     brouard  12000:   int stepsize;
1.218     brouard  12001:   /* int agelim; */
                   12002:        int ageminl;
1.217     brouard  12003:   int hstepm;
                   12004:   int nhstepm;
1.238     brouard  12005:   int h, i, i1, j, k, nres;
1.218     brouard  12006:        
1.217     brouard  12007:   double agedeb;
                   12008:   double ***p3mat;
1.218     brouard  12009:        
                   12010:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   12011:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   12012:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   12013:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   12014:   }
                   12015:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   12016:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   12017:   
                   12018:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   12019:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  12020:   
1.218     brouard  12021:   /* agelim=AGESUP; */
1.289     brouard  12022:   ageminl=AGEINF; /* was 30 */
1.218     brouard  12023:   hstepm=stepsize*YEARM; /* Every year of age */
                   12024:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   12025:   
                   12026:   /* hstepm=1;   aff par mois*/
                   12027:   pstamp(ficrespijb);
1.255     brouard  12028:   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  12029:   i1= pow(2,cptcoveff);
1.218     brouard  12030:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12031:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   12032:   /*   k=k+1;  */
1.238     brouard  12033:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  12034:     k=TKresult[nres];
1.338     brouard  12035:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12036:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   12037:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   12038:     /*         continue; */
                   12039:     fprintf(ficrespijb,"\n#****** ");
                   12040:     for(j=1;j<=cptcovs;j++){
1.338     brouard  12041:       fprintf(ficrespijb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.337     brouard  12042:       /* for(j=1;j<=cptcoveff;j++) */
                   12043:       /*       fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12044:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   12045:       /*       fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12046:     }
                   12047:     fprintf(ficrespijb,"******\n");
                   12048:     if(invalidvarcomb[k]){  /* Is it necessary here? */
                   12049:       fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   12050:       continue;
                   12051:     }
                   12052:     
                   12053:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   12054:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   12055:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   12056:       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 */
                   12057:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
                   12058:       
                   12059:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   12060:       
                   12061:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   12062:       /* and memory limitations if stepm is small */
                   12063:       
                   12064:       /* oldm=oldms;savm=savms; */
                   12065:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   12066:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);/* Bug valgrind */
                   12067:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
                   12068:       fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
                   12069:       for(i=1; i<=nlstate;i++)
                   12070:        for(j=1; j<=nlstate+ndeath;j++)
                   12071:          fprintf(ficrespijb," %1d-%1d",i,j);
                   12072:       fprintf(ficrespijb,"\n");
                   12073:       for (h=0; h<=nhstepm; h++){
                   12074:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   12075:        fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   12076:        /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
1.217     brouard  12077:        for(i=1; i<=nlstate;i++)
                   12078:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  12079:            fprintf(ficrespijb," %.5f", p3mat[i][j][h]);/* Bug valgrind */
1.217     brouard  12080:        fprintf(ficrespijb,"\n");
1.337     brouard  12081:       }
                   12082:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12083:       fprintf(ficrespijb,"\n");
                   12084:     } /* end age deb */
                   12085:     /* } /\* end combination *\/ */
1.238     brouard  12086:   } /* end nres */
1.218     brouard  12087:   return 0;
                   12088:  } /*  hBijx */
1.217     brouard  12089: 
1.180     brouard  12090: 
1.136     brouard  12091: /***********************************************/
                   12092: /**************** Main Program *****************/
                   12093: /***********************************************/
                   12094: 
                   12095: int main(int argc, char *argv[])
                   12096: {
                   12097: #ifdef GSL
                   12098:   const gsl_multimin_fminimizer_type *T;
                   12099:   size_t iteri = 0, it;
                   12100:   int rval = GSL_CONTINUE;
                   12101:   int status = GSL_SUCCESS;
                   12102:   double ssval;
                   12103: #endif
                   12104:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  12105:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   12106:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  12107:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  12108:   int jj, ll, li, lj, lk;
1.136     brouard  12109:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  12110:   int num_filled;
1.136     brouard  12111:   int itimes;
                   12112:   int NDIM=2;
                   12113:   int vpopbased=0;
1.235     brouard  12114:   int nres=0;
1.258     brouard  12115:   int endishere=0;
1.277     brouard  12116:   int noffset=0;
1.274     brouard  12117:   int ncurrv=0; /* Temporary variable */
                   12118:   
1.164     brouard  12119:   char ca[32], cb[32];
1.136     brouard  12120:   /*  FILE *fichtm; *//* Html File */
                   12121:   /* FILE *ficgp;*/ /*Gnuplot File */
                   12122:   struct stat info;
1.191     brouard  12123:   double agedeb=0.;
1.194     brouard  12124: 
                   12125:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  12126:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  12127: 
1.165     brouard  12128:   double fret;
1.191     brouard  12129:   double dum=0.; /* Dummy variable */
1.136     brouard  12130:   double ***p3mat;
1.218     brouard  12131:   /* double ***mobaverage; */
1.319     brouard  12132:   double wald;
1.164     brouard  12133: 
                   12134:   char line[MAXLINE];
1.197     brouard  12135:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   12136: 
1.234     brouard  12137:   char  modeltemp[MAXLINE];
1.332     brouard  12138:   char resultline[MAXLINE], resultlineori[MAXLINE];
1.230     brouard  12139:   
1.136     brouard  12140:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  12141:   char *tok, *val; /* pathtot */
1.334     brouard  12142:   /* int firstobs=1, lastobs=10; /\* nobs = lastobs-firstobs declared globally ;*\/ */
1.195     brouard  12143:   int c,  h , cpt, c2;
1.191     brouard  12144:   int jl=0;
                   12145:   int i1, j1, jk, stepsize=0;
1.194     brouard  12146:   int count=0;
                   12147: 
1.164     brouard  12148:   int *tab; 
1.136     brouard  12149:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  12150:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   12151:   /* double anprojf, mprojf, jprojf; */
                   12152:   /* double jintmean,mintmean,aintmean;   */
                   12153:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   12154:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   12155:   double yrfproj= 10.0; /* Number of years of forward projections */
                   12156:   double yrbproj= 10.0; /* Number of years of backward projections */
                   12157:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  12158:   int mobilav=0,popforecast=0;
1.191     brouard  12159:   int hstepm=0, nhstepm=0;
1.136     brouard  12160:   int agemortsup;
                   12161:   float  sumlpop=0.;
                   12162:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   12163:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   12164: 
1.191     brouard  12165:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  12166:   double ftolpl=FTOL;
                   12167:   double **prlim;
1.217     brouard  12168:   double **bprlim;
1.317     brouard  12169:   double ***param; /* Matrix of parameters, param[i][j][k] param=ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel) 
                   12170:                     state of origin, state of destination including death, for each covariate: constante, age, and V1 V2 etc. */
1.251     brouard  12171:   double ***paramstart; /* Matrix of starting parameter values */
                   12172:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  12173:   double **matcov; /* Matrix of covariance */
1.203     brouard  12174:   double **hess; /* Hessian matrix */
1.136     brouard  12175:   double ***delti3; /* Scale */
                   12176:   double *delti; /* Scale */
                   12177:   double ***eij, ***vareij;
                   12178:   double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  12179: 
1.136     brouard  12180:   double *epj, vepp;
1.164     brouard  12181: 
1.273     brouard  12182:   double dateprev1, dateprev2;
1.296     brouard  12183:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   12184:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   12185: 
1.217     brouard  12186: 
1.136     brouard  12187:   double **ximort;
1.145     brouard  12188:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  12189:   int *dcwave;
                   12190: 
1.164     brouard  12191:   char z[1]="c";
1.136     brouard  12192: 
                   12193:   /*char  *strt;*/
                   12194:   char strtend[80];
1.126     brouard  12195: 
1.164     brouard  12196: 
1.126     brouard  12197: /*   setlocale (LC_ALL, ""); */
                   12198: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   12199: /*   textdomain (PACKAGE); */
                   12200: /*   setlocale (LC_CTYPE, ""); */
                   12201: /*   setlocale (LC_MESSAGES, ""); */
                   12202: 
                   12203:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  12204:   rstart_time = time(NULL);  
                   12205:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   12206:   start_time = *localtime(&rstart_time);
1.126     brouard  12207:   curr_time=start_time;
1.157     brouard  12208:   /*tml = *localtime(&start_time.tm_sec);*/
                   12209:   /* strcpy(strstart,asctime(&tml)); */
                   12210:   strcpy(strstart,asctime(&start_time));
1.126     brouard  12211: 
                   12212: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  12213: /*  tp.tm_sec = tp.tm_sec +86400; */
                   12214: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  12215: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   12216: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   12217: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  12218: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  12219: /*   strt=asctime(&tmg); */
                   12220: /*   printf("Time(after) =%s",strstart);  */
                   12221: /*  (void) time (&time_value);
                   12222: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   12223: *  tm = *localtime(&time_value);
                   12224: *  strstart=asctime(&tm);
                   12225: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   12226: */
                   12227: 
                   12228:   nberr=0; /* Number of errors and warnings */
                   12229:   nbwarn=0;
1.184     brouard  12230: #ifdef WIN32
                   12231:   _getcwd(pathcd, size);
                   12232: #else
1.126     brouard  12233:   getcwd(pathcd, size);
1.184     brouard  12234: #endif
1.191     brouard  12235:   syscompilerinfo(0);
1.196     brouard  12236:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  12237:   if(argc <=1){
                   12238:     printf("\nEnter the parameter file name: ");
1.205     brouard  12239:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   12240:       printf("ERROR Empty parameter file name\n");
                   12241:       goto end;
                   12242:     }
1.126     brouard  12243:     i=strlen(pathr);
                   12244:     if(pathr[i-1]=='\n')
                   12245:       pathr[i-1]='\0';
1.156     brouard  12246:     i=strlen(pathr);
1.205     brouard  12247:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  12248:       pathr[i-1]='\0';
1.205     brouard  12249:     }
                   12250:     i=strlen(pathr);
                   12251:     if( i==0 ){
                   12252:       printf("ERROR Empty parameter file name\n");
                   12253:       goto end;
                   12254:     }
                   12255:     for (tok = pathr; tok != NULL; ){
1.126     brouard  12256:       printf("Pathr |%s|\n",pathr);
                   12257:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   12258:       printf("val= |%s| pathr=%s\n",val,pathr);
                   12259:       strcpy (pathtot, val);
                   12260:       if(pathr[0] == '\0') break; /* Dirty */
                   12261:     }
                   12262:   }
1.281     brouard  12263:   else if (argc<=2){
                   12264:     strcpy(pathtot,argv[1]);
                   12265:   }
1.126     brouard  12266:   else{
                   12267:     strcpy(pathtot,argv[1]);
1.281     brouard  12268:     strcpy(z,argv[2]);
                   12269:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  12270:   }
                   12271:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   12272:   /*cygwin_split_path(pathtot,path,optionfile);
                   12273:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   12274:   /* cutv(path,optionfile,pathtot,'\\');*/
                   12275: 
                   12276:   /* Split argv[0], imach program to get pathimach */
                   12277:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   12278:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   12279:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   12280:  /*   strcpy(pathimach,argv[0]); */
                   12281:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   12282:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   12283:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  12284: #ifdef WIN32
                   12285:   _chdir(path); /* Can be a relative path */
                   12286:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   12287: #else
1.126     brouard  12288:   chdir(path); /* Can be a relative path */
1.184     brouard  12289:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   12290: #endif
                   12291:   printf("Current directory %s!\n",pathcd);
1.126     brouard  12292:   strcpy(command,"mkdir ");
                   12293:   strcat(command,optionfilefiname);
                   12294:   if((outcmd=system(command)) != 0){
1.169     brouard  12295:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  12296:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   12297:     /* fclose(ficlog); */
                   12298: /*     exit(1); */
                   12299:   }
                   12300: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   12301: /*     perror("mkdir"); */
                   12302: /*   } */
                   12303: 
                   12304:   /*-------- arguments in the command line --------*/
                   12305: 
1.186     brouard  12306:   /* Main Log file */
1.126     brouard  12307:   strcat(filelog, optionfilefiname);
                   12308:   strcat(filelog,".log");    /* */
                   12309:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   12310:     printf("Problem with logfile %s\n",filelog);
                   12311:     goto end;
                   12312:   }
                   12313:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  12314:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  12315:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   12316:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   12317:  path=%s \n\
                   12318:  optionfile=%s\n\
                   12319:  optionfilext=%s\n\
1.156     brouard  12320:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  12321: 
1.197     brouard  12322:   syscompilerinfo(1);
1.167     brouard  12323: 
1.126     brouard  12324:   printf("Local time (at start):%s",strstart);
                   12325:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   12326:   fflush(ficlog);
                   12327: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  12328: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  12329: 
                   12330:   /* */
                   12331:   strcpy(fileres,"r");
                   12332:   strcat(fileres, optionfilefiname);
1.201     brouard  12333:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  12334:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  12335:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  12336: 
1.186     brouard  12337:   /* Main ---------arguments file --------*/
1.126     brouard  12338: 
                   12339:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  12340:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   12341:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  12342:     fflush(ficlog);
1.149     brouard  12343:     /* goto end; */
                   12344:     exit(70); 
1.126     brouard  12345:   }
                   12346: 
                   12347:   strcpy(filereso,"o");
1.201     brouard  12348:   strcat(filereso,fileresu);
1.126     brouard  12349:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   12350:     printf("Problem with Output resultfile: %s\n", filereso);
                   12351:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   12352:     fflush(ficlog);
                   12353:     goto end;
                   12354:   }
1.278     brouard  12355:       /*-------- Rewriting parameter file ----------*/
                   12356:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   12357:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   12358:   strcat(rfileres,".");    /* */
                   12359:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   12360:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   12361:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   12362:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   12363:     fflush(ficlog);
                   12364:     goto end;
                   12365:   }
                   12366:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  12367: 
1.278     brouard  12368:                                      
1.126     brouard  12369:   /* Reads comments: lines beginning with '#' */
                   12370:   numlinepar=0;
1.277     brouard  12371:   /* Is it a BOM UTF-8 Windows file? */
                   12372:   /* First parameter line */
1.197     brouard  12373:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  12374:     noffset=0;
                   12375:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   12376:     {
                   12377:       noffset=noffset+3;
                   12378:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   12379:     }
1.302     brouard  12380: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   12381:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
1.277     brouard  12382:     {
                   12383:       noffset=noffset+2;
                   12384:       printf("# File is an UTF16BE BOM file\n");
                   12385:     }
                   12386:     else if( line[0] == 0 && line[1] == 0)
                   12387:     {
                   12388:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   12389:        noffset=noffset+4;
                   12390:        printf("# File is an UTF16BE BOM file\n");
                   12391:       }
                   12392:     } else{
                   12393:       ;/*printf(" Not a BOM file\n");*/
                   12394:     }
                   12395:   
1.197     brouard  12396:     /* If line starts with a # it is a comment */
1.277     brouard  12397:     if (line[noffset] == '#') {
1.197     brouard  12398:       numlinepar++;
                   12399:       fputs(line,stdout);
                   12400:       fputs(line,ficparo);
1.278     brouard  12401:       fputs(line,ficres);
1.197     brouard  12402:       fputs(line,ficlog);
                   12403:       continue;
                   12404:     }else
                   12405:       break;
                   12406:   }
                   12407:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   12408:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   12409:     if (num_filled != 5) {
                   12410:       printf("Should be 5 parameters\n");
1.283     brouard  12411:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  12412:     }
1.126     brouard  12413:     numlinepar++;
1.197     brouard  12414:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  12415:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   12416:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   12417:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  12418:   }
                   12419:   /* Second parameter line */
                   12420:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  12421:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   12422:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  12423:     if (line[0] == '#') {
                   12424:       numlinepar++;
1.283     brouard  12425:       printf("%s",line);
                   12426:       fprintf(ficres,"%s",line);
                   12427:       fprintf(ficparo,"%s",line);
                   12428:       fprintf(ficlog,"%s",line);
1.197     brouard  12429:       continue;
                   12430:     }else
                   12431:       break;
                   12432:   }
1.223     brouard  12433:   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", \
                   12434:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   12435:     if (num_filled != 11) {
                   12436:       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  12437:       printf("but line=%s\n",line);
1.283     brouard  12438:       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");
                   12439:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  12440:     }
1.286     brouard  12441:     if( lastpass > maxwav){
                   12442:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   12443:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   12444:       fflush(ficlog);
                   12445:       goto end;
                   12446:     }
                   12447:       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  12448:     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  12449:     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  12450:     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  12451:   }
1.203     brouard  12452:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  12453:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  12454:   /* Third parameter line */
                   12455:   while(fgets(line, MAXLINE, ficpar)) {
                   12456:     /* If line starts with a # it is a comment */
                   12457:     if (line[0] == '#') {
                   12458:       numlinepar++;
1.283     brouard  12459:       printf("%s",line);
                   12460:       fprintf(ficres,"%s",line);
                   12461:       fprintf(ficparo,"%s",line);
                   12462:       fprintf(ficlog,"%s",line);
1.197     brouard  12463:       continue;
                   12464:     }else
                   12465:       break;
                   12466:   }
1.201     brouard  12467:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
1.279     brouard  12468:     if (num_filled != 1){
1.302     brouard  12469:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   12470:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
1.197     brouard  12471:       model[0]='\0';
                   12472:       goto end;
                   12473:     }
                   12474:     else{
                   12475:       if (model[0]=='+'){
                   12476:        for(i=1; i<=strlen(model);i++)
                   12477:          modeltemp[i-1]=model[i];
1.201     brouard  12478:        strcpy(model,modeltemp); 
1.197     brouard  12479:       }
                   12480:     }
1.338     brouard  12481:     /* printf(" model=1+age%s modeltemp= %s, model=1+age+%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  12482:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  12483:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   12484:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   12485:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  12486:   }
                   12487:   /* 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); */
                   12488:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   12489:   /* 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  12490:   /* 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); */
                   12491:   /* 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  12492:   fflush(ficlog);
1.190     brouard  12493:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   12494:   if(model[0]=='#'){
1.279     brouard  12495:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   12496:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   12497:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  12498:     if(mle != -1){
1.279     brouard  12499:       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  12500:       exit(1);
                   12501:     }
                   12502:   }
1.126     brouard  12503:   while((c=getc(ficpar))=='#' && c!= EOF){
                   12504:     ungetc(c,ficpar);
                   12505:     fgets(line, MAXLINE, ficpar);
                   12506:     numlinepar++;
1.195     brouard  12507:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   12508:       z[0]=line[1];
                   12509:     }
                   12510:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  12511:     fputs(line, stdout);
                   12512:     //puts(line);
1.126     brouard  12513:     fputs(line,ficparo);
                   12514:     fputs(line,ficlog);
                   12515:   }
                   12516:   ungetc(c,ficpar);
                   12517: 
                   12518:    
1.290     brouard  12519:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   12520:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   12521:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
                   12522:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /**< Time varying covariate (dummy and quantitative)*/
1.340   ! brouard  12523:   /* if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);  /\**< Might be better *\/ */
1.136     brouard  12524:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   12525:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   12526:      v1+v2*age+v2*v3 makes cptcovn = 3
                   12527:   */
                   12528:   if (strlen(model)>1) 
1.187     brouard  12529:     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  12530:   else
1.187     brouard  12531:     ncovmodel=2; /* Constant and age */
1.133     brouard  12532:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   12533:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  12534:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   12535:     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);
                   12536:     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);
                   12537:     fflush(stdout);
                   12538:     fclose (ficlog);
                   12539:     goto end;
                   12540:   }
1.126     brouard  12541:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   12542:   delti=delti3[1][1];
                   12543:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   12544:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  12545: /* We could also provide initial parameters values giving by simple logistic regression 
                   12546:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   12547:       /* for(i=1;i<nlstate;i++){ */
                   12548:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   12549:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   12550:       /* } */
1.126     brouard  12551:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  12552:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   12553:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  12554:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   12555:     fclose (ficparo);
                   12556:     fclose (ficlog);
                   12557:     goto end;
                   12558:     exit(0);
1.220     brouard  12559:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  12560:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  12561:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   12562:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  12563:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   12564:     matcov=matrix(1,npar,1,npar);
1.203     brouard  12565:     hess=matrix(1,npar,1,npar);
1.220     brouard  12566:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  12567:     /* Read guessed parameters */
1.126     brouard  12568:     /* Reads comments: lines beginning with '#' */
                   12569:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12570:       ungetc(c,ficpar);
                   12571:       fgets(line, MAXLINE, ficpar);
                   12572:       numlinepar++;
1.141     brouard  12573:       fputs(line,stdout);
1.126     brouard  12574:       fputs(line,ficparo);
                   12575:       fputs(line,ficlog);
                   12576:     }
                   12577:     ungetc(c,ficpar);
                   12578:     
                   12579:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  12580:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  12581:     for(i=1; i <=nlstate; i++){
1.234     brouard  12582:       j=0;
1.126     brouard  12583:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  12584:        if(jj==i) continue;
                   12585:        j++;
1.292     brouard  12586:        while((c=getc(ficpar))=='#' && c!= EOF){
                   12587:          ungetc(c,ficpar);
                   12588:          fgets(line, MAXLINE, ficpar);
                   12589:          numlinepar++;
                   12590:          fputs(line,stdout);
                   12591:          fputs(line,ficparo);
                   12592:          fputs(line,ficlog);
                   12593:        }
                   12594:        ungetc(c,ficpar);
1.234     brouard  12595:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   12596:        if ((i1 != i) || (j1 != jj)){
                   12597:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  12598: It might be a problem of design; if ncovcol and the model are correct\n \
                   12599: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  12600:          exit(1);
                   12601:        }
                   12602:        fprintf(ficparo,"%1d%1d",i1,j1);
                   12603:        if(mle==1)
                   12604:          printf("%1d%1d",i,jj);
                   12605:        fprintf(ficlog,"%1d%1d",i,jj);
                   12606:        for(k=1; k<=ncovmodel;k++){
                   12607:          fscanf(ficpar," %lf",&param[i][j][k]);
                   12608:          if(mle==1){
                   12609:            printf(" %lf",param[i][j][k]);
                   12610:            fprintf(ficlog," %lf",param[i][j][k]);
                   12611:          }
                   12612:          else
                   12613:            fprintf(ficlog," %lf",param[i][j][k]);
                   12614:          fprintf(ficparo," %lf",param[i][j][k]);
                   12615:        }
                   12616:        fscanf(ficpar,"\n");
                   12617:        numlinepar++;
                   12618:        if(mle==1)
                   12619:          printf("\n");
                   12620:        fprintf(ficlog,"\n");
                   12621:        fprintf(ficparo,"\n");
1.126     brouard  12622:       }
                   12623:     }  
                   12624:     fflush(ficlog);
1.234     brouard  12625:     
1.251     brouard  12626:     /* Reads parameters values */
1.126     brouard  12627:     p=param[1][1];
1.251     brouard  12628:     pstart=paramstart[1][1];
1.126     brouard  12629:     
                   12630:     /* Reads comments: lines beginning with '#' */
                   12631:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12632:       ungetc(c,ficpar);
                   12633:       fgets(line, MAXLINE, ficpar);
                   12634:       numlinepar++;
1.141     brouard  12635:       fputs(line,stdout);
1.126     brouard  12636:       fputs(line,ficparo);
                   12637:       fputs(line,ficlog);
                   12638:     }
                   12639:     ungetc(c,ficpar);
                   12640: 
                   12641:     for(i=1; i <=nlstate; i++){
                   12642:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  12643:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   12644:        if ( (i1-i) * (j1-j) != 0){
                   12645:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   12646:          exit(1);
                   12647:        }
                   12648:        printf("%1d%1d",i,j);
                   12649:        fprintf(ficparo,"%1d%1d",i1,j1);
                   12650:        fprintf(ficlog,"%1d%1d",i1,j1);
                   12651:        for(k=1; k<=ncovmodel;k++){
                   12652:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   12653:          printf(" %le",delti3[i][j][k]);
                   12654:          fprintf(ficparo," %le",delti3[i][j][k]);
                   12655:          fprintf(ficlog," %le",delti3[i][j][k]);
                   12656:        }
                   12657:        fscanf(ficpar,"\n");
                   12658:        numlinepar++;
                   12659:        printf("\n");
                   12660:        fprintf(ficparo,"\n");
                   12661:        fprintf(ficlog,"\n");
1.126     brouard  12662:       }
                   12663:     }
                   12664:     fflush(ficlog);
1.234     brouard  12665:     
1.145     brouard  12666:     /* Reads covariance matrix */
1.126     brouard  12667:     delti=delti3[1][1];
1.220     brouard  12668:                
                   12669:                
1.126     brouard  12670:     /* 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  12671:                
1.126     brouard  12672:     /* Reads comments: lines beginning with '#' */
                   12673:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12674:       ungetc(c,ficpar);
                   12675:       fgets(line, MAXLINE, ficpar);
                   12676:       numlinepar++;
1.141     brouard  12677:       fputs(line,stdout);
1.126     brouard  12678:       fputs(line,ficparo);
                   12679:       fputs(line,ficlog);
                   12680:     }
                   12681:     ungetc(c,ficpar);
1.220     brouard  12682:                
1.126     brouard  12683:     matcov=matrix(1,npar,1,npar);
1.203     brouard  12684:     hess=matrix(1,npar,1,npar);
1.131     brouard  12685:     for(i=1; i <=npar; i++)
                   12686:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  12687:                
1.194     brouard  12688:     /* Scans npar lines */
1.126     brouard  12689:     for(i=1; i <=npar; i++){
1.226     brouard  12690:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  12691:       if(count != 3){
1.226     brouard  12692:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  12693: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   12694: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  12695:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  12696: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   12697: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  12698:        exit(1);
1.220     brouard  12699:       }else{
1.226     brouard  12700:        if(mle==1)
                   12701:          printf("%1d%1d%d",i1,j1,jk);
                   12702:       }
                   12703:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   12704:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  12705:       for(j=1; j <=i; j++){
1.226     brouard  12706:        fscanf(ficpar," %le",&matcov[i][j]);
                   12707:        if(mle==1){
                   12708:          printf(" %.5le",matcov[i][j]);
                   12709:        }
                   12710:        fprintf(ficlog," %.5le",matcov[i][j]);
                   12711:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  12712:       }
                   12713:       fscanf(ficpar,"\n");
                   12714:       numlinepar++;
                   12715:       if(mle==1)
1.220     brouard  12716:                                printf("\n");
1.126     brouard  12717:       fprintf(ficlog,"\n");
                   12718:       fprintf(ficparo,"\n");
                   12719:     }
1.194     brouard  12720:     /* End of read covariance matrix npar lines */
1.126     brouard  12721:     for(i=1; i <=npar; i++)
                   12722:       for(j=i+1;j<=npar;j++)
1.226     brouard  12723:        matcov[i][j]=matcov[j][i];
1.126     brouard  12724:     
                   12725:     if(mle==1)
                   12726:       printf("\n");
                   12727:     fprintf(ficlog,"\n");
                   12728:     
                   12729:     fflush(ficlog);
                   12730:     
                   12731:   }    /* End of mle != -3 */
1.218     brouard  12732:   
1.186     brouard  12733:   /*  Main data
                   12734:    */
1.290     brouard  12735:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   12736:   /* num=lvector(1,n); */
                   12737:   /* moisnais=vector(1,n); */
                   12738:   /* annais=vector(1,n); */
                   12739:   /* moisdc=vector(1,n); */
                   12740:   /* andc=vector(1,n); */
                   12741:   /* weight=vector(1,n); */
                   12742:   /* agedc=vector(1,n); */
                   12743:   /* cod=ivector(1,n); */
                   12744:   /* for(i=1;i<=n;i++){ */
                   12745:   num=lvector(firstobs,lastobs);
                   12746:   moisnais=vector(firstobs,lastobs);
                   12747:   annais=vector(firstobs,lastobs);
                   12748:   moisdc=vector(firstobs,lastobs);
                   12749:   andc=vector(firstobs,lastobs);
                   12750:   weight=vector(firstobs,lastobs);
                   12751:   agedc=vector(firstobs,lastobs);
                   12752:   cod=ivector(firstobs,lastobs);
                   12753:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  12754:     num[i]=0;
                   12755:     moisnais[i]=0;
                   12756:     annais[i]=0;
                   12757:     moisdc[i]=0;
                   12758:     andc[i]=0;
                   12759:     agedc[i]=0;
                   12760:     cod[i]=0;
                   12761:     weight[i]=1.0; /* Equal weights, 1 by default */
                   12762:   }
1.290     brouard  12763:   mint=matrix(1,maxwav,firstobs,lastobs);
                   12764:   anint=matrix(1,maxwav,firstobs,lastobs);
1.325     brouard  12765:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */
1.336     brouard  12766:   /* printf("BUG ncovmodel=%d NCOVMAX=%d 2**ncovmodel=%f BUG\n",ncovmodel,NCOVMAX,pow(2,ncovmodel)); */
1.126     brouard  12767:   tab=ivector(1,NCOVMAX);
1.144     brouard  12768:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  12769:   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  12770: 
1.136     brouard  12771:   /* Reads data from file datafile */
                   12772:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   12773:     goto end;
                   12774: 
                   12775:   /* Calculation of the number of parameters from char model */
1.234     brouard  12776:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  12777:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   12778:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   12779:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   12780:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  12781:   */
                   12782:   
                   12783:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   12784:   TvarsDind=ivector(1,NCOVMAX); /*  */
1.330     brouard  12785:   TnsdVar=ivector(1,NCOVMAX); /*  */
1.335     brouard  12786:     /* for(i=1; i<=NCOVMAX;i++) TnsdVar[i]=3; */
1.234     brouard  12787:   TvarsD=ivector(1,NCOVMAX); /*  */
                   12788:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   12789:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  12790:   TvarF=ivector(1,NCOVMAX); /*  */
                   12791:   TvarFind=ivector(1,NCOVMAX); /*  */
                   12792:   TvarV=ivector(1,NCOVMAX); /*  */
                   12793:   TvarVind=ivector(1,NCOVMAX); /*  */
                   12794:   TvarA=ivector(1,NCOVMAX); /*  */
                   12795:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  12796:   TvarFD=ivector(1,NCOVMAX); /*  */
                   12797:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   12798:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   12799:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   12800:   TvarVD=ivector(1,NCOVMAX); /*  */
                   12801:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   12802:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   12803:   TvarVQind=ivector(1,NCOVMAX); /*  */
1.339     brouard  12804:   TvarVV=ivector(1,NCOVMAX); /*  */
                   12805:   TvarVVind=ivector(1,NCOVMAX); /*  */
1.231     brouard  12806: 
1.230     brouard  12807:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  12808:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  12809:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   12810:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   12811:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.137     brouard  12812:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   12813:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   12814:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   12815:   */
                   12816:   /* For model-covariate k tells which data-covariate to use but
                   12817:     because this model-covariate is a construction we invent a new column
                   12818:     ncovcol + k1
                   12819:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   12820:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  12821:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   12822:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  12823:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   12824:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  12825:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  12826:   */
1.145     brouard  12827:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   12828:   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  12829:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   12830:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.330     brouard  12831:   Tvardk=imatrix(1,NCOVMAX,1,2);
1.145     brouard  12832:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  12833:                         4 covariates (3 plus signs)
                   12834:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
1.328     brouard  12835:                           */  
                   12836:   for(i=1;i<NCOVMAX;i++)
                   12837:     Tage[i]=0;
1.230     brouard  12838:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  12839:                                * individual dummy, fixed or varying:
                   12840:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   12841:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  12842:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   12843:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   12844:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   12845:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   12846:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  12847:                                * individual quantitative, fixed or varying:
                   12848:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   12849:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   12850:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.186     brouard  12851: /* Main decodemodel */
                   12852: 
1.187     brouard  12853: 
1.223     brouard  12854:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  12855:     goto end;
                   12856: 
1.137     brouard  12857:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   12858:     nbwarn++;
                   12859:     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); 
                   12860:     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); 
                   12861:   }
1.136     brouard  12862:     /*  if(mle==1){*/
1.137     brouard  12863:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   12864:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  12865:   }
                   12866: 
                   12867:     /*-calculation of age at interview from date of interview and age at death -*/
                   12868:   agev=matrix(1,maxwav,1,imx);
                   12869: 
                   12870:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   12871:     goto end;
                   12872: 
1.126     brouard  12873: 
1.136     brouard  12874:   agegomp=(int)agemin;
1.290     brouard  12875:   free_vector(moisnais,firstobs,lastobs);
                   12876:   free_vector(annais,firstobs,lastobs);
1.126     brouard  12877:   /* free_matrix(mint,1,maxwav,1,n);
                   12878:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  12879:   /* free_vector(moisdc,1,n); */
                   12880:   /* free_vector(andc,1,n); */
1.145     brouard  12881:   /* */
                   12882:   
1.126     brouard  12883:   wav=ivector(1,imx);
1.214     brouard  12884:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   12885:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   12886:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   12887:   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.*/
                   12888:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   12889:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  12890:    
                   12891:   /* Concatenates waves */
1.214     brouard  12892:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   12893:      Death is a valid wave (if date is known).
                   12894:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   12895:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   12896:      and mw[mi+1][i]. dh depends on stepm.
                   12897:   */
                   12898: 
1.126     brouard  12899:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  12900:   /* Concatenates waves */
1.145     brouard  12901:  
1.290     brouard  12902:   free_vector(moisdc,firstobs,lastobs);
                   12903:   free_vector(andc,firstobs,lastobs);
1.215     brouard  12904: 
1.126     brouard  12905:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   12906:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   12907:   ncodemax[1]=1;
1.145     brouard  12908:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  12909:   cptcoveff=0;
1.220     brouard  12910:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
1.335     brouard  12911:     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  12912:   }
                   12913:   
                   12914:   ncovcombmax=pow(2,cptcoveff);
1.338     brouard  12915:   invalidvarcomb=ivector(0, ncovcombmax); 
                   12916:   for(i=0;i<ncovcombmax;i++)
1.227     brouard  12917:     invalidvarcomb[i]=0;
                   12918:   
1.211     brouard  12919:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  12920:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  12921:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  12922:   
1.200     brouard  12923:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  12924:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  12925:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  12926:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   12927:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   12928:    * (currently 0 or 1) in the data.
                   12929:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   12930:    * corresponding modality (h,j).
                   12931:    */
                   12932: 
1.145     brouard  12933:   h=0;
                   12934:   /*if (cptcovn > 0) */
1.126     brouard  12935:   m=pow(2,cptcoveff);
                   12936:  
1.144     brouard  12937:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  12938:           * For k=4 covariates, h goes from 1 to m=2**k
                   12939:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   12940:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.329     brouard  12941:           *     h\k   1     2     3     4   *  h-1\k-1  4  3  2  1          
                   12942:           *______________________________   *______________________
                   12943:           *     1 i=1 1 i=1 1 i=1 1 i=1 1   *     0     0  0  0  0 
                   12944:           *     2     2     1     1     1   *     1     0  0  0  1 
                   12945:           *     3 i=2 1     2     1     1   *     2     0  0  1  0 
                   12946:           *     4     2     2     1     1   *     3     0  0  1  1 
                   12947:           *     5 i=3 1 i=2 1     2     1   *     4     0  1  0  0 
                   12948:           *     6     2     1     2     1   *     5     0  1  0  1 
                   12949:           *     7 i=4 1     2     2     1   *     6     0  1  1  0 
                   12950:           *     8     2     2     2     1   *     7     0  1  1  1 
                   12951:           *     9 i=5 1 i=3 1 i=2 1     2   *     8     1  0  0  0 
                   12952:           *    10     2     1     1     2   *     9     1  0  0  1 
                   12953:           *    11 i=6 1     2     1     2   *    10     1  0  1  0 
                   12954:           *    12     2     2     1     2   *    11     1  0  1  1 
                   12955:           *    13 i=7 1 i=4 1     2     2   *    12     1  1  0  0  
                   12956:           *    14     2     1     2     2   *    13     1  1  0  1 
                   12957:           *    15 i=8 1     2     2     2   *    14     1  1  1  0 
                   12958:           *    16     2     2     2     2   *    15     1  1  1  1          
                   12959:           */                                     
1.212     brouard  12960:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  12961:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   12962:      * and the value of each covariate?
                   12963:      * V1=1, V2=1, V3=2, V4=1 ?
                   12964:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   12965:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   12966:      * In order to get the real value in the data, we use nbcode
                   12967:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   12968:      * We are keeping this crazy system in order to be able (in the future?) 
                   12969:      * to have more than 2 values (0 or 1) for a covariate.
                   12970:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   12971:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   12972:      *              bbbbbbbb
                   12973:      *              76543210     
                   12974:      *   h-1        00000101 (6-1=5)
1.219     brouard  12975:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  12976:      *           &
                   12977:      *     1        00000001 (1)
1.219     brouard  12978:      *              00000000        = 1 & ((h-1) >> (k-1))
                   12979:      *          +1= 00000001 =1 
1.211     brouard  12980:      *
                   12981:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   12982:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   12983:      *    >>k'            11
                   12984:      *          &   00000001
                   12985:      *            = 00000001
                   12986:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   12987:      * Reverse h=6 and m=16?
                   12988:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   12989:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   12990:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   12991:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   12992:      * V3=decodtabm(14,3,2**4)=2
                   12993:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   12994:      *(h-1) >> (j-1)    0011 =13 >> 2
                   12995:      *          &1 000000001
                   12996:      *           = 000000001
                   12997:      *         +1= 000000010 =2
                   12998:      *                  2211
                   12999:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   13000:      *                  V3=2
1.220     brouard  13001:                 * codtabm and decodtabm are identical
1.211     brouard  13002:      */
                   13003: 
1.145     brouard  13004: 
                   13005:  free_ivector(Ndum,-1,NCOVMAX);
                   13006: 
                   13007: 
1.126     brouard  13008:     
1.186     brouard  13009:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  13010:   strcpy(optionfilegnuplot,optionfilefiname);
                   13011:   if(mle==-3)
1.201     brouard  13012:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  13013:   strcat(optionfilegnuplot,".gp");
                   13014: 
                   13015:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   13016:     printf("Problem with file %s",optionfilegnuplot);
                   13017:   }
                   13018:   else{
1.204     brouard  13019:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  13020:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  13021:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   13022:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  13023:   }
                   13024:   /*  fclose(ficgp);*/
1.186     brouard  13025: 
                   13026: 
                   13027:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  13028: 
                   13029:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   13030:   if(mle==-3)
1.201     brouard  13031:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  13032:   strcat(optionfilehtm,".htm");
                   13033:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  13034:     printf("Problem with %s \n",optionfilehtm);
                   13035:     exit(0);
1.126     brouard  13036:   }
                   13037: 
                   13038:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   13039:   strcat(optionfilehtmcov,"-cov.htm");
                   13040:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   13041:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   13042:   }
                   13043:   else{
                   13044:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   13045: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  13046: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  13047:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   13048:   }
                   13049: 
1.335     brouard  13050:   fprintf(fichtm,"<html><head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n\
                   13051: <title>IMaCh %s</title></head>\n\
                   13052:  <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n\
                   13053: <font size=\"3\">Sponsored by Copyright (C)  2002-2015 <a href=http://www.ined.fr>INED</a>\
                   13054: -EUROREVES-Institut de longévité-2013-2022-Japan Society for the Promotion of Sciences 日本学術振興会 \
                   13055: (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - \
                   13056: <a href=https://software.intel.com/en-us>Intel Software 2015-2018</a></font><br> \n", optionfilehtm);
                   13057:   
                   13058:   fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  13059: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  13060: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.337     brouard  13061: 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  13062: \n\
                   13063: <hr  size=\"2\" color=\"#EC5E5E\">\
                   13064:  <ul><li><h4>Parameter files</h4>\n\
                   13065:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   13066:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   13067:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   13068:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   13069:  - Date and time at start: %s</ul>\n",\
1.335     brouard  13070:          version,fullversion,optionfilehtm,optionfilehtm,title,datafile,datafile,firstpass,lastpass,stepm, weightopt, model, \
1.126     brouard  13071:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   13072:          fileres,fileres,\
                   13073:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   13074:   fflush(fichtm);
                   13075: 
                   13076:   strcpy(pathr,path);
                   13077:   strcat(pathr,optionfilefiname);
1.184     brouard  13078: #ifdef WIN32
                   13079:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   13080: #else
1.126     brouard  13081:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  13082: #endif
                   13083:          
1.126     brouard  13084:   
1.220     brouard  13085:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   13086:                 and for any valid combination of covariates
1.126     brouard  13087:      and prints on file fileres'p'. */
1.251     brouard  13088:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  13089:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  13090: 
                   13091:   fprintf(fichtm,"\n");
1.286     brouard  13092:   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  13093:          ftol, stepm);
                   13094:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   13095:   ncurrv=1;
                   13096:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   13097:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   13098:   ncurrv=i;
                   13099:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  13100:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  13101:   ncurrv=i;
                   13102:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  13103:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  13104:   ncurrv=i;
                   13105:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   13106:   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", \
                   13107:           nlstate, ndeath, maxwav, mle, weightopt);
                   13108: 
                   13109:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   13110: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   13111: 
                   13112:   
1.317     brouard  13113:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Number of (used) observations=%d <br>\n\
1.126     brouard  13114: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   13115: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  13116:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  13117:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  13118:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   13119:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   13120:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   13121:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  13122: 
1.126     brouard  13123:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   13124:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   13125:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   13126: 
                   13127:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  13128:   /* For mortality only */
1.126     brouard  13129:   if (mle==-3){
1.136     brouard  13130:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  13131:     for(i=1;i<=NDIM;i++)
                   13132:       for(j=1;j<=NDIM;j++)
                   13133:        ximort[i][j]=0.;
1.186     brouard  13134:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  13135:     cens=ivector(firstobs,lastobs);
                   13136:     ageexmed=vector(firstobs,lastobs);
                   13137:     agecens=vector(firstobs,lastobs);
                   13138:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  13139:                
1.126     brouard  13140:     for (i=1; i<=imx; i++){
                   13141:       dcwave[i]=-1;
                   13142:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  13143:        if (s[m][i]>nlstate) {
                   13144:          dcwave[i]=m;
                   13145:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   13146:          break;
                   13147:        }
1.126     brouard  13148:     }
1.226     brouard  13149:     
1.126     brouard  13150:     for (i=1; i<=imx; i++) {
                   13151:       if (wav[i]>0){
1.226     brouard  13152:        ageexmed[i]=agev[mw[1][i]][i];
                   13153:        j=wav[i];
                   13154:        agecens[i]=1.; 
                   13155:        
                   13156:        if (ageexmed[i]> 1 && wav[i] > 0){
                   13157:          agecens[i]=agev[mw[j][i]][i];
                   13158:          cens[i]= 1;
                   13159:        }else if (ageexmed[i]< 1) 
                   13160:          cens[i]= -1;
                   13161:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   13162:          cens[i]=0 ;
1.126     brouard  13163:       }
                   13164:       else cens[i]=-1;
                   13165:     }
                   13166:     
                   13167:     for (i=1;i<=NDIM;i++) {
                   13168:       for (j=1;j<=NDIM;j++)
1.226     brouard  13169:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  13170:     }
                   13171:     
1.302     brouard  13172:     p[1]=0.0268; p[NDIM]=0.083;
                   13173:     /* printf("%lf %lf", p[1], p[2]); */
1.126     brouard  13174:     
                   13175:     
1.136     brouard  13176: #ifdef GSL
                   13177:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  13178: #else
1.126     brouard  13179:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  13180: #endif
1.201     brouard  13181:     strcpy(filerespow,"POW-MORT_"); 
                   13182:     strcat(filerespow,fileresu);
1.126     brouard  13183:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   13184:       printf("Problem with resultfile: %s\n", filerespow);
                   13185:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   13186:     }
1.136     brouard  13187: #ifdef GSL
                   13188:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  13189: #else
1.126     brouard  13190:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  13191: #endif
1.126     brouard  13192:     /*  for (i=1;i<=nlstate;i++)
                   13193:        for(j=1;j<=nlstate+ndeath;j++)
                   13194:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   13195:     */
                   13196:     fprintf(ficrespow,"\n");
1.136     brouard  13197: #ifdef GSL
                   13198:     /* gsl starts here */ 
                   13199:     T = gsl_multimin_fminimizer_nmsimplex;
                   13200:     gsl_multimin_fminimizer *sfm = NULL;
                   13201:     gsl_vector *ss, *x;
                   13202:     gsl_multimin_function minex_func;
                   13203: 
                   13204:     /* Initial vertex size vector */
                   13205:     ss = gsl_vector_alloc (NDIM);
                   13206:     
                   13207:     if (ss == NULL){
                   13208:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   13209:     }
                   13210:     /* Set all step sizes to 1 */
                   13211:     gsl_vector_set_all (ss, 0.001);
                   13212: 
                   13213:     /* Starting point */
1.126     brouard  13214:     
1.136     brouard  13215:     x = gsl_vector_alloc (NDIM);
                   13216:     
                   13217:     if (x == NULL){
                   13218:       gsl_vector_free(ss);
                   13219:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   13220:     }
                   13221:   
                   13222:     /* Initialize method and iterate */
                   13223:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  13224:     /*     gsl_vector_set(x, 0, 0.0268); */
                   13225:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  13226:     gsl_vector_set(x, 0, p[1]);
                   13227:     gsl_vector_set(x, 1, p[2]);
                   13228: 
                   13229:     minex_func.f = &gompertz_f;
                   13230:     minex_func.n = NDIM;
                   13231:     minex_func.params = (void *)&p; /* ??? */
                   13232:     
                   13233:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   13234:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   13235:     
                   13236:     printf("Iterations beginning .....\n\n");
                   13237:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   13238: 
                   13239:     iteri=0;
                   13240:     while (rval == GSL_CONTINUE){
                   13241:       iteri++;
                   13242:       status = gsl_multimin_fminimizer_iterate(sfm);
                   13243:       
                   13244:       if (status) printf("error: %s\n", gsl_strerror (status));
                   13245:       fflush(0);
                   13246:       
                   13247:       if (status) 
                   13248:         break;
                   13249:       
                   13250:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   13251:       ssval = gsl_multimin_fminimizer_size (sfm);
                   13252:       
                   13253:       if (rval == GSL_SUCCESS)
                   13254:         printf ("converged to a local maximum at\n");
                   13255:       
                   13256:       printf("%5d ", iteri);
                   13257:       for (it = 0; it < NDIM; it++){
                   13258:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   13259:       }
                   13260:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   13261:     }
                   13262:     
                   13263:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   13264:     
                   13265:     gsl_vector_free(x); /* initial values */
                   13266:     gsl_vector_free(ss); /* inital step size */
                   13267:     for (it=0; it<NDIM; it++){
                   13268:       p[it+1]=gsl_vector_get(sfm->x,it);
                   13269:       fprintf(ficrespow," %.12lf", p[it]);
                   13270:     }
                   13271:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   13272: #endif
                   13273: #ifdef POWELL
                   13274:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   13275: #endif  
1.126     brouard  13276:     fclose(ficrespow);
                   13277:     
1.203     brouard  13278:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  13279: 
                   13280:     for(i=1; i <=NDIM; i++)
                   13281:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  13282:                                matcov[i][j]=matcov[j][i];
1.126     brouard  13283:     
                   13284:     printf("\nCovariance matrix\n ");
1.203     brouard  13285:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  13286:     for(i=1; i <=NDIM; i++) {
                   13287:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  13288:                                printf("%f ",matcov[i][j]);
                   13289:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  13290:       }
1.203     brouard  13291:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  13292:     }
                   13293:     
                   13294:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  13295:     for (i=1;i<=NDIM;i++) {
1.126     brouard  13296:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  13297:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   13298:     }
1.302     brouard  13299:     lsurv=vector(agegomp,AGESUP);
                   13300:     lpop=vector(agegomp,AGESUP);
                   13301:     tpop=vector(agegomp,AGESUP);
1.126     brouard  13302:     lsurv[agegomp]=100000;
                   13303:     
                   13304:     for (k=agegomp;k<=AGESUP;k++) {
                   13305:       agemortsup=k;
                   13306:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   13307:     }
                   13308:     
                   13309:     for (k=agegomp;k<agemortsup;k++)
                   13310:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   13311:     
                   13312:     for (k=agegomp;k<agemortsup;k++){
                   13313:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   13314:       sumlpop=sumlpop+lpop[k];
                   13315:     }
                   13316:     
                   13317:     tpop[agegomp]=sumlpop;
                   13318:     for (k=agegomp;k<(agemortsup-3);k++){
                   13319:       /*  tpop[k+1]=2;*/
                   13320:       tpop[k+1]=tpop[k]-lpop[k];
                   13321:     }
                   13322:     
                   13323:     
                   13324:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   13325:     for (k=agegomp;k<(agemortsup-2);k++) 
                   13326:       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]);
                   13327:     
                   13328:     
                   13329:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  13330:                ageminpar=50;
                   13331:                agemaxpar=100;
1.194     brouard  13332:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   13333:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   13334: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13335: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   13336:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   13337: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13338: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  13339:     }else{
                   13340:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   13341:                        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  13342:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  13343:                }
1.201     brouard  13344:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  13345:                     stepm, weightopt,\
                   13346:                     model,imx,p,matcov,agemortsup);
                   13347:     
1.302     brouard  13348:     free_vector(lsurv,agegomp,AGESUP);
                   13349:     free_vector(lpop,agegomp,AGESUP);
                   13350:     free_vector(tpop,agegomp,AGESUP);
1.220     brouard  13351:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  13352:     free_ivector(dcwave,firstobs,lastobs);
                   13353:     free_vector(agecens,firstobs,lastobs);
                   13354:     free_vector(ageexmed,firstobs,lastobs);
                   13355:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  13356: #ifdef GSL
1.136     brouard  13357: #endif
1.186     brouard  13358:   } /* Endof if mle==-3 mortality only */
1.205     brouard  13359:   /* Standard  */
                   13360:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   13361:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   13362:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  13363:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  13364:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   13365:     for (k=1; k<=npar;k++)
                   13366:       printf(" %d %8.5f",k,p[k]);
                   13367:     printf("\n");
1.205     brouard  13368:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   13369:       /* mlikeli uses func not funcone */
1.247     brouard  13370:       /* for(i=1;i<nlstate;i++){ */
                   13371:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   13372:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   13373:       /* } */
1.205     brouard  13374:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   13375:     }
                   13376:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   13377:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   13378:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   13379:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   13380:     }
                   13381:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  13382:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   13383:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
1.335     brouard  13384:           /* exit(0); */
1.126     brouard  13385:     for (k=1; k<=npar;k++)
                   13386:       printf(" %d %8.5f",k,p[k]);
                   13387:     printf("\n");
                   13388:     
                   13389:     /*--------- results files --------------*/
1.283     brouard  13390:     /* 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  13391:     
                   13392:     
                   13393:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  13394:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); /* Printing model equation */
1.126     brouard  13395:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  13396: 
                   13397:     printf("#model=  1      +     age ");
                   13398:     fprintf(ficres,"#model=  1      +     age ");
                   13399:     fprintf(ficlog,"#model=  1      +     age ");
                   13400:     fprintf(fichtm,"\n<ul><li> model=1+age+%s\n \
                   13401: </ul>", model);
                   13402: 
                   13403:     fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">\n");
                   13404:     fprintf(fichtm, "<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   13405:     if(nagesqr==1){
                   13406:       printf("  + age*age  ");
                   13407:       fprintf(ficres,"  + age*age  ");
                   13408:       fprintf(ficlog,"  + age*age  ");
                   13409:       fprintf(fichtm, "<th>+ age*age</th>");
                   13410:     }
                   13411:     for(j=1;j <=ncovmodel-2;j++){
                   13412:       if(Typevar[j]==0) {
                   13413:        printf("  +      V%d  ",Tvar[j]);
                   13414:        fprintf(ficres,"  +      V%d  ",Tvar[j]);
                   13415:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   13416:        fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   13417:       }else if(Typevar[j]==1) {
                   13418:        printf("  +    V%d*age ",Tvar[j]);
                   13419:        fprintf(ficres,"  +    V%d*age ",Tvar[j]);
                   13420:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   13421:        fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   13422:       }else if(Typevar[j]==2) {
                   13423:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13424:        fprintf(ficres,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13425:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13426:        fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13427:       }
                   13428:     }
                   13429:     printf("\n");
                   13430:     fprintf(ficres,"\n");
                   13431:     fprintf(ficlog,"\n");
                   13432:     fprintf(fichtm, "</tr>");
                   13433:     fprintf(fichtm, "\n");
                   13434:     
                   13435:     
1.126     brouard  13436:     for(i=1,jk=1; i <=nlstate; i++){
                   13437:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  13438:        if (k != i) {
1.319     brouard  13439:          fprintf(fichtm, "<tr>");
1.225     brouard  13440:          printf("%d%d ",i,k);
                   13441:          fprintf(ficlog,"%d%d ",i,k);
                   13442:          fprintf(ficres,"%1d%1d ",i,k);
1.319     brouard  13443:          fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  13444:          for(j=1; j <=ncovmodel; j++){
                   13445:            printf("%12.7f ",p[jk]);
                   13446:            fprintf(ficlog,"%12.7f ",p[jk]);
                   13447:            fprintf(ficres,"%12.7f ",p[jk]);
1.319     brouard  13448:            fprintf(fichtm, "<td>%12.7f</td>",p[jk]);
1.225     brouard  13449:            jk++; 
                   13450:          }
                   13451:          printf("\n");
                   13452:          fprintf(ficlog,"\n");
                   13453:          fprintf(ficres,"\n");
1.319     brouard  13454:          fprintf(fichtm, "</tr>\n");
1.225     brouard  13455:        }
1.126     brouard  13456:       }
                   13457:     }
1.319     brouard  13458:     /* fprintf(fichtm,"</tr>\n"); */
                   13459:     fprintf(fichtm,"</table>\n");
                   13460:     fprintf(fichtm, "\n");
                   13461: 
1.203     brouard  13462:     if(mle != 0){
                   13463:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  13464:       ftolhess=ftol; /* Usually correct */
1.203     brouard  13465:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   13466:       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");
                   13467:       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  13468:       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  13469:       fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">");
                   13470:       fprintf(fichtm, "\n<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   13471:       if(nagesqr==1){
                   13472:        printf("  + age*age  ");
                   13473:        fprintf(ficres,"  + age*age  ");
                   13474:        fprintf(ficlog,"  + age*age  ");
                   13475:        fprintf(fichtm, "<th>+ age*age</th>");
                   13476:       }
                   13477:       for(j=1;j <=ncovmodel-2;j++){
                   13478:        if(Typevar[j]==0) {
                   13479:          printf("  +      V%d  ",Tvar[j]);
                   13480:          fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   13481:        }else if(Typevar[j]==1) {
                   13482:          printf("  +    V%d*age ",Tvar[j]);
                   13483:          fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   13484:        }else if(Typevar[j]==2) {
                   13485:          fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13486:        }
                   13487:       }
                   13488:       fprintf(fichtm, "</tr>\n");
                   13489:  
1.203     brouard  13490:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  13491:        for(k=1; k <=(nlstate+ndeath); k++){
                   13492:          if (k != i) {
1.319     brouard  13493:            fprintf(fichtm, "<tr valign=top>");
1.225     brouard  13494:            printf("%d%d ",i,k);
                   13495:            fprintf(ficlog,"%d%d ",i,k);
1.319     brouard  13496:            fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  13497:            for(j=1; j <=ncovmodel; j++){
1.319     brouard  13498:              wald=p[jk]/sqrt(matcov[jk][jk]);
1.324     brouard  13499:              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]));
                   13500:              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  13501:              if(fabs(wald) > 1.96){
1.321     brouard  13502:                fprintf(fichtm, "<td><b>%12.7f</b></br> (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
1.319     brouard  13503:              }else{
                   13504:                fprintf(fichtm, "<td>%12.7f (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
                   13505:              }
1.324     brouard  13506:              fprintf(fichtm,"W=%8.3f</br>",wald);
1.319     brouard  13507:              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  13508:              jk++; 
                   13509:            }
                   13510:            printf("\n");
                   13511:            fprintf(ficlog,"\n");
1.319     brouard  13512:            fprintf(fichtm, "</tr>\n");
1.225     brouard  13513:          }
                   13514:        }
1.193     brouard  13515:       }
1.203     brouard  13516:     } /* end of hesscov and Wald tests */
1.319     brouard  13517:     fprintf(fichtm,"</table>\n");
1.225     brouard  13518:     
1.203     brouard  13519:     /*  */
1.126     brouard  13520:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   13521:     printf("# Scales (for hessian or gradient estimation)\n");
                   13522:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   13523:     for(i=1,jk=1; i <=nlstate; i++){
                   13524:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  13525:        if (j!=i) {
                   13526:          fprintf(ficres,"%1d%1d",i,j);
                   13527:          printf("%1d%1d",i,j);
                   13528:          fprintf(ficlog,"%1d%1d",i,j);
                   13529:          for(k=1; k<=ncovmodel;k++){
                   13530:            printf(" %.5e",delti[jk]);
                   13531:            fprintf(ficlog," %.5e",delti[jk]);
                   13532:            fprintf(ficres," %.5e",delti[jk]);
                   13533:            jk++;
                   13534:          }
                   13535:          printf("\n");
                   13536:          fprintf(ficlog,"\n");
                   13537:          fprintf(ficres,"\n");
                   13538:        }
1.126     brouard  13539:       }
                   13540:     }
                   13541:     
                   13542:     fprintf(ficres,"# Covariance matrix \n# 121 Var(a12)\n# 122 Cov(b12,a12) Var(b12)\n#   ...\n# 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n");
1.203     brouard  13543:     if(mle >= 1) /* To big for the screen */
1.126     brouard  13544:       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");
                   13545:     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");
                   13546:     /* # 121 Var(a12)\n\ */
                   13547:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   13548:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   13549:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   13550:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   13551:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   13552:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   13553:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   13554:     
                   13555:     
                   13556:     /* Just to have a covariance matrix which will be more understandable
                   13557:        even is we still don't want to manage dictionary of variables
                   13558:     */
                   13559:     for(itimes=1;itimes<=2;itimes++){
                   13560:       jj=0;
                   13561:       for(i=1; i <=nlstate; i++){
1.225     brouard  13562:        for(j=1; j <=nlstate+ndeath; j++){
                   13563:          if(j==i) continue;
                   13564:          for(k=1; k<=ncovmodel;k++){
                   13565:            jj++;
                   13566:            ca[0]= k+'a'-1;ca[1]='\0';
                   13567:            if(itimes==1){
                   13568:              if(mle>=1)
                   13569:                printf("#%1d%1d%d",i,j,k);
                   13570:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   13571:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   13572:            }else{
                   13573:              if(mle>=1)
                   13574:                printf("%1d%1d%d",i,j,k);
                   13575:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   13576:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   13577:            }
                   13578:            ll=0;
                   13579:            for(li=1;li <=nlstate; li++){
                   13580:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   13581:                if(lj==li) continue;
                   13582:                for(lk=1;lk<=ncovmodel;lk++){
                   13583:                  ll++;
                   13584:                  if(ll<=jj){
                   13585:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   13586:                    if(ll<jj){
                   13587:                      if(itimes==1){
                   13588:                        if(mle>=1)
                   13589:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13590:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13591:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13592:                      }else{
                   13593:                        if(mle>=1)
                   13594:                          printf(" %.5e",matcov[jj][ll]); 
                   13595:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   13596:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   13597:                      }
                   13598:                    }else{
                   13599:                      if(itimes==1){
                   13600:                        if(mle>=1)
                   13601:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   13602:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   13603:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   13604:                      }else{
                   13605:                        if(mle>=1)
                   13606:                          printf(" %.7e",matcov[jj][ll]); 
                   13607:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   13608:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   13609:                      }
                   13610:                    }
                   13611:                  }
                   13612:                } /* end lk */
                   13613:              } /* end lj */
                   13614:            } /* end li */
                   13615:            if(mle>=1)
                   13616:              printf("\n");
                   13617:            fprintf(ficlog,"\n");
                   13618:            fprintf(ficres,"\n");
                   13619:            numlinepar++;
                   13620:          } /* end k*/
                   13621:        } /*end j */
1.126     brouard  13622:       } /* end i */
                   13623:     } /* end itimes */
                   13624:     
                   13625:     fflush(ficlog);
                   13626:     fflush(ficres);
1.225     brouard  13627:     while(fgets(line, MAXLINE, ficpar)) {
                   13628:       /* If line starts with a # it is a comment */
                   13629:       if (line[0] == '#') {
                   13630:        numlinepar++;
                   13631:        fputs(line,stdout);
                   13632:        fputs(line,ficparo);
                   13633:        fputs(line,ficlog);
1.299     brouard  13634:        fputs(line,ficres);
1.225     brouard  13635:        continue;
                   13636:       }else
                   13637:        break;
                   13638:     }
                   13639:     
1.209     brouard  13640:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   13641:     /*   ungetc(c,ficpar); */
                   13642:     /*   fgets(line, MAXLINE, ficpar); */
                   13643:     /*   fputs(line,stdout); */
                   13644:     /*   fputs(line,ficparo); */
                   13645:     /* } */
                   13646:     /* ungetc(c,ficpar); */
1.126     brouard  13647:     
                   13648:     estepm=0;
1.209     brouard  13649:     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  13650:       
                   13651:       if (num_filled != 6) {
                   13652:        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);
                   13653:        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);
                   13654:        goto end;
                   13655:       }
                   13656:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   13657:     }
                   13658:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   13659:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   13660:     
1.209     brouard  13661:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  13662:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   13663:     if (fage <= 2) {
                   13664:       bage = ageminpar;
                   13665:       fage = agemaxpar;
                   13666:     }
                   13667:     
                   13668:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  13669:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   13670:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  13671:                
1.186     brouard  13672:     /* Other stuffs, more or less useful */    
1.254     brouard  13673:     while(fgets(line, MAXLINE, ficpar)) {
                   13674:       /* If line starts with a # it is a comment */
                   13675:       if (line[0] == '#') {
                   13676:        numlinepar++;
                   13677:        fputs(line,stdout);
                   13678:        fputs(line,ficparo);
                   13679:        fputs(line,ficlog);
1.299     brouard  13680:        fputs(line,ficres);
1.254     brouard  13681:        continue;
                   13682:       }else
                   13683:        break;
                   13684:     }
                   13685: 
                   13686:     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){
                   13687:       
                   13688:       if (num_filled != 7) {
                   13689:        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);
                   13690:        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);
                   13691:        goto end;
                   13692:       }
                   13693:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   13694:       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);
                   13695:       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);
                   13696:       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  13697:     }
1.254     brouard  13698: 
                   13699:     while(fgets(line, MAXLINE, ficpar)) {
                   13700:       /* If line starts with a # it is a comment */
                   13701:       if (line[0] == '#') {
                   13702:        numlinepar++;
                   13703:        fputs(line,stdout);
                   13704:        fputs(line,ficparo);
                   13705:        fputs(line,ficlog);
1.299     brouard  13706:        fputs(line,ficres);
1.254     brouard  13707:        continue;
                   13708:       }else
                   13709:        break;
1.126     brouard  13710:     }
                   13711:     
                   13712:     
                   13713:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   13714:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   13715:     
1.254     brouard  13716:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   13717:       if (num_filled != 1) {
                   13718:        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);
                   13719:        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);
                   13720:        goto end;
                   13721:       }
                   13722:       printf("pop_based=%d\n",popbased);
                   13723:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   13724:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   13725:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   13726:     }
                   13727:      
1.258     brouard  13728:     /* Results */
1.332     brouard  13729:     /* Value of covariate in each resultine will be compututed (if product) and sorted according to model rank */
                   13730:     /* It is precov[] because we need the varying age in order to compute the real cov[] of the model equation */  
                   13731:     precov=matrix(1,MAXRESULTLINESPONE,1,NCOVMAX+1);
1.307     brouard  13732:     endishere=0;
1.258     brouard  13733:     nresult=0;
1.308     brouard  13734:     parameterline=0;
1.258     brouard  13735:     do{
                   13736:       if(!fgets(line, MAXLINE, ficpar)){
                   13737:        endishere=1;
1.308     brouard  13738:        parameterline=15;
1.258     brouard  13739:       }else if (line[0] == '#') {
                   13740:        /* If line starts with a # it is a comment */
1.254     brouard  13741:        numlinepar++;
                   13742:        fputs(line,stdout);
                   13743:        fputs(line,ficparo);
                   13744:        fputs(line,ficlog);
1.299     brouard  13745:        fputs(line,ficres);
1.254     brouard  13746:        continue;
1.258     brouard  13747:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   13748:        parameterline=11;
1.296     brouard  13749:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  13750:        parameterline=12;
1.307     brouard  13751:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
1.258     brouard  13752:        parameterline=13;
1.307     brouard  13753:       }
1.258     brouard  13754:       else{
                   13755:        parameterline=14;
1.254     brouard  13756:       }
1.308     brouard  13757:       switch (parameterline){ /* =0 only if only comments */
1.258     brouard  13758:       case 11:
1.296     brouard  13759:        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)){
                   13760:                  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  13761:          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);
                   13762:          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);
                   13763:          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);
                   13764:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  13765:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   13766:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  13767:           prvforecast = 1;
                   13768:        } 
                   13769:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.313     brouard  13770:          printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   13771:          fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   13772:          fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  13773:           prvforecast = 2;
                   13774:        }
                   13775:        else {
                   13776:          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);
                   13777:          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);
                   13778:          goto end;
1.258     brouard  13779:        }
1.254     brouard  13780:        break;
1.258     brouard  13781:       case 12:
1.296     brouard  13782:        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)){
                   13783:           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);
                   13784:          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);
                   13785:          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);
                   13786:          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);
                   13787:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  13788:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   13789:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  13790:           prvbackcast = 1;
                   13791:        } 
                   13792:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.313     brouard  13793:          printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   13794:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   13795:          fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  13796:           prvbackcast = 2;
                   13797:        }
                   13798:        else {
                   13799:          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);
                   13800:          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);
                   13801:          goto end;
1.258     brouard  13802:        }
1.230     brouard  13803:        break;
1.258     brouard  13804:       case 13:
1.332     brouard  13805:        num_filled=sscanf(line,"result:%[^\n]\n",resultlineori);
1.307     brouard  13806:        nresult++; /* Sum of resultlines */
1.332     brouard  13807:        printf("Result %d: result:%s\n",nresult, resultlineori);
                   13808:        /* removefirstspace(&resultlineori); */
                   13809:        
                   13810:        if(strstr(resultlineori,"v") !=0){
                   13811:          printf("Error. 'v' must be in upper case 'V' result: %s ",resultlineori);
                   13812:          fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultlineori);fflush(ficlog);
                   13813:          return 1;
                   13814:        }
                   13815:        trimbb(resultline, resultlineori); /* Suppressing double blank in the resultline */
                   13816:        printf("Decoderesult resultline=\"%s\" resultlineori=\"%s\"\n", resultline, resultlineori);
1.318     brouard  13817:        if(nresult > MAXRESULTLINESPONE-1){
                   13818:          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);
                   13819:          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  13820:          goto end;
                   13821:        }
1.332     brouard  13822:        
1.310     brouard  13823:        if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.314     brouard  13824:          fprintf(ficparo,"result: %s\n",resultline);
                   13825:          fprintf(ficres,"result: %s\n",resultline);
                   13826:          fprintf(ficlog,"result: %s\n",resultline);
1.310     brouard  13827:        } else
                   13828:          goto end;
1.307     brouard  13829:        break;
                   13830:       case 14:
                   13831:        printf("Error: Unknown command '%s'\n",line);
                   13832:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
1.314     brouard  13833:        if(line[0] == ' ' || line[0] == '\n'){
                   13834:          printf("It should not be an empty line '%s'\n",line);
                   13835:          fprintf(ficlog,"It should not be an empty line '%s'\n",line);
                   13836:        }         
1.307     brouard  13837:        if(ncovmodel >=2 && nresult==0 ){
                   13838:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   13839:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  13840:        }
1.307     brouard  13841:        /* goto end; */
                   13842:        break;
1.308     brouard  13843:       case 15:
                   13844:        printf("End of resultlines.\n");
                   13845:        fprintf(ficlog,"End of resultlines.\n");
                   13846:        break;
                   13847:       default: /* parameterline =0 */
1.307     brouard  13848:        nresult=1;
                   13849:        decoderesult(".",nresult ); /* No covariate */
1.258     brouard  13850:       } /* End switch parameterline */
                   13851:     }while(endishere==0); /* End do */
1.126     brouard  13852:     
1.230     brouard  13853:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  13854:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  13855:     
                   13856:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  13857:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  13858:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  13859: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13860: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  13861:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  13862: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13863: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  13864:     }else{
1.270     brouard  13865:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  13866:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   13867:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   13868:       if(prvforecast==1){
                   13869:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   13870:         jprojd=jproj1;
                   13871:         mprojd=mproj1;
                   13872:         anprojd=anproj1;
                   13873:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   13874:         jprojf=jproj2;
                   13875:         mprojf=mproj2;
                   13876:         anprojf=anproj2;
                   13877:       } else if(prvforecast == 2){
                   13878:         dateprojd=dateintmean;
                   13879:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   13880:         dateprojf=dateintmean+yrfproj;
                   13881:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   13882:       }
                   13883:       if(prvbackcast==1){
                   13884:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   13885:         jbackd=jback1;
                   13886:         mbackd=mback1;
                   13887:         anbackd=anback1;
                   13888:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   13889:         jbackf=jback2;
                   13890:         mbackf=mback2;
                   13891:         anbackf=anback2;
                   13892:       } else if(prvbackcast == 2){
                   13893:         datebackd=dateintmean;
                   13894:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   13895:         datebackf=dateintmean-yrbproj;
                   13896:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   13897:       }
                   13898:       
                   13899:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);
1.220     brouard  13900:     }
                   13901:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  13902:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   13903:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  13904:                
1.225     brouard  13905:     /*------------ free_vector  -------------*/
                   13906:     /*  chdir(path); */
1.220     brouard  13907:                
1.215     brouard  13908:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   13909:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   13910:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   13911:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  13912:     free_lvector(num,firstobs,lastobs);
                   13913:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  13914:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   13915:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   13916:     fclose(ficparo);
                   13917:     fclose(ficres);
1.220     brouard  13918:                
                   13919:                
1.186     brouard  13920:     /* Other results (useful)*/
1.220     brouard  13921:                
                   13922:                
1.126     brouard  13923:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  13924:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   13925:     prlim=matrix(1,nlstate,1,nlstate);
1.332     brouard  13926:     /* Computes the prevalence limit for each combination k of the dummy covariates by calling prevalim(k) */
1.209     brouard  13927:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  13928:     fclose(ficrespl);
                   13929: 
                   13930:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  13931:     /*#include "hpijx.h"*/
1.332     brouard  13932:     /** 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?*/
                   13933:     /* calls hpxij with combination k */
1.180     brouard  13934:     hPijx(p, bage, fage);
1.145     brouard  13935:     fclose(ficrespij);
1.227     brouard  13936:     
1.220     brouard  13937:     /* ncovcombmax=  pow(2,cptcoveff); */
1.332     brouard  13938:     /*-------------- Variance of one-step probabilities for a combination ij or for nres ?---*/
1.145     brouard  13939:     k=1;
1.126     brouard  13940:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  13941:     
1.269     brouard  13942:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   13943:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   13944:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  13945:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  13946:        for(k=1;k<=ncovcombmax;k++)
                   13947:          probs[i][j][k]=0.;
1.269     brouard  13948:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   13949:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  13950:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  13951:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   13952:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  13953:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  13954:          for(k=1;k<=ncovcombmax;k++)
                   13955:            mobaverages[i][j][k]=0.;
1.219     brouard  13956:       mobaverage=mobaverages;
                   13957:       if (mobilav!=0) {
1.235     brouard  13958:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  13959:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  13960:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   13961:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   13962:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   13963:        }
1.269     brouard  13964:       } else if (mobilavproj !=0) {
1.235     brouard  13965:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  13966:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  13967:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   13968:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   13969:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   13970:        }
1.269     brouard  13971:       }else{
                   13972:        printf("Internal error moving average\n");
                   13973:        fflush(stdout);
                   13974:        exit(1);
1.219     brouard  13975:       }
                   13976:     }/* end if moving average */
1.227     brouard  13977:     
1.126     brouard  13978:     /*---------- Forecasting ------------------*/
1.296     brouard  13979:     if(prevfcast==1){ 
                   13980:       /*   /\*    if(stepm ==1){*\/ */
                   13981:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   13982:       /*This done previously after freqsummary.*/
                   13983:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   13984:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   13985:       
                   13986:       /* } else if (prvforecast==2){ */
                   13987:       /*   /\*    if(stepm ==1){*\/ */
                   13988:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   13989:       /* } */
                   13990:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   13991:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  13992:     }
1.269     brouard  13993: 
1.296     brouard  13994:     /* Prevbcasting */
                   13995:     if(prevbcast==1){
1.219     brouard  13996:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   13997:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   13998:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   13999: 
                   14000:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   14001: 
                   14002:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  14003: 
1.219     brouard  14004:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   14005:       fclose(ficresplb);
                   14006: 
1.222     brouard  14007:       hBijx(p, bage, fage, mobaverage);
                   14008:       fclose(ficrespijb);
1.219     brouard  14009: 
1.296     brouard  14010:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   14011:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   14012:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   14013:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   14014:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   14015:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   14016: 
                   14017:       
1.269     brouard  14018:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  14019: 
                   14020:       
1.269     brouard  14021:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  14022:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   14023:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   14024:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  14025:     }    /* end  Prevbcasting */
1.268     brouard  14026:  
1.186     brouard  14027:  
                   14028:     /* ------ Other prevalence ratios------------ */
1.126     brouard  14029: 
1.215     brouard  14030:     free_ivector(wav,1,imx);
                   14031:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   14032:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   14033:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  14034:                
                   14035:                
1.127     brouard  14036:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  14037:                
1.201     brouard  14038:     strcpy(filerese,"E_");
                   14039:     strcat(filerese,fileresu);
1.126     brouard  14040:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   14041:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   14042:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   14043:     }
1.208     brouard  14044:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   14045:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  14046: 
                   14047:     pstamp(ficreseij);
1.219     brouard  14048:                
1.235     brouard  14049:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   14050:     if (cptcovn < 1){i1=1;}
                   14051:     
                   14052:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   14053:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  14054:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  14055:        continue;
1.219     brouard  14056:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  14057:       printf("\n#****** ");
1.225     brouard  14058:       for(j=1;j<=cptcoveff;j++) {
1.332     brouard  14059:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   14060:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.235     brouard  14061:       }
                   14062:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.337     brouard  14063:        printf(" V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]); /* TvarsQ[j] gives the name of the jth quantitative (fixed or time v) */
                   14064:        fprintf(ficreseij,"V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]);
1.219     brouard  14065:       }
                   14066:       fprintf(ficreseij,"******\n");
1.235     brouard  14067:       printf("******\n");
1.219     brouard  14068:       
                   14069:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   14070:       oldm=oldms;savm=savms;
1.330     brouard  14071:       /* 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  14072:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  14073:       
1.219     brouard  14074:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  14075:     }
                   14076:     fclose(ficreseij);
1.208     brouard  14077:     printf("done evsij\n");fflush(stdout);
                   14078:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  14079: 
1.218     brouard  14080:                
1.227     brouard  14081:     /*---------- State-specific expectancies and variances ------------*/
1.336     brouard  14082:     /* Should be moved in a function */                
1.201     brouard  14083:     strcpy(filerest,"T_");
                   14084:     strcat(filerest,fileresu);
1.127     brouard  14085:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   14086:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   14087:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   14088:     }
1.208     brouard  14089:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   14090:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  14091:     strcpy(fileresstde,"STDE_");
                   14092:     strcat(fileresstde,fileresu);
1.126     brouard  14093:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  14094:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   14095:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  14096:     }
1.227     brouard  14097:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   14098:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  14099: 
1.201     brouard  14100:     strcpy(filerescve,"CVE_");
                   14101:     strcat(filerescve,fileresu);
1.126     brouard  14102:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  14103:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   14104:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  14105:     }
1.227     brouard  14106:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   14107:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  14108: 
1.201     brouard  14109:     strcpy(fileresv,"V_");
                   14110:     strcat(fileresv,fileresu);
1.126     brouard  14111:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   14112:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   14113:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   14114:     }
1.227     brouard  14115:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   14116:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  14117: 
1.235     brouard  14118:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   14119:     if (cptcovn < 1){i1=1;}
                   14120:     
1.334     brouard  14121:     for(nres=1; nres <= nresult; nres++) /* For each resultline, find the combination and output results according to the values of dummies and then quanti.  */
                   14122:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying. For each nres and each value at position k
                   14123:                          * we know Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline
                   14124:                          * Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline 
                   14125:                          * and Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
                   14126:       /* */
                   14127:       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  14128:        continue;
1.321     brouard  14129:       printf("\n# model %s \n#****** Result for:", model);
                   14130:       fprintf(ficrest,"\n# model %s \n#****** Result for:", model);
                   14131:       fprintf(ficlog,"\n# model %s \n#****** Result for:", model);
1.334     brouard  14132:       /* It might not be a good idea to mix dummies and quantitative */
                   14133:       /* 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 *\/ */
                   14134:       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 */
                   14135:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* Output by variables in the resultline *\/ */
                   14136:        /* Tvaraff[j] is the name of the dummy variable in position j in the equation model:
                   14137:         * Tvaraff[1]@9={4, 3, 0, 0, 0, 0, 0, 0, 0}, in model=V5+V4+V3+V4*V3+V5*age
                   14138:         * (V5 is quanti) V4 and V3 are dummies
                   14139:         * TnsdVar[4] is the position 1 and TnsdVar[3]=2 in codtabm(k,l)(V4  V3)=V4  V3
                   14140:         *                                                              l=1 l=2
                   14141:         *                                                           k=1  1   1   0   0
                   14142:         *                                                           k=2  2   1   1   0
                   14143:         *                                                           k=3 [1] [2]  0   1
                   14144:         *                                                           k=4  2   2   1   1
                   14145:         * If nres=1 result: V3=1 V4=0 then k=3 and outputs
                   14146:         * If nres=2 result: V4=1 V3=0 then k=2 and outputs
                   14147:         * nres=1 =>k=3 j=1 V4= nbcode[4][codtabm(3,1)=1)=0; j=2  V3= nbcode[3][codtabm(3,2)=2]=1
                   14148:         * nres=2 =>k=2 j=1 V4= nbcode[4][codtabm(2,1)=2)=1; j=2  V3= nbcode[3][codtabm(2,2)=1]=0
                   14149:         */
                   14150:        /* Tvresult[nres][j] Name of the variable at position j in this resultline */
                   14151:        /* Tresult[nres][j] Value of this variable at position j could be a float if quantitative  */
                   14152: /* We give up with the combinations!! */
                   14153:        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 */
                   14154: 
                   14155:        if(Dummy[modelresult[nres][j]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to j in resultline  */
1.337     brouard  14156:          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  */
                   14157:          fprintf(ficlog,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][j]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
                   14158:          fprintf(ficrest,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][j]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
1.334     brouard  14159:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   14160:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   14161:          }else{
                   14162:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   14163:          }
                   14164:          /* fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14165:          /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14166:        }else if(Dummy[modelresult[nres][j]]==1){ /* Quanti variable */
                   14167:          /* For each selected (single) quantitative value */
1.337     brouard  14168:          printf(" V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   14169:          fprintf(ficlog," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   14170:          fprintf(ficrest," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
1.334     brouard  14171:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   14172:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   14173:          }else{
                   14174:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   14175:          }
                   14176:        }else{
                   14177:          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 */
                   14178:          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 */
                   14179:          exit(1);
                   14180:        }
1.335     brouard  14181:       } /* End loop for each variable in the resultline */
1.334     brouard  14182:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   14183:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /\* Wrong j is not in the equation model *\/ */
                   14184:       /*       fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14185:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14186:       /* }      */
1.208     brouard  14187:       fprintf(ficrest,"******\n");
1.227     brouard  14188:       fprintf(ficlog,"******\n");
                   14189:       printf("******\n");
1.208     brouard  14190:       
                   14191:       fprintf(ficresstdeij,"\n#****** ");
                   14192:       fprintf(ficrescveij,"\n#****** ");
1.337     brouard  14193:       /* It could have been: for(j=1;j<=cptcoveff;j++) {printf("V=%d=%lg",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);} */
                   14194:       /* But it won't be sorted and depends on how the resultline is ordered */
1.225     brouard  14195:       for(j=1;j<=cptcoveff;j++) {
1.334     brouard  14196:        fprintf(ficresstdeij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   14197:        /* fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14198:        /* fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14199:       }
                   14200:       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  14201:        fprintf(ficresstdeij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
                   14202:        fprintf(ficrescveij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
1.235     brouard  14203:       }        
1.208     brouard  14204:       fprintf(ficresstdeij,"******\n");
                   14205:       fprintf(ficrescveij,"******\n");
                   14206:       
                   14207:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  14208:       /* pstamp(ficresvij); */
1.225     brouard  14209:       for(j=1;j<=cptcoveff;j++) 
1.335     brouard  14210:        fprintf(ficresvij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   14211:        /* fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[TnsdVar[Tvaraff[j]]])]); */
1.235     brouard  14212:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  14213:        /* fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]); /\* To solve *\/ */
1.337     brouard  14214:        fprintf(ficresvij," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /* Solved */
1.235     brouard  14215:       }        
1.208     brouard  14216:       fprintf(ficresvij,"******\n");
                   14217:       
                   14218:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   14219:       oldm=oldms;savm=savms;
1.235     brouard  14220:       printf(" cvevsij ");
                   14221:       fprintf(ficlog, " cvevsij ");
                   14222:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  14223:       printf(" end cvevsij \n ");
                   14224:       fprintf(ficlog, " end cvevsij \n ");
                   14225:       
                   14226:       /*
                   14227:        */
                   14228:       /* goto endfree; */
                   14229:       
                   14230:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   14231:       pstamp(ficrest);
                   14232:       
1.269     brouard  14233:       epj=vector(1,nlstate+1);
1.208     brouard  14234:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  14235:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   14236:        cptcod= 0; /* To be deleted */
                   14237:        printf("varevsij vpopbased=%d \n",vpopbased);
                   14238:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  14239:        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  14240:        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 ");
                   14241:        if(vpopbased==1)
                   14242:          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);
                   14243:        else
1.288     brouard  14244:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
1.335     brouard  14245:        fprintf(ficrest,"# Age popbased mobilav e.. (std) "); /* Adding covariate values? */
1.227     brouard  14246:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   14247:        fprintf(ficrest,"\n");
                   14248:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  14249:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   14250:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  14251:        for(age=bage; age <=fage ;age++){
1.235     brouard  14252:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  14253:          if (vpopbased==1) {
                   14254:            if(mobilav ==0){
                   14255:              for(i=1; i<=nlstate;i++)
                   14256:                prlim[i][i]=probs[(int)age][i][k];
                   14257:            }else{ /* mobilav */ 
                   14258:              for(i=1; i<=nlstate;i++)
                   14259:                prlim[i][i]=mobaverage[(int)age][i][k];
                   14260:            }
                   14261:          }
1.219     brouard  14262:          
1.227     brouard  14263:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   14264:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   14265:          /* printf(" age %4.0f ",age); */
                   14266:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   14267:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   14268:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   14269:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   14270:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   14271:            }
                   14272:            epj[nlstate+1] +=epj[j];
                   14273:          }
                   14274:          /* printf(" age %4.0f \n",age); */
1.219     brouard  14275:          
1.227     brouard  14276:          for(i=1, vepp=0.;i <=nlstate;i++)
                   14277:            for(j=1;j <=nlstate;j++)
                   14278:              vepp += vareij[i][j][(int)age];
                   14279:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   14280:          for(j=1;j <=nlstate;j++){
                   14281:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   14282:          }
                   14283:          fprintf(ficrest,"\n");
                   14284:        }
1.208     brouard  14285:       } /* End vpopbased */
1.269     brouard  14286:       free_vector(epj,1,nlstate+1);
1.208     brouard  14287:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   14288:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  14289:       printf("done selection\n");fflush(stdout);
                   14290:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  14291:       
1.335     brouard  14292:     } /* End k selection or end covariate selection for nres */
1.227     brouard  14293: 
                   14294:     printf("done State-specific expectancies\n");fflush(stdout);
                   14295:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   14296: 
1.335     brouard  14297:     /* variance-covariance of forward period prevalence */
1.269     brouard  14298:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  14299: 
1.227     brouard  14300:     
1.290     brouard  14301:     free_vector(weight,firstobs,lastobs);
1.330     brouard  14302:     free_imatrix(Tvardk,1,NCOVMAX,1,2);
1.227     brouard  14303:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  14304:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   14305:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   14306:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   14307:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  14308:     free_ivector(tab,1,NCOVMAX);
                   14309:     fclose(ficresstdeij);
                   14310:     fclose(ficrescveij);
                   14311:     fclose(ficresvij);
                   14312:     fclose(ficrest);
                   14313:     fclose(ficpar);
                   14314:     
                   14315:     
1.126     brouard  14316:     /*---------- End : free ----------------*/
1.219     brouard  14317:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  14318:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   14319:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  14320:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   14321:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  14322:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  14323:   /* endfree:*/
                   14324:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   14325:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   14326:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.290     brouard  14327:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs);
                   14328:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   14329:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   14330:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  14331:   free_matrix(matcov,1,npar,1,npar);
                   14332:   free_matrix(hess,1,npar,1,npar);
                   14333:   /*free_vector(delti,1,npar);*/
                   14334:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   14335:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  14336:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  14337:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   14338:   
                   14339:   free_ivector(ncodemax,1,NCOVMAX);
                   14340:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   14341:   free_ivector(Dummy,-1,NCOVMAX);
                   14342:   free_ivector(Fixed,-1,NCOVMAX);
1.238     brouard  14343:   free_ivector(DummyV,1,NCOVMAX);
                   14344:   free_ivector(FixedV,1,NCOVMAX);
1.227     brouard  14345:   free_ivector(Typevar,-1,NCOVMAX);
                   14346:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  14347:   free_ivector(TvarsQ,1,NCOVMAX);
                   14348:   free_ivector(TvarsQind,1,NCOVMAX);
                   14349:   free_ivector(TvarsD,1,NCOVMAX);
1.330     brouard  14350:   free_ivector(TnsdVar,1,NCOVMAX);
1.234     brouard  14351:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  14352:   free_ivector(TvarFD,1,NCOVMAX);
                   14353:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  14354:   free_ivector(TvarF,1,NCOVMAX);
                   14355:   free_ivector(TvarFind,1,NCOVMAX);
                   14356:   free_ivector(TvarV,1,NCOVMAX);
                   14357:   free_ivector(TvarVind,1,NCOVMAX);
                   14358:   free_ivector(TvarA,1,NCOVMAX);
                   14359:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  14360:   free_ivector(TvarFQ,1,NCOVMAX);
                   14361:   free_ivector(TvarFQind,1,NCOVMAX);
                   14362:   free_ivector(TvarVD,1,NCOVMAX);
                   14363:   free_ivector(TvarVDind,1,NCOVMAX);
                   14364:   free_ivector(TvarVQ,1,NCOVMAX);
                   14365:   free_ivector(TvarVQind,1,NCOVMAX);
1.339     brouard  14366:   free_ivector(TvarVV,1,NCOVMAX);
                   14367:   free_ivector(TvarVVind,1,NCOVMAX);
                   14368:   
1.230     brouard  14369:   free_ivector(Tvarsel,1,NCOVMAX);
                   14370:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  14371:   free_ivector(Tposprod,1,NCOVMAX);
                   14372:   free_ivector(Tprod,1,NCOVMAX);
                   14373:   free_ivector(Tvaraff,1,NCOVMAX);
1.338     brouard  14374:   free_ivector(invalidvarcomb,0,ncovcombmax);
1.227     brouard  14375:   free_ivector(Tage,1,NCOVMAX);
                   14376:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  14377:   free_ivector(TmodelInvind,1,NCOVMAX);
                   14378:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.332     brouard  14379: 
                   14380:   free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /* Could be elsewhere ?*/
                   14381: 
1.227     brouard  14382:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   14383:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  14384:   fflush(fichtm);
                   14385:   fflush(ficgp);
                   14386:   
1.227     brouard  14387:   
1.126     brouard  14388:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  14389:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   14390:     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  14391:   }else{
                   14392:     printf("End of Imach\n");
                   14393:     fprintf(ficlog,"End of Imach\n");
                   14394:   }
                   14395:   printf("See log file on %s\n",filelog);
                   14396:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  14397:   /*(void) gettimeofday(&end_time,&tzp);*/
                   14398:   rend_time = time(NULL);  
                   14399:   end_time = *localtime(&rend_time);
                   14400:   /* tml = *localtime(&end_time.tm_sec); */
                   14401:   strcpy(strtend,asctime(&end_time));
1.126     brouard  14402:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   14403:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  14404:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  14405:   
1.157     brouard  14406:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   14407:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   14408:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  14409:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   14410: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   14411:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   14412:   fclose(fichtm);
                   14413:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   14414:   fclose(fichtmcov);
                   14415:   fclose(ficgp);
                   14416:   fclose(ficlog);
                   14417:   /*------ End -----------*/
1.227     brouard  14418:   
1.281     brouard  14419: 
                   14420: /* Executes gnuplot */
1.227     brouard  14421:   
                   14422:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  14423: #ifdef WIN32
1.227     brouard  14424:   if (_chdir(pathcd) != 0)
                   14425:     printf("Can't move to directory %s!\n",path);
                   14426:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  14427: #else
1.227     brouard  14428:     if(chdir(pathcd) != 0)
                   14429:       printf("Can't move to directory %s!\n", path);
                   14430:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  14431: #endif 
1.126     brouard  14432:     printf("Current directory %s!\n",pathcd);
                   14433:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   14434:   sprintf(plotcmd,"gnuplot");
1.157     brouard  14435: #ifdef _WIN32
1.126     brouard  14436:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   14437: #endif
                   14438:   if(!stat(plotcmd,&info)){
1.158     brouard  14439:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  14440:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  14441:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  14442:     }else
                   14443:       strcpy(pplotcmd,plotcmd);
1.157     brouard  14444: #ifdef __unix
1.126     brouard  14445:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   14446:     if(!stat(plotcmd,&info)){
1.158     brouard  14447:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  14448:     }else
                   14449:       strcpy(pplotcmd,plotcmd);
                   14450: #endif
                   14451:   }else
                   14452:     strcpy(pplotcmd,plotcmd);
                   14453:   
                   14454:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  14455:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  14456:   strcpy(pplotcmd,plotcmd);
1.227     brouard  14457:   
1.126     brouard  14458:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  14459:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  14460:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  14461:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  14462:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  14463:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  14464:       strcpy(plotcmd,pplotcmd);
                   14465:     }
1.126     brouard  14466:   }
1.158     brouard  14467:   printf(" Successful, please wait...");
1.126     brouard  14468:   while (z[0] != 'q') {
                   14469:     /* chdir(path); */
1.154     brouard  14470:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  14471:     scanf("%s",z);
                   14472: /*     if (z[0] == 'c') system("./imach"); */
                   14473:     if (z[0] == 'e') {
1.158     brouard  14474: #ifdef __APPLE__
1.152     brouard  14475:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  14476: #elif __linux
                   14477:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  14478: #else
1.152     brouard  14479:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  14480: #endif
                   14481:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   14482:       system(pplotcmd);
1.126     brouard  14483:     }
                   14484:     else if (z[0] == 'g') system(plotcmd);
                   14485:     else if (z[0] == 'q') exit(0);
                   14486:   }
1.227     brouard  14487: end:
1.126     brouard  14488:   while (z[0] != 'q') {
1.195     brouard  14489:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  14490:     scanf("%s",z);
                   14491:   }
1.283     brouard  14492:   printf("End\n");
1.282     brouard  14493:   exit(0);
1.126     brouard  14494: }

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