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

1.337   ! brouard     1: /* $Id: imach.c,v 1.336 2022/08/31 09:52:36 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.337   ! brouard     4:   Revision 1.336  2022/08/31 09:52:36  brouard
        !             5:   *** empty log message ***
        !             6: 
1.336     brouard     7:   Revision 1.335  2022/08/31 08:23:16  brouard
                      8:   Summary: improvements...
                      9: 
1.335     brouard    10:   Revision 1.334  2022/08/25 09:08:41  brouard
                     11:   Summary: In progress for quantitative
                     12: 
1.334     brouard    13:   Revision 1.333  2022/08/21 09:10:30  brouard
                     14:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                     15:   reassigning covariates: my first idea was that people will always
                     16:   use the first covariate V1 into the model but in fact they are
                     17:   producing data with many covariates and can use an equation model
                     18:   with some of the covariate; it means that in a model V2+V3 instead
                     19:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                     20:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                     21:   the equation model is restricted to two variables only (V2, V3)
                     22:   and the combination for V2 should be codtabm(k,1) instead of
                     23:   (codtabm(k,2), and the code should be
                     24:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                     25:   made. All of these should be simplified once a day like we did in
                     26:   hpxij() for example by using precov[nres] which is computed in
                     27:   decoderesult for each nres of each resultline. Loop should be done
                     28:   on the equation model globally by distinguishing only product with
                     29:   age (which are changing with age) and no more on type of
                     30:   covariates, single dummies, single covariates.
                     31: 
1.333     brouard    32:   Revision 1.332  2022/08/21 09:06:25  brouard
                     33:   Summary: Version 0.99r33
                     34: 
                     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.332     brouard    53:   Revision 1.331  2022/08/07 05:40:09  brouard
                     54:   *** empty log message ***
                     55: 
1.331     brouard    56:   Revision 1.330  2022/08/06 07:18:25  brouard
                     57:   Summary: last 0.99r31
                     58: 
                     59:   *  imach.c (Module): Version of imach using partly decoderesult to rebuild xpxij function
                     60: 
1.330     brouard    61:   Revision 1.329  2022/08/03 17:29:54  brouard
                     62:   *  imach.c (Module): Many errors in graphs fixed with Vn*age covariates.
                     63: 
1.329     brouard    64:   Revision 1.328  2022/07/27 17:40:48  brouard
                     65:   Summary: valgrind bug fixed by initializing to zero DummyV as well as Tage
                     66: 
1.328     brouard    67:   Revision 1.327  2022/07/27 14:47:35  brouard
                     68:   Summary: Still a problem for one-step probabilities in case of quantitative variables
                     69: 
1.327     brouard    70:   Revision 1.326  2022/07/26 17:33:55  brouard
                     71:   Summary: some test with nres=1
                     72: 
1.326     brouard    73:   Revision 1.325  2022/07/25 14:27:23  brouard
                     74:   Summary: r30
                     75: 
                     76:   * imach.c (Module): Error cptcovn instead of nsd in bmij (was
                     77:   coredumped, revealed by Feiuno, thank you.
                     78: 
1.325     brouard    79:   Revision 1.324  2022/07/23 17:44:26  brouard
                     80:   *** empty log message ***
                     81: 
1.324     brouard    82:   Revision 1.323  2022/07/22 12:30:08  brouard
                     83:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                     84: 
1.323     brouard    85:   Revision 1.322  2022/07/22 12:27:48  brouard
                     86:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                     87: 
1.322     brouard    88:   Revision 1.321  2022/07/22 12:04:24  brouard
                     89:   Summary: r28
                     90: 
                     91:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                     92: 
1.321     brouard    93:   Revision 1.320  2022/06/02 05:10:11  brouard
                     94:   *** empty log message ***
                     95: 
1.320     brouard    96:   Revision 1.319  2022/06/02 04:45:11  brouard
                     97:   * imach.c (Module): Adding the Wald tests from the log to the main
                     98:   htm for better display of the maximum likelihood estimators.
                     99: 
1.319     brouard   100:   Revision 1.318  2022/05/24 08:10:59  brouard
                    101:   * imach.c (Module): Some attempts to find a bug of wrong estimates
                    102:   of confidencce intervals with product in the equation modelC
                    103: 
1.318     brouard   104:   Revision 1.317  2022/05/15 15:06:23  brouard
                    105:   * imach.c (Module):  Some minor improvements
                    106: 
1.317     brouard   107:   Revision 1.316  2022/05/11 15:11:31  brouard
                    108:   Summary: r27
                    109: 
1.316     brouard   110:   Revision 1.315  2022/05/11 15:06:32  brouard
                    111:   *** empty log message ***
                    112: 
1.315     brouard   113:   Revision 1.314  2022/04/13 17:43:09  brouard
                    114:   * imach.c (Module): Adding link to text data files
                    115: 
1.314     brouard   116:   Revision 1.313  2022/04/11 15:57:42  brouard
                    117:   * imach.c (Module): Error in rewriting the 'r' file with yearsfproj or yearsbproj fixed
                    118: 
1.313     brouard   119:   Revision 1.312  2022/04/05 21:24:39  brouard
                    120:   *** empty log message ***
                    121: 
1.312     brouard   122:   Revision 1.311  2022/04/05 21:03:51  brouard
                    123:   Summary: Fixed quantitative covariates
                    124: 
                    125:          Fixed covariates (dummy or quantitative)
                    126:        with missing values have never been allowed but are ERRORS and
                    127:        program quits. Standard deviations of fixed covariates were
                    128:        wrongly computed. Mean and standard deviations of time varying
                    129:        covariates are still not computed.
                    130: 
1.311     brouard   131:   Revision 1.310  2022/03/17 08:45:53  brouard
                    132:   Summary: 99r25
                    133: 
                    134:   Improving detection of errors: result lines should be compatible with
                    135:   the model.
                    136: 
1.310     brouard   137:   Revision 1.309  2021/05/20 12:39:14  brouard
                    138:   Summary: Version 0.99r24
                    139: 
1.309     brouard   140:   Revision 1.308  2021/03/31 13:11:57  brouard
                    141:   Summary: Version 0.99r23
                    142: 
                    143: 
                    144:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
                    145: 
1.308     brouard   146:   Revision 1.307  2021/03/08 18:11:32  brouard
                    147:   Summary: 0.99r22 fixed bug on result:
                    148: 
1.307     brouard   149:   Revision 1.306  2021/02/20 15:44:02  brouard
                    150:   Summary: Version 0.99r21
                    151: 
                    152:   * imach.c (Module): Fix bug on quitting after result lines!
                    153:   (Module): Version 0.99r21
                    154: 
1.306     brouard   155:   Revision 1.305  2021/02/20 15:28:30  brouard
                    156:   * imach.c (Module): Fix bug on quitting after result lines!
                    157: 
1.305     brouard   158:   Revision 1.304  2021/02/12 11:34:20  brouard
                    159:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
                    160: 
1.304     brouard   161:   Revision 1.303  2021/02/11 19:50:15  brouard
                    162:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
                    163: 
1.303     brouard   164:   Revision 1.302  2020/02/22 21:00:05  brouard
                    165:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
                    166:   and life table from the data without any state)
                    167: 
1.302     brouard   168:   Revision 1.301  2019/06/04 13:51:20  brouard
                    169:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                    170: 
1.301     brouard   171:   Revision 1.300  2019/05/22 19:09:45  brouard
                    172:   Summary: version 0.99r19 of May 2019
                    173: 
1.300     brouard   174:   Revision 1.299  2019/05/22 18:37:08  brouard
                    175:   Summary: Cleaned 0.99r19
                    176: 
1.299     brouard   177:   Revision 1.298  2019/05/22 18:19:56  brouard
                    178:   *** empty log message ***
                    179: 
1.298     brouard   180:   Revision 1.297  2019/05/22 17:56:10  brouard
                    181:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                    182: 
1.297     brouard   183:   Revision 1.296  2019/05/20 13:03:18  brouard
                    184:   Summary: Projection syntax simplified
                    185: 
                    186: 
                    187:   We can now start projections, forward or backward, from the mean date
                    188:   of inteviews up to or down to a number of years of projection:
                    189:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                    190:   or
                    191:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                    192:   or
                    193:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                    194:   or
                    195:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                    196: 
1.296     brouard   197:   Revision 1.295  2019/05/18 09:52:50  brouard
                    198:   Summary: doxygen tex bug
                    199: 
1.295     brouard   200:   Revision 1.294  2019/05/16 14:54:33  brouard
                    201:   Summary: There was some wrong lines added
                    202: 
1.294     brouard   203:   Revision 1.293  2019/05/09 15:17:34  brouard
                    204:   *** empty log message ***
                    205: 
1.293     brouard   206:   Revision 1.292  2019/05/09 14:17:20  brouard
                    207:   Summary: Some updates
                    208: 
1.292     brouard   209:   Revision 1.291  2019/05/09 13:44:18  brouard
                    210:   Summary: Before ncovmax
                    211: 
1.291     brouard   212:   Revision 1.290  2019/05/09 13:39:37  brouard
                    213:   Summary: 0.99r18 unlimited number of individuals
                    214: 
                    215:   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.
                    216: 
1.290     brouard   217:   Revision 1.289  2018/12/13 09:16:26  brouard
                    218:   Summary: Bug for young ages (<-30) will be in r17
                    219: 
1.289     brouard   220:   Revision 1.288  2018/05/02 20:58:27  brouard
                    221:   Summary: Some bugs fixed
                    222: 
1.288     brouard   223:   Revision 1.287  2018/05/01 17:57:25  brouard
                    224:   Summary: Bug fixed by providing frequencies only for non missing covariates
                    225: 
1.287     brouard   226:   Revision 1.286  2018/04/27 14:27:04  brouard
                    227:   Summary: some minor bugs
                    228: 
1.286     brouard   229:   Revision 1.285  2018/04/21 21:02:16  brouard
                    230:   Summary: Some bugs fixed, valgrind tested
                    231: 
1.285     brouard   232:   Revision 1.284  2018/04/20 05:22:13  brouard
                    233:   Summary: Computing mean and stdeviation of fixed quantitative variables
                    234: 
1.284     brouard   235:   Revision 1.283  2018/04/19 14:49:16  brouard
                    236:   Summary: Some minor bugs fixed
                    237: 
1.283     brouard   238:   Revision 1.282  2018/02/27 22:50:02  brouard
                    239:   *** empty log message ***
                    240: 
1.282     brouard   241:   Revision 1.281  2018/02/27 19:25:23  brouard
                    242:   Summary: Adding second argument for quitting
                    243: 
1.281     brouard   244:   Revision 1.280  2018/02/21 07:58:13  brouard
                    245:   Summary: 0.99r15
                    246: 
                    247:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                    248: 
1.280     brouard   249:   Revision 1.279  2017/07/20 13:35:01  brouard
                    250:   Summary: temporary working
                    251: 
1.279     brouard   252:   Revision 1.278  2017/07/19 14:09:02  brouard
                    253:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                    254: 
1.278     brouard   255:   Revision 1.277  2017/07/17 08:53:49  brouard
                    256:   Summary: BOM files can be read now
                    257: 
1.277     brouard   258:   Revision 1.276  2017/06/30 15:48:31  brouard
                    259:   Summary: Graphs improvements
                    260: 
1.276     brouard   261:   Revision 1.275  2017/06/30 13:39:33  brouard
                    262:   Summary: Saito's color
                    263: 
1.275     brouard   264:   Revision 1.274  2017/06/29 09:47:08  brouard
                    265:   Summary: Version 0.99r14
                    266: 
1.274     brouard   267:   Revision 1.273  2017/06/27 11:06:02  brouard
                    268:   Summary: More documentation on projections
                    269: 
1.273     brouard   270:   Revision 1.272  2017/06/27 10:22:40  brouard
                    271:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    272: 
1.272     brouard   273:   Revision 1.271  2017/06/27 10:17:50  brouard
                    274:   Summary: Some bug with rint
                    275: 
1.271     brouard   276:   Revision 1.270  2017/05/24 05:45:29  brouard
                    277:   *** empty log message ***
                    278: 
1.270     brouard   279:   Revision 1.269  2017/05/23 08:39:25  brouard
                    280:   Summary: Code into subroutine, cleanings
                    281: 
1.269     brouard   282:   Revision 1.268  2017/05/18 20:09:32  brouard
                    283:   Summary: backprojection and confidence intervals of backprevalence
                    284: 
1.268     brouard   285:   Revision 1.267  2017/05/13 10:25:05  brouard
                    286:   Summary: temporary save for backprojection
                    287: 
1.267     brouard   288:   Revision 1.266  2017/05/13 07:26:12  brouard
                    289:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    290: 
1.266     brouard   291:   Revision 1.265  2017/04/26 16:22:11  brouard
                    292:   Summary: imach 0.99r13 Some bugs fixed
                    293: 
1.265     brouard   294:   Revision 1.264  2017/04/26 06:01:29  brouard
                    295:   Summary: Labels in graphs
                    296: 
1.264     brouard   297:   Revision 1.263  2017/04/24 15:23:15  brouard
                    298:   Summary: to save
                    299: 
1.263     brouard   300:   Revision 1.262  2017/04/18 16:48:12  brouard
                    301:   *** empty log message ***
                    302: 
1.262     brouard   303:   Revision 1.261  2017/04/05 10:14:09  brouard
                    304:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    305: 
1.261     brouard   306:   Revision 1.260  2017/04/04 17:46:59  brouard
                    307:   Summary: Gnuplot indexations fixed (humm)
                    308: 
1.260     brouard   309:   Revision 1.259  2017/04/04 13:01:16  brouard
                    310:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    311: 
1.259     brouard   312:   Revision 1.258  2017/04/03 10:17:47  brouard
                    313:   Summary: Version 0.99r12
                    314: 
                    315:   Some cleanings, conformed with updated documentation.
                    316: 
1.258     brouard   317:   Revision 1.257  2017/03/29 16:53:30  brouard
                    318:   Summary: Temp
                    319: 
1.257     brouard   320:   Revision 1.256  2017/03/27 05:50:23  brouard
                    321:   Summary: Temporary
                    322: 
1.256     brouard   323:   Revision 1.255  2017/03/08 16:02:28  brouard
                    324:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    325: 
1.255     brouard   326:   Revision 1.254  2017/03/08 07:13:00  brouard
                    327:   Summary: Fixing data parameter line
                    328: 
1.254     brouard   329:   Revision 1.253  2016/12/15 11:59:41  brouard
                    330:   Summary: 0.99 in progress
                    331: 
1.253     brouard   332:   Revision 1.252  2016/09/15 21:15:37  brouard
                    333:   *** empty log message ***
                    334: 
1.252     brouard   335:   Revision 1.251  2016/09/15 15:01:13  brouard
                    336:   Summary: not working
                    337: 
1.251     brouard   338:   Revision 1.250  2016/09/08 16:07:27  brouard
                    339:   Summary: continue
                    340: 
1.250     brouard   341:   Revision 1.249  2016/09/07 17:14:18  brouard
                    342:   Summary: Starting values from frequencies
                    343: 
1.249     brouard   344:   Revision 1.248  2016/09/07 14:10:18  brouard
                    345:   *** empty log message ***
                    346: 
1.248     brouard   347:   Revision 1.247  2016/09/02 11:11:21  brouard
                    348:   *** empty log message ***
                    349: 
1.247     brouard   350:   Revision 1.246  2016/09/02 08:49:22  brouard
                    351:   *** empty log message ***
                    352: 
1.246     brouard   353:   Revision 1.245  2016/09/02 07:25:01  brouard
                    354:   *** empty log message ***
                    355: 
1.245     brouard   356:   Revision 1.244  2016/09/02 07:17:34  brouard
                    357:   *** empty log message ***
                    358: 
1.244     brouard   359:   Revision 1.243  2016/09/02 06:45:35  brouard
                    360:   *** empty log message ***
                    361: 
1.243     brouard   362:   Revision 1.242  2016/08/30 15:01:20  brouard
                    363:   Summary: Fixing a lots
                    364: 
1.242     brouard   365:   Revision 1.241  2016/08/29 17:17:25  brouard
                    366:   Summary: gnuplot problem in Back projection to fix
                    367: 
1.241     brouard   368:   Revision 1.240  2016/08/29 07:53:18  brouard
                    369:   Summary: Better
                    370: 
1.240     brouard   371:   Revision 1.239  2016/08/26 15:51:03  brouard
                    372:   Summary: Improvement in Powell output in order to copy and paste
                    373: 
                    374:   Author:
                    375: 
1.239     brouard   376:   Revision 1.238  2016/08/26 14:23:35  brouard
                    377:   Summary: Starting tests of 0.99
                    378: 
1.238     brouard   379:   Revision 1.237  2016/08/26 09:20:19  brouard
                    380:   Summary: to valgrind
                    381: 
1.237     brouard   382:   Revision 1.236  2016/08/25 10:50:18  brouard
                    383:   *** empty log message ***
                    384: 
1.236     brouard   385:   Revision 1.235  2016/08/25 06:59:23  brouard
                    386:   *** empty log message ***
                    387: 
1.235     brouard   388:   Revision 1.234  2016/08/23 16:51:20  brouard
                    389:   *** empty log message ***
                    390: 
1.234     brouard   391:   Revision 1.233  2016/08/23 07:40:50  brouard
                    392:   Summary: not working
                    393: 
1.233     brouard   394:   Revision 1.232  2016/08/22 14:20:21  brouard
                    395:   Summary: not working
                    396: 
1.232     brouard   397:   Revision 1.231  2016/08/22 07:17:15  brouard
                    398:   Summary: not working
                    399: 
1.231     brouard   400:   Revision 1.230  2016/08/22 06:55:53  brouard
                    401:   Summary: Not working
                    402: 
1.230     brouard   403:   Revision 1.229  2016/07/23 09:45:53  brouard
                    404:   Summary: Completing for func too
                    405: 
1.229     brouard   406:   Revision 1.228  2016/07/22 17:45:30  brouard
                    407:   Summary: Fixing some arrays, still debugging
                    408: 
1.227     brouard   409:   Revision 1.226  2016/07/12 18:42:34  brouard
                    410:   Summary: temp
                    411: 
1.226     brouard   412:   Revision 1.225  2016/07/12 08:40:03  brouard
                    413:   Summary: saving but not running
                    414: 
1.225     brouard   415:   Revision 1.224  2016/07/01 13:16:01  brouard
                    416:   Summary: Fixes
                    417: 
1.224     brouard   418:   Revision 1.223  2016/02/19 09:23:35  brouard
                    419:   Summary: temporary
                    420: 
1.223     brouard   421:   Revision 1.222  2016/02/17 08:14:50  brouard
                    422:   Summary: Probably last 0.98 stable version 0.98r6
                    423: 
1.222     brouard   424:   Revision 1.221  2016/02/15 23:35:36  brouard
                    425:   Summary: minor bug
                    426: 
1.220     brouard   427:   Revision 1.219  2016/02/15 00:48:12  brouard
                    428:   *** empty log message ***
                    429: 
1.219     brouard   430:   Revision 1.218  2016/02/12 11:29:23  brouard
                    431:   Summary: 0.99 Back projections
                    432: 
1.218     brouard   433:   Revision 1.217  2015/12/23 17:18:31  brouard
                    434:   Summary: Experimental backcast
                    435: 
1.217     brouard   436:   Revision 1.216  2015/12/18 17:32:11  brouard
                    437:   Summary: 0.98r4 Warning and status=-2
                    438: 
                    439:   Version 0.98r4 is now:
                    440:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    441:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    442:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    443: 
1.216     brouard   444:   Revision 1.215  2015/12/16 08:52:24  brouard
                    445:   Summary: 0.98r4 working
                    446: 
1.215     brouard   447:   Revision 1.214  2015/12/16 06:57:54  brouard
                    448:   Summary: temporary not working
                    449: 
1.214     brouard   450:   Revision 1.213  2015/12/11 18:22:17  brouard
                    451:   Summary: 0.98r4
                    452: 
1.213     brouard   453:   Revision 1.212  2015/11/21 12:47:24  brouard
                    454:   Summary: minor typo
                    455: 
1.212     brouard   456:   Revision 1.211  2015/11/21 12:41:11  brouard
                    457:   Summary: 0.98r3 with some graph of projected cross-sectional
                    458: 
                    459:   Author: Nicolas Brouard
                    460: 
1.211     brouard   461:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   462:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   463:   Summary: Adding ftolpl parameter
                    464:   Author: N Brouard
                    465: 
                    466:   We had difficulties to get smoothed confidence intervals. It was due
                    467:   to the period prevalence which wasn't computed accurately. The inner
                    468:   parameter ftolpl is now an outer parameter of the .imach parameter
                    469:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    470:   computation are long.
                    471: 
1.209     brouard   472:   Revision 1.208  2015/11/17 14:31:57  brouard
                    473:   Summary: temporary
                    474: 
1.208     brouard   475:   Revision 1.207  2015/10/27 17:36:57  brouard
                    476:   *** empty log message ***
                    477: 
1.207     brouard   478:   Revision 1.206  2015/10/24 07:14:11  brouard
                    479:   *** empty log message ***
                    480: 
1.206     brouard   481:   Revision 1.205  2015/10/23 15:50:53  brouard
                    482:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    483: 
1.205     brouard   484:   Revision 1.204  2015/10/01 16:20:26  brouard
                    485:   Summary: Some new graphs of contribution to likelihood
                    486: 
1.204     brouard   487:   Revision 1.203  2015/09/30 17:45:14  brouard
                    488:   Summary: looking at better estimation of the hessian
                    489: 
                    490:   Also a better criteria for convergence to the period prevalence And
                    491:   therefore adding the number of years needed to converge. (The
                    492:   prevalence in any alive state shold sum to one
                    493: 
1.203     brouard   494:   Revision 1.202  2015/09/22 19:45:16  brouard
                    495:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    496: 
1.202     brouard   497:   Revision 1.201  2015/09/15 17:34:58  brouard
                    498:   Summary: 0.98r0
                    499: 
                    500:   - Some new graphs like suvival functions
                    501:   - Some bugs fixed like model=1+age+V2.
                    502: 
1.201     brouard   503:   Revision 1.200  2015/09/09 16:53:55  brouard
                    504:   Summary: Big bug thanks to Flavia
                    505: 
                    506:   Even model=1+age+V2. did not work anymore
                    507: 
1.200     brouard   508:   Revision 1.199  2015/09/07 14:09:23  brouard
                    509:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    510: 
1.199     brouard   511:   Revision 1.198  2015/09/03 07:14:39  brouard
                    512:   Summary: 0.98q5 Flavia
                    513: 
1.198     brouard   514:   Revision 1.197  2015/09/01 18:24:39  brouard
                    515:   *** empty log message ***
                    516: 
1.197     brouard   517:   Revision 1.196  2015/08/18 23:17:52  brouard
                    518:   Summary: 0.98q5
                    519: 
1.196     brouard   520:   Revision 1.195  2015/08/18 16:28:39  brouard
                    521:   Summary: Adding a hack for testing purpose
                    522: 
                    523:   After reading the title, ftol and model lines, if the comment line has
                    524:   a q, starting with #q, the answer at the end of the run is quit. It
                    525:   permits to run test files in batch with ctest. The former workaround was
                    526:   $ echo q | imach foo.imach
                    527: 
1.195     brouard   528:   Revision 1.194  2015/08/18 13:32:00  brouard
                    529:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    530: 
1.194     brouard   531:   Revision 1.193  2015/08/04 07:17:42  brouard
                    532:   Summary: 0.98q4
                    533: 
1.193     brouard   534:   Revision 1.192  2015/07/16 16:49:02  brouard
                    535:   Summary: Fixing some outputs
                    536: 
1.192     brouard   537:   Revision 1.191  2015/07/14 10:00:33  brouard
                    538:   Summary: Some fixes
                    539: 
1.191     brouard   540:   Revision 1.190  2015/05/05 08:51:13  brouard
                    541:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    542: 
                    543:   Fix 1+age+.
                    544: 
1.190     brouard   545:   Revision 1.189  2015/04/30 14:45:16  brouard
                    546:   Summary: 0.98q2
                    547: 
1.189     brouard   548:   Revision 1.188  2015/04/30 08:27:53  brouard
                    549:   *** empty log message ***
                    550: 
1.188     brouard   551:   Revision 1.187  2015/04/29 09:11:15  brouard
                    552:   *** empty log message ***
                    553: 
1.187     brouard   554:   Revision 1.186  2015/04/23 12:01:52  brouard
                    555:   Summary: V1*age is working now, version 0.98q1
                    556: 
                    557:   Some codes had been disabled in order to simplify and Vn*age was
                    558:   working in the optimization phase, ie, giving correct MLE parameters,
                    559:   but, as usual, outputs were not correct and program core dumped.
                    560: 
1.186     brouard   561:   Revision 1.185  2015/03/11 13:26:42  brouard
                    562:   Summary: Inclusion of compile and links command line for Intel Compiler
                    563: 
1.185     brouard   564:   Revision 1.184  2015/03/11 11:52:39  brouard
                    565:   Summary: Back from Windows 8. Intel Compiler
                    566: 
1.184     brouard   567:   Revision 1.183  2015/03/10 20:34:32  brouard
                    568:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    569: 
                    570:   We use directest instead of original Powell test; probably no
                    571:   incidence on the results, but better justifications;
                    572:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    573:   wrong results.
                    574: 
1.183     brouard   575:   Revision 1.182  2015/02/12 08:19:57  brouard
                    576:   Summary: Trying to keep directest which seems simpler and more general
                    577:   Author: Nicolas Brouard
                    578: 
1.182     brouard   579:   Revision 1.181  2015/02/11 23:22:24  brouard
                    580:   Summary: Comments on Powell added
                    581: 
                    582:   Author:
                    583: 
1.181     brouard   584:   Revision 1.180  2015/02/11 17:33:45  brouard
                    585:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    586: 
1.180     brouard   587:   Revision 1.179  2015/01/04 09:57:06  brouard
                    588:   Summary: back to OS/X
                    589: 
1.179     brouard   590:   Revision 1.178  2015/01/04 09:35:48  brouard
                    591:   *** empty log message ***
                    592: 
1.178     brouard   593:   Revision 1.177  2015/01/03 18:40:56  brouard
                    594:   Summary: Still testing ilc32 on OSX
                    595: 
1.177     brouard   596:   Revision 1.176  2015/01/03 16:45:04  brouard
                    597:   *** empty log message ***
                    598: 
1.176     brouard   599:   Revision 1.175  2015/01/03 16:33:42  brouard
                    600:   *** empty log message ***
                    601: 
1.175     brouard   602:   Revision 1.174  2015/01/03 16:15:49  brouard
                    603:   Summary: Still in cross-compilation
                    604: 
1.174     brouard   605:   Revision 1.173  2015/01/03 12:06:26  brouard
                    606:   Summary: trying to detect cross-compilation
                    607: 
1.173     brouard   608:   Revision 1.172  2014/12/27 12:07:47  brouard
                    609:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    610: 
1.172     brouard   611:   Revision 1.171  2014/12/23 13:26:59  brouard
                    612:   Summary: Back from Visual C
                    613: 
                    614:   Still problem with utsname.h on Windows
                    615: 
1.171     brouard   616:   Revision 1.170  2014/12/23 11:17:12  brouard
                    617:   Summary: Cleaning some \%% back to %%
                    618: 
                    619:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    620: 
1.170     brouard   621:   Revision 1.169  2014/12/22 23:08:31  brouard
                    622:   Summary: 0.98p
                    623: 
                    624:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    625: 
1.169     brouard   626:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   627:   Summary: update
1.169     brouard   628: 
1.168     brouard   629:   Revision 1.167  2014/12/22 13:50:56  brouard
                    630:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    631: 
                    632:   Testing on Linux 64
                    633: 
1.167     brouard   634:   Revision 1.166  2014/12/22 11:40:47  brouard
                    635:   *** empty log message ***
                    636: 
1.166     brouard   637:   Revision 1.165  2014/12/16 11:20:36  brouard
                    638:   Summary: After compiling on Visual C
                    639: 
                    640:   * imach.c (Module): Merging 1.61 to 1.162
                    641: 
1.165     brouard   642:   Revision 1.164  2014/12/16 10:52:11  brouard
                    643:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    644: 
                    645:   * imach.c (Module): Merging 1.61 to 1.162
                    646: 
1.164     brouard   647:   Revision 1.163  2014/12/16 10:30:11  brouard
                    648:   * imach.c (Module): Merging 1.61 to 1.162
                    649: 
1.163     brouard   650:   Revision 1.162  2014/09/25 11:43:39  brouard
                    651:   Summary: temporary backup 0.99!
                    652: 
1.162     brouard   653:   Revision 1.1  2014/09/16 11:06:58  brouard
                    654:   Summary: With some code (wrong) for nlopt
                    655: 
                    656:   Author:
                    657: 
                    658:   Revision 1.161  2014/09/15 20:41:41  brouard
                    659:   Summary: Problem with macro SQR on Intel compiler
                    660: 
1.161     brouard   661:   Revision 1.160  2014/09/02 09:24:05  brouard
                    662:   *** empty log message ***
                    663: 
1.160     brouard   664:   Revision 1.159  2014/09/01 10:34:10  brouard
                    665:   Summary: WIN32
                    666:   Author: Brouard
                    667: 
1.159     brouard   668:   Revision 1.158  2014/08/27 17:11:51  brouard
                    669:   *** empty log message ***
                    670: 
1.158     brouard   671:   Revision 1.157  2014/08/27 16:26:55  brouard
                    672:   Summary: Preparing windows Visual studio version
                    673:   Author: Brouard
                    674: 
                    675:   In order to compile on Visual studio, time.h is now correct and time_t
                    676:   and tm struct should be used. difftime should be used but sometimes I
                    677:   just make the differences in raw time format (time(&now).
                    678:   Trying to suppress #ifdef LINUX
                    679:   Add xdg-open for __linux in order to open default browser.
                    680: 
1.157     brouard   681:   Revision 1.156  2014/08/25 20:10:10  brouard
                    682:   *** empty log message ***
                    683: 
1.156     brouard   684:   Revision 1.155  2014/08/25 18:32:34  brouard
                    685:   Summary: New compile, minor changes
                    686:   Author: Brouard
                    687: 
1.155     brouard   688:   Revision 1.154  2014/06/20 17:32:08  brouard
                    689:   Summary: Outputs now all graphs of convergence to period prevalence
                    690: 
1.154     brouard   691:   Revision 1.153  2014/06/20 16:45:46  brouard
                    692:   Summary: If 3 live state, convergence to period prevalence on same graph
                    693:   Author: Brouard
                    694: 
1.153     brouard   695:   Revision 1.152  2014/06/18 17:54:09  brouard
                    696:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    697: 
1.152     brouard   698:   Revision 1.151  2014/06/18 16:43:30  brouard
                    699:   *** empty log message ***
                    700: 
1.151     brouard   701:   Revision 1.150  2014/06/18 16:42:35  brouard
                    702:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    703:   Author: brouard
                    704: 
1.150     brouard   705:   Revision 1.149  2014/06/18 15:51:14  brouard
                    706:   Summary: Some fixes in parameter files errors
                    707:   Author: Nicolas Brouard
                    708: 
1.149     brouard   709:   Revision 1.148  2014/06/17 17:38:48  brouard
                    710:   Summary: Nothing new
                    711:   Author: Brouard
                    712: 
                    713:   Just a new packaging for OS/X version 0.98nS
                    714: 
1.148     brouard   715:   Revision 1.147  2014/06/16 10:33:11  brouard
                    716:   *** empty log message ***
                    717: 
1.147     brouard   718:   Revision 1.146  2014/06/16 10:20:28  brouard
                    719:   Summary: Merge
                    720:   Author: Brouard
                    721: 
                    722:   Merge, before building revised version.
                    723: 
1.146     brouard   724:   Revision 1.145  2014/06/10 21:23:15  brouard
                    725:   Summary: Debugging with valgrind
                    726:   Author: Nicolas Brouard
                    727: 
                    728:   Lot of changes in order to output the results with some covariates
                    729:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    730:   improve the code.
                    731:   No more memory valgrind error but a lot has to be done in order to
                    732:   continue the work of splitting the code into subroutines.
                    733:   Also, decodemodel has been improved. Tricode is still not
                    734:   optimal. nbcode should be improved. Documentation has been added in
                    735:   the source code.
                    736: 
1.144     brouard   737:   Revision 1.143  2014/01/26 09:45:38  brouard
                    738:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    739: 
                    740:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    741:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    742: 
1.143     brouard   743:   Revision 1.142  2014/01/26 03:57:36  brouard
                    744:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    745: 
                    746:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    747: 
1.142     brouard   748:   Revision 1.141  2014/01/26 02:42:01  brouard
                    749:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    750: 
1.141     brouard   751:   Revision 1.140  2011/09/02 10:37:54  brouard
                    752:   Summary: times.h is ok with mingw32 now.
                    753: 
1.140     brouard   754:   Revision 1.139  2010/06/14 07:50:17  brouard
                    755:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    756:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    757: 
1.139     brouard   758:   Revision 1.138  2010/04/30 18:19:40  brouard
                    759:   *** empty log message ***
                    760: 
1.138     brouard   761:   Revision 1.137  2010/04/29 18:11:38  brouard
                    762:   (Module): Checking covariates for more complex models
                    763:   than V1+V2. A lot of change to be done. Unstable.
                    764: 
1.137     brouard   765:   Revision 1.136  2010/04/26 20:30:53  brouard
                    766:   (Module): merging some libgsl code. Fixing computation
                    767:   of likelione (using inter/intrapolation if mle = 0) in order to
                    768:   get same likelihood as if mle=1.
                    769:   Some cleaning of code and comments added.
                    770: 
1.136     brouard   771:   Revision 1.135  2009/10/29 15:33:14  brouard
                    772:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    773: 
1.135     brouard   774:   Revision 1.134  2009/10/29 13:18:53  brouard
                    775:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    776: 
1.134     brouard   777:   Revision 1.133  2009/07/06 10:21:25  brouard
                    778:   just nforces
                    779: 
1.133     brouard   780:   Revision 1.132  2009/07/06 08:22:05  brouard
                    781:   Many tings
                    782: 
1.132     brouard   783:   Revision 1.131  2009/06/20 16:22:47  brouard
                    784:   Some dimensions resccaled
                    785: 
1.131     brouard   786:   Revision 1.130  2009/05/26 06:44:34  brouard
                    787:   (Module): Max Covariate is now set to 20 instead of 8. A
                    788:   lot of cleaning with variables initialized to 0. Trying to make
                    789:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    790: 
1.130     brouard   791:   Revision 1.129  2007/08/31 13:49:27  lievre
                    792:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    793: 
1.129     lievre    794:   Revision 1.128  2006/06/30 13:02:05  brouard
                    795:   (Module): Clarifications on computing e.j
                    796: 
1.128     brouard   797:   Revision 1.127  2006/04/28 18:11:50  brouard
                    798:   (Module): Yes the sum of survivors was wrong since
                    799:   imach-114 because nhstepm was no more computed in the age
                    800:   loop. Now we define nhstepma in the age loop.
                    801:   (Module): In order to speed up (in case of numerous covariates) we
                    802:   compute health expectancies (without variances) in a first step
                    803:   and then all the health expectancies with variances or standard
                    804:   deviation (needs data from the Hessian matrices) which slows the
                    805:   computation.
                    806:   In the future we should be able to stop the program is only health
                    807:   expectancies and graph are needed without standard deviations.
                    808: 
1.127     brouard   809:   Revision 1.126  2006/04/28 17:23:28  brouard
                    810:   (Module): Yes the sum of survivors was wrong since
                    811:   imach-114 because nhstepm was no more computed in the age
                    812:   loop. Now we define nhstepma in the age loop.
                    813:   Version 0.98h
                    814: 
1.126     brouard   815:   Revision 1.125  2006/04/04 15:20:31  lievre
                    816:   Errors in calculation of health expectancies. Age was not initialized.
                    817:   Forecasting file added.
                    818: 
                    819:   Revision 1.124  2006/03/22 17:13:53  lievre
                    820:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    821:   The log-likelihood is printed in the log file
                    822: 
                    823:   Revision 1.123  2006/03/20 10:52:43  brouard
                    824:   * imach.c (Module): <title> changed, corresponds to .htm file
                    825:   name. <head> headers where missing.
                    826: 
                    827:   * imach.c (Module): Weights can have a decimal point as for
                    828:   English (a comma might work with a correct LC_NUMERIC environment,
                    829:   otherwise the weight is truncated).
                    830:   Modification of warning when the covariates values are not 0 or
                    831:   1.
                    832:   Version 0.98g
                    833: 
                    834:   Revision 1.122  2006/03/20 09:45:41  brouard
                    835:   (Module): Weights can have a decimal point as for
                    836:   English (a comma might work with a correct LC_NUMERIC environment,
                    837:   otherwise the weight is truncated).
                    838:   Modification of warning when the covariates values are not 0 or
                    839:   1.
                    840:   Version 0.98g
                    841: 
                    842:   Revision 1.121  2006/03/16 17:45:01  lievre
                    843:   * imach.c (Module): Comments concerning covariates added
                    844: 
                    845:   * imach.c (Module): refinements in the computation of lli if
                    846:   status=-2 in order to have more reliable computation if stepm is
                    847:   not 1 month. Version 0.98f
                    848: 
                    849:   Revision 1.120  2006/03/16 15:10:38  lievre
                    850:   (Module): refinements in the computation of lli if
                    851:   status=-2 in order to have more reliable computation if stepm is
                    852:   not 1 month. Version 0.98f
                    853: 
                    854:   Revision 1.119  2006/03/15 17:42:26  brouard
                    855:   (Module): Bug if status = -2, the loglikelihood was
                    856:   computed as likelihood omitting the logarithm. Version O.98e
                    857: 
                    858:   Revision 1.118  2006/03/14 18:20:07  brouard
                    859:   (Module): varevsij Comments added explaining the second
                    860:   table of variances if popbased=1 .
                    861:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    862:   (Module): Function pstamp added
                    863:   (Module): Version 0.98d
                    864: 
                    865:   Revision 1.117  2006/03/14 17:16:22  brouard
                    866:   (Module): varevsij Comments added explaining the second
                    867:   table of variances if popbased=1 .
                    868:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    869:   (Module): Function pstamp added
                    870:   (Module): Version 0.98d
                    871: 
                    872:   Revision 1.116  2006/03/06 10:29:27  brouard
                    873:   (Module): Variance-covariance wrong links and
                    874:   varian-covariance of ej. is needed (Saito).
                    875: 
                    876:   Revision 1.115  2006/02/27 12:17:45  brouard
                    877:   (Module): One freematrix added in mlikeli! 0.98c
                    878: 
                    879:   Revision 1.114  2006/02/26 12:57:58  brouard
                    880:   (Module): Some improvements in processing parameter
                    881:   filename with strsep.
                    882: 
                    883:   Revision 1.113  2006/02/24 14:20:24  brouard
                    884:   (Module): Memory leaks checks with valgrind and:
                    885:   datafile was not closed, some imatrix were not freed and on matrix
                    886:   allocation too.
                    887: 
                    888:   Revision 1.112  2006/01/30 09:55:26  brouard
                    889:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    890: 
                    891:   Revision 1.111  2006/01/25 20:38:18  brouard
                    892:   (Module): Lots of cleaning and bugs added (Gompertz)
                    893:   (Module): Comments can be added in data file. Missing date values
                    894:   can be a simple dot '.'.
                    895: 
                    896:   Revision 1.110  2006/01/25 00:51:50  brouard
                    897:   (Module): Lots of cleaning and bugs added (Gompertz)
                    898: 
                    899:   Revision 1.109  2006/01/24 19:37:15  brouard
                    900:   (Module): Comments (lines starting with a #) are allowed in data.
                    901: 
                    902:   Revision 1.108  2006/01/19 18:05:42  lievre
                    903:   Gnuplot problem appeared...
                    904:   To be fixed
                    905: 
                    906:   Revision 1.107  2006/01/19 16:20:37  brouard
                    907:   Test existence of gnuplot in imach path
                    908: 
                    909:   Revision 1.106  2006/01/19 13:24:36  brouard
                    910:   Some cleaning and links added in html output
                    911: 
                    912:   Revision 1.105  2006/01/05 20:23:19  lievre
                    913:   *** empty log message ***
                    914: 
                    915:   Revision 1.104  2005/09/30 16:11:43  lievre
                    916:   (Module): sump fixed, loop imx fixed, and simplifications.
                    917:   (Module): If the status is missing at the last wave but we know
                    918:   that the person is alive, then we can code his/her status as -2
                    919:   (instead of missing=-1 in earlier versions) and his/her
                    920:   contributions to the likelihood is 1 - Prob of dying from last
                    921:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    922:   the healthy state at last known wave). Version is 0.98
                    923: 
                    924:   Revision 1.103  2005/09/30 15:54:49  lievre
                    925:   (Module): sump fixed, loop imx fixed, and simplifications.
                    926: 
                    927:   Revision 1.102  2004/09/15 17:31:30  brouard
                    928:   Add the possibility to read data file including tab characters.
                    929: 
                    930:   Revision 1.101  2004/09/15 10:38:38  brouard
                    931:   Fix on curr_time
                    932: 
                    933:   Revision 1.100  2004/07/12 18:29:06  brouard
                    934:   Add version for Mac OS X. Just define UNIX in Makefile
                    935: 
                    936:   Revision 1.99  2004/06/05 08:57:40  brouard
                    937:   *** empty log message ***
                    938: 
                    939:   Revision 1.98  2004/05/16 15:05:56  brouard
                    940:   New version 0.97 . First attempt to estimate force of mortality
                    941:   directly from the data i.e. without the need of knowing the health
                    942:   state at each age, but using a Gompertz model: log u =a + b*age .
                    943:   This is the basic analysis of mortality and should be done before any
                    944:   other analysis, in order to test if the mortality estimated from the
                    945:   cross-longitudinal survey is different from the mortality estimated
                    946:   from other sources like vital statistic data.
                    947: 
                    948:   The same imach parameter file can be used but the option for mle should be -3.
                    949: 
1.324     brouard   950:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   951:   former routines in order to include the new code within the former code.
                    952: 
                    953:   The output is very simple: only an estimate of the intercept and of
                    954:   the slope with 95% confident intervals.
                    955: 
                    956:   Current limitations:
                    957:   A) Even if you enter covariates, i.e. with the
                    958:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    959:   B) There is no computation of Life Expectancy nor Life Table.
                    960: 
                    961:   Revision 1.97  2004/02/20 13:25:42  lievre
                    962:   Version 0.96d. Population forecasting command line is (temporarily)
                    963:   suppressed.
                    964: 
                    965:   Revision 1.96  2003/07/15 15:38:55  brouard
                    966:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    967:   rewritten within the same printf. Workaround: many printfs.
                    968: 
                    969:   Revision 1.95  2003/07/08 07:54:34  brouard
                    970:   * imach.c (Repository):
                    971:   (Repository): Using imachwizard code to output a more meaningful covariance
                    972:   matrix (cov(a12,c31) instead of numbers.
                    973: 
                    974:   Revision 1.94  2003/06/27 13:00:02  brouard
                    975:   Just cleaning
                    976: 
                    977:   Revision 1.93  2003/06/25 16:33:55  brouard
                    978:   (Module): On windows (cygwin) function asctime_r doesn't
                    979:   exist so I changed back to asctime which exists.
                    980:   (Module): Version 0.96b
                    981: 
                    982:   Revision 1.92  2003/06/25 16:30:45  brouard
                    983:   (Module): On windows (cygwin) function asctime_r doesn't
                    984:   exist so I changed back to asctime which exists.
                    985: 
                    986:   Revision 1.91  2003/06/25 15:30:29  brouard
                    987:   * imach.c (Repository): Duplicated warning errors corrected.
                    988:   (Repository): Elapsed time after each iteration is now output. It
                    989:   helps to forecast when convergence will be reached. Elapsed time
                    990:   is stamped in powell.  We created a new html file for the graphs
                    991:   concerning matrix of covariance. It has extension -cov.htm.
                    992: 
                    993:   Revision 1.90  2003/06/24 12:34:15  brouard
                    994:   (Module): Some bugs corrected for windows. Also, when
                    995:   mle=-1 a template is output in file "or"mypar.txt with the design
                    996:   of the covariance matrix to be input.
                    997: 
                    998:   Revision 1.89  2003/06/24 12:30:52  brouard
                    999:   (Module): Some bugs corrected for windows. Also, when
                   1000:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1001:   of the covariance matrix to be input.
                   1002: 
                   1003:   Revision 1.88  2003/06/23 17:54:56  brouard
                   1004:   * 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.
                   1005: 
                   1006:   Revision 1.87  2003/06/18 12:26:01  brouard
                   1007:   Version 0.96
                   1008: 
                   1009:   Revision 1.86  2003/06/17 20:04:08  brouard
                   1010:   (Module): Change position of html and gnuplot routines and added
                   1011:   routine fileappend.
                   1012: 
                   1013:   Revision 1.85  2003/06/17 13:12:43  brouard
                   1014:   * imach.c (Repository): Check when date of death was earlier that
                   1015:   current date of interview. It may happen when the death was just
                   1016:   prior to the death. In this case, dh was negative and likelihood
                   1017:   was wrong (infinity). We still send an "Error" but patch by
                   1018:   assuming that the date of death was just one stepm after the
                   1019:   interview.
                   1020:   (Repository): Because some people have very long ID (first column)
                   1021:   we changed int to long in num[] and we added a new lvector for
                   1022:   memory allocation. But we also truncated to 8 characters (left
                   1023:   truncation)
                   1024:   (Repository): No more line truncation errors.
                   1025: 
                   1026:   Revision 1.84  2003/06/13 21:44:43  brouard
                   1027:   * imach.c (Repository): Replace "freqsummary" at a correct
                   1028:   place. It differs from routine "prevalence" which may be called
                   1029:   many times. Probs is memory consuming and must be used with
                   1030:   parcimony.
                   1031:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                   1032: 
                   1033:   Revision 1.83  2003/06/10 13:39:11  lievre
                   1034:   *** empty log message ***
                   1035: 
                   1036:   Revision 1.82  2003/06/05 15:57:20  brouard
                   1037:   Add log in  imach.c and  fullversion number is now printed.
                   1038: 
                   1039: */
                   1040: /*
                   1041:    Interpolated Markov Chain
                   1042: 
                   1043:   Short summary of the programme:
                   1044:   
1.227     brouard  1045:   This program computes Healthy Life Expectancies or State-specific
                   1046:   (if states aren't health statuses) Expectancies from
                   1047:   cross-longitudinal data. Cross-longitudinal data consist in: 
                   1048: 
                   1049:   -1- a first survey ("cross") where individuals from different ages
                   1050:   are interviewed on their health status or degree of disability (in
                   1051:   the case of a health survey which is our main interest)
                   1052: 
                   1053:   -2- at least a second wave of interviews ("longitudinal") which
                   1054:   measure each change (if any) in individual health status.  Health
                   1055:   expectancies are computed from the time spent in each health state
                   1056:   according to a model. More health states you consider, more time is
                   1057:   necessary to reach the Maximum Likelihood of the parameters involved
                   1058:   in the model.  The simplest model is the multinomial logistic model
                   1059:   where pij is the probability to be observed in state j at the second
                   1060:   wave conditional to be observed in state i at the first
                   1061:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                   1062:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                   1063:   have a more complex model than "constant and age", you should modify
                   1064:   the program where the markup *Covariates have to be included here
                   1065:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard  1066:   convergence.
                   1067: 
                   1068:   The advantage of this computer programme, compared to a simple
                   1069:   multinomial logistic model, is clear when the delay between waves is not
                   1070:   identical for each individual. Also, if a individual missed an
                   1071:   intermediate interview, the information is lost, but taken into
                   1072:   account using an interpolation or extrapolation.  
                   1073: 
                   1074:   hPijx is the probability to be observed in state i at age x+h
                   1075:   conditional to the observed state i at age x. The delay 'h' can be
                   1076:   split into an exact number (nh*stepm) of unobserved intermediate
                   1077:   states. This elementary transition (by month, quarter,
                   1078:   semester or year) is modelled as a multinomial logistic.  The hPx
                   1079:   matrix is simply the matrix product of nh*stepm elementary matrices
                   1080:   and the contribution of each individual to the likelihood is simply
                   1081:   hPijx.
                   1082: 
                   1083:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard  1084:   of the life expectancies. It also computes the period (stable) prevalence.
                   1085: 
                   1086: Back prevalence and projections:
1.227     brouard  1087: 
                   1088:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                   1089:    double agemaxpar, double ftolpl, int *ncvyearp, double
                   1090:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                   1091:    mobilavproj)
                   1092: 
                   1093:     Computes the back prevalence limit for any combination of
                   1094:     covariate values k at any age between ageminpar and agemaxpar and
                   1095:     returns it in **bprlim. In the loops,
                   1096: 
                   1097:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                   1098:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                   1099: 
                   1100:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard  1101:    Computes for any combination of covariates k and any age between bage and fage 
                   1102:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1103:                        oldm=oldms;savm=savms;
1.227     brouard  1104: 
1.267     brouard  1105:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard  1106:      Computes the transition matrix starting at age 'age' over
                   1107:      'nhstepm*hstepm*stepm' months (i.e. until
                   1108:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard  1109:      nhstepm*hstepm matrices. 
                   1110: 
                   1111:      Returns p3mat[i][j][h] after calling
                   1112:      p3mat[i][j][h]=matprod2(newm,
                   1113:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                   1114:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                   1115:      oldm);
1.226     brouard  1116: 
                   1117: Important routines
                   1118: 
                   1119: - func (or funcone), computes logit (pij) distinguishing
                   1120:   o fixed variables (single or product dummies or quantitative);
                   1121:   o varying variables by:
                   1122:    (1) wave (single, product dummies, quantitative), 
                   1123:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                   1124:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                   1125:        % varying dummy (not done) or quantitative (not done);
                   1126: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                   1127:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                   1128: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
1.325     brouard  1129:   o There are 2**cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
1.226     brouard  1130:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard  1131: 
1.226     brouard  1132: 
                   1133:   
1.324     brouard  1134:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                   1135:            Institut national d'études démographiques, Paris.
1.126     brouard  1136:   This software have been partly granted by Euro-REVES, a concerted action
                   1137:   from the European Union.
                   1138:   It is copyrighted identically to a GNU software product, ie programme and
                   1139:   software can be distributed freely for non commercial use. Latest version
                   1140:   can be accessed at http://euroreves.ined.fr/imach .
                   1141: 
                   1142:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                   1143:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                   1144:   
                   1145:   **********************************************************************/
                   1146: /*
                   1147:   main
                   1148:   read parameterfile
                   1149:   read datafile
                   1150:   concatwav
                   1151:   freqsummary
                   1152:   if (mle >= 1)
                   1153:     mlikeli
                   1154:   print results files
                   1155:   if mle==1 
                   1156:      computes hessian
                   1157:   read end of parameter file: agemin, agemax, bage, fage, estepm
                   1158:       begin-prev-date,...
                   1159:   open gnuplot file
                   1160:   open html file
1.145     brouard  1161:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1162:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1163:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1164:     freexexit2 possible for memory heap.
                   1165: 
                   1166:   h Pij x                         | pij_nom  ficrestpij
                   1167:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1168:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1169:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1170: 
                   1171:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1172:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1173:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1174:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1175:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1176: 
1.126     brouard  1177:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1178:   health expectancies
                   1179:   Variance-covariance of DFLE
                   1180:   prevalence()
                   1181:    movingaverage()
                   1182:   varevsij() 
                   1183:   if popbased==1 varevsij(,popbased)
                   1184:   total life expectancies
                   1185:   Variance of period (stable) prevalence
                   1186:  end
                   1187: */
                   1188: 
1.187     brouard  1189: /* #define DEBUG */
                   1190: /* #define DEBUGBRENT */
1.203     brouard  1191: /* #define DEBUGLINMIN */
                   1192: /* #define DEBUGHESS */
                   1193: #define DEBUGHESSIJ
1.224     brouard  1194: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1195: #define POWELL /* Instead of NLOPT */
1.224     brouard  1196: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1197: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1198: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.319     brouard  1199: /* #define FLATSUP  *//* Suppresses directions where likelihood is flat */
1.126     brouard  1200: 
                   1201: #include <math.h>
                   1202: #include <stdio.h>
                   1203: #include <stdlib.h>
                   1204: #include <string.h>
1.226     brouard  1205: #include <ctype.h>
1.159     brouard  1206: 
                   1207: #ifdef _WIN32
                   1208: #include <io.h>
1.172     brouard  1209: #include <windows.h>
                   1210: #include <tchar.h>
1.159     brouard  1211: #else
1.126     brouard  1212: #include <unistd.h>
1.159     brouard  1213: #endif
1.126     brouard  1214: 
                   1215: #include <limits.h>
                   1216: #include <sys/types.h>
1.171     brouard  1217: 
                   1218: #if defined(__GNUC__)
                   1219: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1220: #endif
                   1221: 
1.126     brouard  1222: #include <sys/stat.h>
                   1223: #include <errno.h>
1.159     brouard  1224: /* extern int errno; */
1.126     brouard  1225: 
1.157     brouard  1226: /* #ifdef LINUX */
                   1227: /* #include <time.h> */
                   1228: /* #include "timeval.h" */
                   1229: /* #else */
                   1230: /* #include <sys/time.h> */
                   1231: /* #endif */
                   1232: 
1.126     brouard  1233: #include <time.h>
                   1234: 
1.136     brouard  1235: #ifdef GSL
                   1236: #include <gsl/gsl_errno.h>
                   1237: #include <gsl/gsl_multimin.h>
                   1238: #endif
                   1239: 
1.167     brouard  1240: 
1.162     brouard  1241: #ifdef NLOPT
                   1242: #include <nlopt.h>
                   1243: typedef struct {
                   1244:   double (* function)(double [] );
                   1245: } myfunc_data ;
                   1246: #endif
                   1247: 
1.126     brouard  1248: /* #include <libintl.h> */
                   1249: /* #define _(String) gettext (String) */
                   1250: 
1.251     brouard  1251: #define MAXLINE 2048 /* Was 256 and 1024. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1252: 
                   1253: #define GNUPLOTPROGRAM "gnuplot"
                   1254: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
1.329     brouard  1255: #define FILENAMELENGTH 256
1.126     brouard  1256: 
                   1257: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1258: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1259: 
1.144     brouard  1260: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                   1261: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1262: 
                   1263: #define NINTERVMAX 8
1.144     brouard  1264: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1265: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.325     brouard  1266: #define NCOVMAX 30  /**< Maximum number of covariates used in the model, including generated covariates V1*V2 or V1*age */
1.197     brouard  1267: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1268: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1269: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1270: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1271: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1272: /* #define AGESUP 130 */
1.288     brouard  1273: /* #define AGESUP 150 */
                   1274: #define AGESUP 200
1.268     brouard  1275: #define AGEINF 0
1.218     brouard  1276: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1277: #define AGEBASE 40
1.194     brouard  1278: #define AGEOVERFLOW 1.e20
1.164     brouard  1279: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1280: #ifdef _WIN32
                   1281: #define DIRSEPARATOR '\\'
                   1282: #define CHARSEPARATOR "\\"
                   1283: #define ODIRSEPARATOR '/'
                   1284: #else
1.126     brouard  1285: #define DIRSEPARATOR '/'
                   1286: #define CHARSEPARATOR "/"
                   1287: #define ODIRSEPARATOR '\\'
                   1288: #endif
                   1289: 
1.337   ! brouard  1290: /* $Id: imach.c,v 1.336 2022/08/31 09:52:36 brouard Exp $ */
1.126     brouard  1291: /* $State: Exp $ */
1.196     brouard  1292: #include "version.h"
                   1293: char version[]=__IMACH_VERSION__;
1.337   ! brouard  1294: 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";
        !          1295: char fullversion[]="$Revision: 1.336 $ $Date: 2022/08/31 09:52:36 $"; 
1.126     brouard  1296: char strstart[80];
                   1297: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1298: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard  1299: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.330     brouard  1300: /* Number of covariates model (1)=V2+V1+ V3*age+V2*V4 */
                   1301: /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
1.335     brouard  1302: 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  1303: 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  1304: int cptcovs=0; /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   1305: int cptcovsnq=0; /**< cptcovsnq number of SIMPLE covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1306: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                   1307: int cptcovprodnoage=0; /**< Number of covariate products without age */   
1.335     brouard  1308: 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  1309: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1310: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.232     brouard  1311: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
1.234     brouard  1312: int nsd=0; /**< Total number of single dummy variables (output) */
                   1313: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1314: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1315: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1316: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1317: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1318: int cptcov=0; /* Working variable */
1.334     brouard  1319: int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs+1 declared globally ;*/
1.290     brouard  1320: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1321: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.302     brouard  1322: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
1.126     brouard  1323: int nlstate=2; /* Number of live states */
                   1324: int ndeath=1; /* Number of dead states */
1.130     brouard  1325: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.223     brouard  1326: int  nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable */ 
1.126     brouard  1327: int popbased=0;
                   1328: 
                   1329: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1330: int maxwav=0; /* Maxim number of waves */
                   1331: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1332: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1333: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard  1334:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1335: int mle=1, weightopt=0;
1.126     brouard  1336: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1337: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1338: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1339:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1340: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1341: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1342: 
1.130     brouard  1343: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1344: double **matprod2(); /* test */
1.126     brouard  1345: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1346: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1347: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1348: 
1.136     brouard  1349: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1350: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1351: FILE *ficlog, *ficrespow;
1.130     brouard  1352: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1353: double fretone; /* Only one call to likelihood */
1.130     brouard  1354: long ipmx=0; /* Number of contributions */
1.126     brouard  1355: double sw; /* Sum of weights */
                   1356: char filerespow[FILENAMELENGTH];
                   1357: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1358: FILE *ficresilk;
                   1359: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1360: FILE *ficresprobmorprev;
                   1361: FILE *fichtm, *fichtmcov; /* Html File */
                   1362: FILE *ficreseij;
                   1363: char filerese[FILENAMELENGTH];
                   1364: FILE *ficresstdeij;
                   1365: char fileresstde[FILENAMELENGTH];
                   1366: FILE *ficrescveij;
                   1367: char filerescve[FILENAMELENGTH];
                   1368: FILE  *ficresvij;
                   1369: char fileresv[FILENAMELENGTH];
1.269     brouard  1370: 
1.126     brouard  1371: char title[MAXLINE];
1.234     brouard  1372: char model[MAXLINE]; /**< The model line */
1.217     brouard  1373: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1374: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1375: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1376: char command[FILENAMELENGTH];
                   1377: int  outcmd=0;
                   1378: 
1.217     brouard  1379: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1380: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1381: char filelog[FILENAMELENGTH]; /* Log file */
                   1382: char filerest[FILENAMELENGTH];
                   1383: char fileregp[FILENAMELENGTH];
                   1384: char popfile[FILENAMELENGTH];
                   1385: 
                   1386: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1387: 
1.157     brouard  1388: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1389: /* struct timezone tzp; */
                   1390: /* extern int gettimeofday(); */
                   1391: struct tm tml, *gmtime(), *localtime();
                   1392: 
                   1393: extern time_t time();
                   1394: 
                   1395: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1396: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                   1397: struct tm tm;
                   1398: 
1.126     brouard  1399: char strcurr[80], strfor[80];
                   1400: 
                   1401: char *endptr;
                   1402: long lval;
                   1403: double dval;
                   1404: 
                   1405: #define NR_END 1
                   1406: #define FREE_ARG char*
                   1407: #define FTOL 1.0e-10
                   1408: 
                   1409: #define NRANSI 
1.240     brouard  1410: #define ITMAX 200
                   1411: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1412: 
                   1413: #define TOL 2.0e-4 
                   1414: 
                   1415: #define CGOLD 0.3819660 
                   1416: #define ZEPS 1.0e-10 
                   1417: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1418: 
                   1419: #define GOLD 1.618034 
                   1420: #define GLIMIT 100.0 
                   1421: #define TINY 1.0e-20 
                   1422: 
                   1423: static double maxarg1,maxarg2;
                   1424: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1425: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1426:   
                   1427: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1428: #define rint(a) floor(a+0.5)
1.166     brouard  1429: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1430: #define mytinydouble 1.0e-16
1.166     brouard  1431: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1432: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1433: /* static double dsqrarg; */
                   1434: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1435: static double sqrarg;
                   1436: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1437: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1438: int agegomp= AGEGOMP;
                   1439: 
                   1440: int imx; 
                   1441: int stepm=1;
                   1442: /* Stepm, step in month: minimum step interpolation*/
                   1443: 
                   1444: int estepm;
                   1445: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1446: 
                   1447: int m,nb;
                   1448: long *num;
1.197     brouard  1449: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1450: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1451:                   covariate for which somebody answered excluding 
                   1452:                   undefined. Usually 2: 0 and 1. */
                   1453: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1454:                             covariate for which somebody answered including 
                   1455:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1456: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1457: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1458: double ***mobaverage, ***mobaverages; /* New global variable */
1.332     brouard  1459: 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  1460: double *ageexmed,*agecens;
                   1461: double dateintmean=0;
1.296     brouard  1462:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1463:   double anprojf, mprojf, jprojf;
1.126     brouard  1464: 
1.296     brouard  1465:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1466:   double anbackf, mbackf, jbackf;
                   1467:   double jintmean,mintmean,aintmean;  
1.126     brouard  1468: double *weight;
                   1469: int **s; /* Status */
1.141     brouard  1470: double *agedc;
1.145     brouard  1471: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1472:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1473:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1474: double **coqvar; /* Fixed quantitative covariate nqv */
                   1475: double ***cotvar; /* Time varying covariate ntv */
1.225     brouard  1476: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1477: double  idx; 
                   1478: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.319     brouard  1479: /* Some documentation */
                   1480:       /*   Design original data
                   1481:        *  V1   V2   V3   V4  V5  V6  V7  V8  Weight ddb ddth d1st s1 V9 V10 V11 V12 s2 V9 V10 V11 V12 
                   1482:        *  <          ncovcol=6   >   nqv=2 (V7 V8)                   dv dv  dv  qtv    dv dv  dvv qtv
                   1483:        *                                                             ntv=3     nqtv=1
1.330     brouard  1484:        *  cptcovn number of covariates (not including constant and age or age*age) = number of plus sign + 1 = 10+1=11
1.319     brouard  1485:        * For time varying covariate, quanti or dummies
                   1486:        *       cotqvar[wav][iv(1 to nqtv)][i]= [1][12][i]=(V12) quanti
                   1487:        *       cotvar[wav][ntv+iv][i]= [3+(1 to nqtv)][i]=(V12) quanti
                   1488:        *       cotvar[wav][iv(1 to ntv)][i]= [1][1][i]=(V9) dummies at wav 1
                   1489:        *       cotvar[wav][iv(1 to ntv)][i]= [1][2][i]=(V10) dummies at wav 1
1.332     brouard  1490:        *       covar[Vk,i], value of the Vkth fixed covariate dummy or quanti for individual i:
1.319     brouard  1491:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   1492:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 + V9 + V9*age + V10
                   1493:        *   k=  1    2      3       4     5       6      7        8   9     10       11 
                   1494:        */
                   1495: /* According to the model, more columns can be added to covar by the product of covariates */
1.318     brouard  1496: /* 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
                   1497:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1498:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1499: */
1.319     brouard  1500: /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1501: /*    k        1  2   3   4     5    6    7     8    9 */
                   1502: /*Typevar[k]=  0  0   0   2     1    0    2     1    0 *//*0 for simple covariate (dummy, quantitative,*/
                   1503:                                                          /* fixed or varying), 1 for age product, 2 for*/
                   1504:                                                          /* product */
                   1505: /*Dummy[k]=    1  0   0   1     3    1    1     2    0 *//*Dummy[k] 0=dummy (0 1), 1 quantitative */
                   1506:                                                          /*(single or product without age), 2 dummy*/
                   1507:                                                          /* with age product, 3 quant with age product*/
                   1508: /*Tvar[k]=     5  4   3   6     5    2    7     1    1 */
                   1509: /*    nsd         1   2                              3 */ /* Counting single dummies covar fixed or tv */
1.330     brouard  1510: /*TnsdVar[Tvar]   1   2                              3 */ 
1.337   ! brouard  1511: /*Tvaraff[nsd]     4   3                              1 */ /* ID of single dummy cova fixed or timevary*/
1.319     brouard  1512: /*TvarsD[nsd]     4   3                              1 */ /* ID of single dummy cova fixed or timevary*/
                   1513: /*TvarsDind[k]    2   3                              9 */ /* position K of single dummy cova */
                   1514: /*    nsq      1                     2                 */ /* Counting single quantit tv */
                   1515: /* TvarsQ[k]   5                     2                 */ /* Number of single quantitative cova */
                   1516: /* TvarsQind   1                     6                 */ /* position K of single quantitative cova */
                   1517: /* Tprod[i]=k             1               2            */ /* Position in model of the ith prod without age */
                   1518: /* cptcovage                    1               2      */ /* Counting cov*age in the model equation */
                   1519: /* Tage[cptcovage]=k            5               8      */ /* Position in the model of ith cov*age */
                   1520: /* Tvard[1][1]@4={4,3,1,2}    V4*V3 V1*V2              */ /* Position in model of the ith prod without age */
1.330     brouard  1521: /* 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  1522: /* 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  1523: /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.234     brouard  1524: /* Type                    */
                   1525: /* V         1  2  3  4  5 */
                   1526: /*           F  F  V  V  V */
                   1527: /*           D  Q  D  D  Q */
                   1528: /*                         */
                   1529: int *TvarsD;
1.330     brouard  1530: int *TnsdVar;
1.234     brouard  1531: int *TvarsDind;
                   1532: int *TvarsQ;
                   1533: int *TvarsQind;
                   1534: 
1.318     brouard  1535: #define MAXRESULTLINESPONE 10+1
1.235     brouard  1536: int nresult=0;
1.258     brouard  1537: int parameterline=0; /* # of the parameter (type) line */
1.334     brouard  1538: int TKresult[MAXRESULTLINESPONE]; /* TKresult[nres]=k for each resultline nres give the corresponding combination of dummies */
                   1539: int resultmodel[MAXRESULTLINESPONE][NCOVMAX];/* resultmodel[k1]=k3: k1th position in the model corresponds to the k3 position in the resultline */
                   1540: int modelresult[MAXRESULTLINESPONE][NCOVMAX];/* modelresult[k3]=k1: k1th position in the model corresponds to the k3 position in the resultline */
                   1541: int Tresult[MAXRESULTLINESPONE][NCOVMAX];/* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1542: int Tinvresult[MAXRESULTLINESPONE][NCOVMAX];/* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line  */
                   1543: double TinvDoQresult[MAXRESULTLINESPONE][NCOVMAX];/* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line */
1.334     brouard  1544: int Tvresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1545: double Tqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
1.318     brouard  1546: double Tqinvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
1.332     brouard  1547: int Tvqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline */
1.318     brouard  1548: 
                   1549: /* 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
                   1550:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1551:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1552: */
1.234     brouard  1553: /* 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  1554: 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 */
                   1555: 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 */
                   1556: 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 */
                   1557: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1558: 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 */
                   1559: 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  1560: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1561: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1562: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1563: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1564: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1565: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1566: 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 */
                   1567: 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 */
                   1568: 
1.230     brouard  1569: int *Tvarsel; /**< Selected covariates for output */
                   1570: double *Tvalsel; /**< Selected modality value of covariate for output */
1.226     brouard  1571: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.227     brouard  1572: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1573: 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  1574: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1575: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1576: int *Tage;
1.227     brouard  1577: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1578: 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  1579: 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*/ 
                   1580: 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  1581: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1582: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1583: int **Tvard;
1.330     brouard  1584: int **Tvardk;
1.227     brouard  1585: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1586: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1587: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1588:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1589:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1590: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1591: double *lsurv, *lpop, *tpop;
                   1592: 
1.231     brouard  1593: #define FD 1; /* Fixed dummy covariate */
                   1594: #define FQ 2; /* Fixed quantitative covariate */
                   1595: #define FP 3; /* Fixed product covariate */
                   1596: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1597: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1598: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1599: #define VD 10; /* Varying dummy covariate */
                   1600: #define VQ 11; /* Varying quantitative covariate */
                   1601: #define VP 12; /* Varying product covariate */
                   1602: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1603: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1604: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1605: #define APFD 16; /* Age product * fixed dummy covariate */
                   1606: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1607: #define APVD 18; /* Age product * varying dummy covariate */
                   1608: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1609: 
                   1610: #define FTYPE 1; /* Fixed covariate */
                   1611: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1612: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1613: 
                   1614: struct kmodel{
                   1615:        int maintype; /* main type */
                   1616:        int subtype; /* subtype */
                   1617: };
                   1618: struct kmodel modell[NCOVMAX];
                   1619: 
1.143     brouard  1620: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1621: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1622: 
                   1623: /**************** split *************************/
                   1624: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1625: {
                   1626:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1627:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1628:   */ 
                   1629:   char *ss;                            /* pointer */
1.186     brouard  1630:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1631: 
                   1632:   l1 = strlen(path );                  /* length of path */
                   1633:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1634:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1635:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1636:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1637:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1638:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1639:     /* get current working directory */
                   1640:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1641: #ifdef WIN32
                   1642:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1643: #else
                   1644:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1645: #endif
1.126     brouard  1646:       return( GLOCK_ERROR_GETCWD );
                   1647:     }
                   1648:     /* got dirc from getcwd*/
                   1649:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1650:   } else {                             /* strip directory from path */
1.126     brouard  1651:     ss++;                              /* after this, the filename */
                   1652:     l2 = strlen( ss );                 /* length of filename */
                   1653:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1654:     strcpy( name, ss );                /* save file name */
                   1655:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1656:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1657:     printf(" DIRC2 = %s \n",dirc);
                   1658:   }
                   1659:   /* We add a separator at the end of dirc if not exists */
                   1660:   l1 = strlen( dirc );                 /* length of directory */
                   1661:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1662:     dirc[l1] =  DIRSEPARATOR;
                   1663:     dirc[l1+1] = 0; 
                   1664:     printf(" DIRC3 = %s \n",dirc);
                   1665:   }
                   1666:   ss = strrchr( name, '.' );           /* find last / */
                   1667:   if (ss >0){
                   1668:     ss++;
                   1669:     strcpy(ext,ss);                    /* save extension */
                   1670:     l1= strlen( name);
                   1671:     l2= strlen(ss)+1;
                   1672:     strncpy( finame, name, l1-l2);
                   1673:     finame[l1-l2]= 0;
                   1674:   }
                   1675: 
                   1676:   return( 0 );                         /* we're done */
                   1677: }
                   1678: 
                   1679: 
                   1680: /******************************************/
                   1681: 
                   1682: void replace_back_to_slash(char *s, char*t)
                   1683: {
                   1684:   int i;
                   1685:   int lg=0;
                   1686:   i=0;
                   1687:   lg=strlen(t);
                   1688:   for(i=0; i<= lg; i++) {
                   1689:     (s[i] = t[i]);
                   1690:     if (t[i]== '\\') s[i]='/';
                   1691:   }
                   1692: }
                   1693: 
1.132     brouard  1694: char *trimbb(char *out, char *in)
1.137     brouard  1695: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1696:   char *s;
                   1697:   s=out;
                   1698:   while (*in != '\0'){
1.137     brouard  1699:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1700:       in++;
                   1701:     }
                   1702:     *out++ = *in++;
                   1703:   }
                   1704:   *out='\0';
                   1705:   return s;
                   1706: }
                   1707: 
1.187     brouard  1708: /* char *substrchaine(char *out, char *in, char *chain) */
                   1709: /* { */
                   1710: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1711: /*   char *s, *t; */
                   1712: /*   t=in;s=out; */
                   1713: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1714: /*     *out++ = *in++; */
                   1715: /*   } */
                   1716: 
                   1717: /*   /\* *in matches *chain *\/ */
                   1718: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1719: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1720: /*   } */
                   1721: /*   in--; chain--; */
                   1722: /*   while ( (*in != '\0')){ */
                   1723: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1724: /*     *out++ = *in++; */
                   1725: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1726: /*   } */
                   1727: /*   *out='\0'; */
                   1728: /*   out=s; */
                   1729: /*   return out; */
                   1730: /* } */
                   1731: char *substrchaine(char *out, char *in, char *chain)
                   1732: {
                   1733:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1734:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1735: 
                   1736:   char *strloc;
                   1737: 
                   1738:   strcpy (out, in); 
                   1739:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1740:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1741:   if(strloc != NULL){ 
                   1742:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1743:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1744:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1745:   }
                   1746:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1747:   return out;
                   1748: }
                   1749: 
                   1750: 
1.145     brouard  1751: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1752: {
1.187     brouard  1753:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1754:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.310     brouard  1755:      gives alocc="abcdef" and blocc="ghi2j".
1.145     brouard  1756:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1757:   */
1.160     brouard  1758:   char *s, *t;
1.145     brouard  1759:   t=in;s=in;
                   1760:   while ((*in != occ) && (*in != '\0')){
                   1761:     *alocc++ = *in++;
                   1762:   }
                   1763:   if( *in == occ){
                   1764:     *(alocc)='\0';
                   1765:     s=++in;
                   1766:   }
                   1767:  
                   1768:   if (s == t) {/* occ not found */
                   1769:     *(alocc-(in-s))='\0';
                   1770:     in=s;
                   1771:   }
                   1772:   while ( *in != '\0'){
                   1773:     *blocc++ = *in++;
                   1774:   }
                   1775: 
                   1776:   *blocc='\0';
                   1777:   return t;
                   1778: }
1.137     brouard  1779: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1780: {
1.187     brouard  1781:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1782:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1783:      gives blocc="abcdef2ghi" and alocc="j".
                   1784:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1785:   */
                   1786:   char *s, *t;
                   1787:   t=in;s=in;
                   1788:   while (*in != '\0'){
                   1789:     while( *in == occ){
                   1790:       *blocc++ = *in++;
                   1791:       s=in;
                   1792:     }
                   1793:     *blocc++ = *in++;
                   1794:   }
                   1795:   if (s == t) /* occ not found */
                   1796:     *(blocc-(in-s))='\0';
                   1797:   else
                   1798:     *(blocc-(in-s)-1)='\0';
                   1799:   in=s;
                   1800:   while ( *in != '\0'){
                   1801:     *alocc++ = *in++;
                   1802:   }
                   1803: 
                   1804:   *alocc='\0';
                   1805:   return s;
                   1806: }
                   1807: 
1.126     brouard  1808: int nbocc(char *s, char occ)
                   1809: {
                   1810:   int i,j=0;
                   1811:   int lg=20;
                   1812:   i=0;
                   1813:   lg=strlen(s);
                   1814:   for(i=0; i<= lg; i++) {
1.234     brouard  1815:     if  (s[i] == occ ) j++;
1.126     brouard  1816:   }
                   1817:   return j;
                   1818: }
                   1819: 
1.137     brouard  1820: /* void cutv(char *u,char *v, char*t, char occ) */
                   1821: /* { */
                   1822: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1823: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1824: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1825: /*   int i,lg,j,p=0; */
                   1826: /*   i=0; */
                   1827: /*   lg=strlen(t); */
                   1828: /*   for(j=0; j<=lg-1; j++) { */
                   1829: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1830: /*   } */
1.126     brouard  1831: 
1.137     brouard  1832: /*   for(j=0; j<p; j++) { */
                   1833: /*     (u[j] = t[j]); */
                   1834: /*   } */
                   1835: /*      u[p]='\0'; */
1.126     brouard  1836: 
1.137     brouard  1837: /*    for(j=0; j<= lg; j++) { */
                   1838: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1839: /*   } */
                   1840: /* } */
1.126     brouard  1841: 
1.160     brouard  1842: #ifdef _WIN32
                   1843: char * strsep(char **pp, const char *delim)
                   1844: {
                   1845:   char *p, *q;
                   1846:          
                   1847:   if ((p = *pp) == NULL)
                   1848:     return 0;
                   1849:   if ((q = strpbrk (p, delim)) != NULL)
                   1850:   {
                   1851:     *pp = q + 1;
                   1852:     *q = '\0';
                   1853:   }
                   1854:   else
                   1855:     *pp = 0;
                   1856:   return p;
                   1857: }
                   1858: #endif
                   1859: 
1.126     brouard  1860: /********************** nrerror ********************/
                   1861: 
                   1862: void nrerror(char error_text[])
                   1863: {
                   1864:   fprintf(stderr,"ERREUR ...\n");
                   1865:   fprintf(stderr,"%s\n",error_text);
                   1866:   exit(EXIT_FAILURE);
                   1867: }
                   1868: /*********************** vector *******************/
                   1869: double *vector(int nl, int nh)
                   1870: {
                   1871:   double *v;
                   1872:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1873:   if (!v) nrerror("allocation failure in vector");
                   1874:   return v-nl+NR_END;
                   1875: }
                   1876: 
                   1877: /************************ free vector ******************/
                   1878: void free_vector(double*v, int nl, int nh)
                   1879: {
                   1880:   free((FREE_ARG)(v+nl-NR_END));
                   1881: }
                   1882: 
                   1883: /************************ivector *******************************/
                   1884: int *ivector(long nl,long nh)
                   1885: {
                   1886:   int *v;
                   1887:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1888:   if (!v) nrerror("allocation failure in ivector");
                   1889:   return v-nl+NR_END;
                   1890: }
                   1891: 
                   1892: /******************free ivector **************************/
                   1893: void free_ivector(int *v, long nl, long nh)
                   1894: {
                   1895:   free((FREE_ARG)(v+nl-NR_END));
                   1896: }
                   1897: 
                   1898: /************************lvector *******************************/
                   1899: long *lvector(long nl,long nh)
                   1900: {
                   1901:   long *v;
                   1902:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1903:   if (!v) nrerror("allocation failure in ivector");
                   1904:   return v-nl+NR_END;
                   1905: }
                   1906: 
                   1907: /******************free lvector **************************/
                   1908: void free_lvector(long *v, long nl, long nh)
                   1909: {
                   1910:   free((FREE_ARG)(v+nl-NR_END));
                   1911: }
                   1912: 
                   1913: /******************* imatrix *******************************/
                   1914: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1915:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1916: { 
                   1917:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1918:   int **m; 
                   1919:   
                   1920:   /* allocate pointers to rows */ 
                   1921:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1922:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1923:   m += NR_END; 
                   1924:   m -= nrl; 
                   1925:   
                   1926:   
                   1927:   /* allocate rows and set pointers to them */ 
                   1928:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1929:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1930:   m[nrl] += NR_END; 
                   1931:   m[nrl] -= ncl; 
                   1932:   
                   1933:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1934:   
                   1935:   /* return pointer to array of pointers to rows */ 
                   1936:   return m; 
                   1937: } 
                   1938: 
                   1939: /****************** free_imatrix *************************/
                   1940: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1941:       int **m;
                   1942:       long nch,ncl,nrh,nrl; 
                   1943:      /* free an int matrix allocated by imatrix() */ 
                   1944: { 
                   1945:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1946:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1947: } 
                   1948: 
                   1949: /******************* matrix *******************************/
                   1950: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1951: {
                   1952:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1953:   double **m;
                   1954: 
                   1955:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1956:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1957:   m += NR_END;
                   1958:   m -= nrl;
                   1959: 
                   1960:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1961:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1962:   m[nrl] += NR_END;
                   1963:   m[nrl] -= ncl;
                   1964: 
                   1965:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1966:   return m;
1.145     brouard  1967:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1968: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1969: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1970:    */
                   1971: }
                   1972: 
                   1973: /*************************free matrix ************************/
                   1974: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1975: {
                   1976:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1977:   free((FREE_ARG)(m+nrl-NR_END));
                   1978: }
                   1979: 
                   1980: /******************* ma3x *******************************/
                   1981: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1982: {
                   1983:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1984:   double ***m;
                   1985: 
                   1986:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1987:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1988:   m += NR_END;
                   1989:   m -= nrl;
                   1990: 
                   1991:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1992:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1993:   m[nrl] += NR_END;
                   1994:   m[nrl] -= ncl;
                   1995: 
                   1996:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1997: 
                   1998:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1999:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   2000:   m[nrl][ncl] += NR_END;
                   2001:   m[nrl][ncl] -= nll;
                   2002:   for (j=ncl+1; j<=nch; j++) 
                   2003:     m[nrl][j]=m[nrl][j-1]+nlay;
                   2004:   
                   2005:   for (i=nrl+1; i<=nrh; i++) {
                   2006:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   2007:     for (j=ncl+1; j<=nch; j++) 
                   2008:       m[i][j]=m[i][j-1]+nlay;
                   2009:   }
                   2010:   return m; 
                   2011:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   2012:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   2013:   */
                   2014: }
                   2015: 
                   2016: /*************************free ma3x ************************/
                   2017: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   2018: {
                   2019:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   2020:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2021:   free((FREE_ARG)(m+nrl-NR_END));
                   2022: }
                   2023: 
                   2024: /*************** function subdirf ***********/
                   2025: char *subdirf(char fileres[])
                   2026: {
                   2027:   /* Caution optionfilefiname is hidden */
                   2028:   strcpy(tmpout,optionfilefiname);
                   2029:   strcat(tmpout,"/"); /* Add to the right */
                   2030:   strcat(tmpout,fileres);
                   2031:   return tmpout;
                   2032: }
                   2033: 
                   2034: /*************** function subdirf2 ***********/
                   2035: char *subdirf2(char fileres[], char *preop)
                   2036: {
1.314     brouard  2037:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
                   2038:  Errors in subdirf, 2, 3 while printing tmpout is
1.315     brouard  2039:  rewritten within the same printf. Workaround: many printfs */
1.126     brouard  2040:   /* Caution optionfilefiname is hidden */
                   2041:   strcpy(tmpout,optionfilefiname);
                   2042:   strcat(tmpout,"/");
                   2043:   strcat(tmpout,preop);
                   2044:   strcat(tmpout,fileres);
                   2045:   return tmpout;
                   2046: }
                   2047: 
                   2048: /*************** function subdirf3 ***********/
                   2049: char *subdirf3(char fileres[], char *preop, char *preop2)
                   2050: {
                   2051:   
                   2052:   /* Caution optionfilefiname is hidden */
                   2053:   strcpy(tmpout,optionfilefiname);
                   2054:   strcat(tmpout,"/");
                   2055:   strcat(tmpout,preop);
                   2056:   strcat(tmpout,preop2);
                   2057:   strcat(tmpout,fileres);
                   2058:   return tmpout;
                   2059: }
1.213     brouard  2060:  
                   2061: /*************** function subdirfext ***********/
                   2062: char *subdirfext(char fileres[], char *preop, char *postop)
                   2063: {
                   2064:   
                   2065:   strcpy(tmpout,preop);
                   2066:   strcat(tmpout,fileres);
                   2067:   strcat(tmpout,postop);
                   2068:   return tmpout;
                   2069: }
1.126     brouard  2070: 
1.213     brouard  2071: /*************** function subdirfext3 ***********/
                   2072: char *subdirfext3(char fileres[], char *preop, char *postop)
                   2073: {
                   2074:   
                   2075:   /* Caution optionfilefiname is hidden */
                   2076:   strcpy(tmpout,optionfilefiname);
                   2077:   strcat(tmpout,"/");
                   2078:   strcat(tmpout,preop);
                   2079:   strcat(tmpout,fileres);
                   2080:   strcat(tmpout,postop);
                   2081:   return tmpout;
                   2082: }
                   2083:  
1.162     brouard  2084: char *asc_diff_time(long time_sec, char ascdiff[])
                   2085: {
                   2086:   long sec_left, days, hours, minutes;
                   2087:   days = (time_sec) / (60*60*24);
                   2088:   sec_left = (time_sec) % (60*60*24);
                   2089:   hours = (sec_left) / (60*60) ;
                   2090:   sec_left = (sec_left) %(60*60);
                   2091:   minutes = (sec_left) /60;
                   2092:   sec_left = (sec_left) % (60);
                   2093:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   2094:   return ascdiff;
                   2095: }
                   2096: 
1.126     brouard  2097: /***************** f1dim *************************/
                   2098: extern int ncom; 
                   2099: extern double *pcom,*xicom;
                   2100: extern double (*nrfunc)(double []); 
                   2101:  
                   2102: double f1dim(double x) 
                   2103: { 
                   2104:   int j; 
                   2105:   double f;
                   2106:   double *xt; 
                   2107:  
                   2108:   xt=vector(1,ncom); 
                   2109:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   2110:   f=(*nrfunc)(xt); 
                   2111:   free_vector(xt,1,ncom); 
                   2112:   return f; 
                   2113: } 
                   2114: 
                   2115: /*****************brent *************************/
                   2116: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  2117: {
                   2118:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   2119:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   2120:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   2121:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   2122:    * returned function value. 
                   2123:   */
1.126     brouard  2124:   int iter; 
                   2125:   double a,b,d,etemp;
1.159     brouard  2126:   double fu=0,fv,fw,fx;
1.164     brouard  2127:   double ftemp=0.;
1.126     brouard  2128:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   2129:   double e=0.0; 
                   2130:  
                   2131:   a=(ax < cx ? ax : cx); 
                   2132:   b=(ax > cx ? ax : cx); 
                   2133:   x=w=v=bx; 
                   2134:   fw=fv=fx=(*f)(x); 
                   2135:   for (iter=1;iter<=ITMAX;iter++) { 
                   2136:     xm=0.5*(a+b); 
                   2137:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   2138:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   2139:     printf(".");fflush(stdout);
                   2140:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  2141: #ifdef DEBUGBRENT
1.126     brouard  2142:     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);
                   2143:     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);
                   2144:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   2145: #endif
                   2146:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   2147:       *xmin=x; 
                   2148:       return fx; 
                   2149:     } 
                   2150:     ftemp=fu;
                   2151:     if (fabs(e) > tol1) { 
                   2152:       r=(x-w)*(fx-fv); 
                   2153:       q=(x-v)*(fx-fw); 
                   2154:       p=(x-v)*q-(x-w)*r; 
                   2155:       q=2.0*(q-r); 
                   2156:       if (q > 0.0) p = -p; 
                   2157:       q=fabs(q); 
                   2158:       etemp=e; 
                   2159:       e=d; 
                   2160:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  2161:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  2162:       else { 
1.224     brouard  2163:                                d=p/q; 
                   2164:                                u=x+d; 
                   2165:                                if (u-a < tol2 || b-u < tol2) 
                   2166:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  2167:       } 
                   2168:     } else { 
                   2169:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2170:     } 
                   2171:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   2172:     fu=(*f)(u); 
                   2173:     if (fu <= fx) { 
                   2174:       if (u >= x) a=x; else b=x; 
                   2175:       SHFT(v,w,x,u) 
1.183     brouard  2176:       SHFT(fv,fw,fx,fu) 
                   2177:     } else { 
                   2178:       if (u < x) a=u; else b=u; 
                   2179:       if (fu <= fw || w == x) { 
1.224     brouard  2180:                                v=w; 
                   2181:                                w=u; 
                   2182:                                fv=fw; 
                   2183:                                fw=fu; 
1.183     brouard  2184:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  2185:                                v=u; 
                   2186:                                fv=fu; 
1.183     brouard  2187:       } 
                   2188:     } 
1.126     brouard  2189:   } 
                   2190:   nrerror("Too many iterations in brent"); 
                   2191:   *xmin=x; 
                   2192:   return fx; 
                   2193: } 
                   2194: 
                   2195: /****************** mnbrak ***********************/
                   2196: 
                   2197: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2198:            double (*func)(double)) 
1.183     brouard  2199: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2200: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2201: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2202: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2203:    */
1.126     brouard  2204:   double ulim,u,r,q, dum;
                   2205:   double fu; 
1.187     brouard  2206: 
                   2207:   double scale=10.;
                   2208:   int iterscale=0;
                   2209: 
                   2210:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2211:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2212: 
                   2213: 
                   2214:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2215:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2216:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2217:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2218:   /* } */
                   2219: 
1.126     brouard  2220:   if (*fb > *fa) { 
                   2221:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2222:     SHFT(dum,*fb,*fa,dum) 
                   2223:   } 
1.126     brouard  2224:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2225:   *fc=(*func)(*cx); 
1.183     brouard  2226: #ifdef DEBUG
1.224     brouard  2227:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2228:   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  2229: #endif
1.224     brouard  2230:   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  2231:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2232:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2233:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2234:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2235:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2236:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2237:       fu=(*func)(u); 
1.163     brouard  2238: #ifdef DEBUG
                   2239:       /* f(x)=A(x-u)**2+f(u) */
                   2240:       double A, fparabu; 
                   2241:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2242:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2243:       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);
                   2244:       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  2245:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2246:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2247:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2248:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2249: #endif 
1.184     brouard  2250: #ifdef MNBRAKORIGINAL
1.183     brouard  2251: #else
1.191     brouard  2252: /*       if (fu > *fc) { */
                   2253: /* #ifdef DEBUG */
                   2254: /*       printf("mnbrak4  fu > fc \n"); */
                   2255: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2256: /* #endif */
                   2257: /*     /\* 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 *\\/  *\/ */
                   2258: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2259: /*     dum=u; /\* Shifting c and u *\/ */
                   2260: /*     u = *cx; */
                   2261: /*     *cx = dum; */
                   2262: /*     dum = fu; */
                   2263: /*     fu = *fc; */
                   2264: /*     *fc =dum; */
                   2265: /*       } else { /\* end *\/ */
                   2266: /* #ifdef DEBUG */
                   2267: /*       printf("mnbrak3  fu < fc \n"); */
                   2268: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2269: /* #endif */
                   2270: /*     dum=u; /\* Shifting c and u *\/ */
                   2271: /*     u = *cx; */
                   2272: /*     *cx = dum; */
                   2273: /*     dum = fu; */
                   2274: /*     fu = *fc; */
                   2275: /*     *fc =dum; */
                   2276: /*       } */
1.224     brouard  2277: #ifdef DEBUGMNBRAK
                   2278:                 double A, fparabu; 
                   2279:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2280:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2281:      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);
                   2282:      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  2283: #endif
1.191     brouard  2284:       dum=u; /* Shifting c and u */
                   2285:       u = *cx;
                   2286:       *cx = dum;
                   2287:       dum = fu;
                   2288:       fu = *fc;
                   2289:       *fc =dum;
1.183     brouard  2290: #endif
1.162     brouard  2291:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2292: #ifdef DEBUG
1.224     brouard  2293:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2294:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2295: #endif
1.126     brouard  2296:       fu=(*func)(u); 
                   2297:       if (fu < *fc) { 
1.183     brouard  2298: #ifdef DEBUG
1.224     brouard  2299:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2300:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2301: #endif
                   2302:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2303:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2304: #ifdef DEBUG
                   2305:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2306: #endif
                   2307:       } 
1.162     brouard  2308:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2309: #ifdef DEBUG
1.224     brouard  2310:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2311:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2312: #endif
1.126     brouard  2313:       u=ulim; 
                   2314:       fu=(*func)(u); 
1.183     brouard  2315:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2316: #ifdef DEBUG
1.224     brouard  2317:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2318:       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  2319: #endif
1.126     brouard  2320:       u=(*cx)+GOLD*(*cx-*bx); 
                   2321:       fu=(*func)(u); 
1.224     brouard  2322: #ifdef DEBUG
                   2323:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2324:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2325: #endif
1.183     brouard  2326:     } /* end tests */
1.126     brouard  2327:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2328:     SHFT(*fa,*fb,*fc,fu) 
                   2329: #ifdef DEBUG
1.224     brouard  2330:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2331:       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  2332: #endif
                   2333:   } /* 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  2334: } 
                   2335: 
                   2336: /*************** linmin ************************/
1.162     brouard  2337: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2338: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2339: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2340: the value of func at the returned location p . This is actually all accomplished by calling the
                   2341: routines mnbrak and brent .*/
1.126     brouard  2342: int ncom; 
                   2343: double *pcom,*xicom;
                   2344: double (*nrfunc)(double []); 
                   2345:  
1.224     brouard  2346: #ifdef LINMINORIGINAL
1.126     brouard  2347: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2348: #else
                   2349: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2350: #endif
1.126     brouard  2351: { 
                   2352:   double brent(double ax, double bx, double cx, 
                   2353:               double (*f)(double), double tol, double *xmin); 
                   2354:   double f1dim(double x); 
                   2355:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2356:              double *fc, double (*func)(double)); 
                   2357:   int j; 
                   2358:   double xx,xmin,bx,ax; 
                   2359:   double fx,fb,fa;
1.187     brouard  2360: 
1.203     brouard  2361: #ifdef LINMINORIGINAL
                   2362: #else
                   2363:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2364: #endif
                   2365:   
1.126     brouard  2366:   ncom=n; 
                   2367:   pcom=vector(1,n); 
                   2368:   xicom=vector(1,n); 
                   2369:   nrfunc=func; 
                   2370:   for (j=1;j<=n;j++) { 
                   2371:     pcom[j]=p[j]; 
1.202     brouard  2372:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2373:   } 
1.187     brouard  2374: 
1.203     brouard  2375: #ifdef LINMINORIGINAL
                   2376:   xx=1.;
                   2377: #else
                   2378:   axs=0.0;
                   2379:   xxs=1.;
                   2380:   do{
                   2381:     xx= xxs;
                   2382: #endif
1.187     brouard  2383:     ax=0.;
                   2384:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2385:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2386:     /* 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))   */
                   2387:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2388:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2389:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2390:     /* 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  2391: #ifdef LINMINORIGINAL
                   2392: #else
                   2393:     if (fx != fx){
1.224     brouard  2394:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2395:                        printf("|");
                   2396:                        fprintf(ficlog,"|");
1.203     brouard  2397: #ifdef DEBUGLINMIN
1.224     brouard  2398:                        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  2399: #endif
                   2400:     }
1.224     brouard  2401:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2402: #endif
                   2403:   
1.191     brouard  2404: #ifdef DEBUGLINMIN
                   2405:   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  2406:   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  2407: #endif
1.224     brouard  2408: #ifdef LINMINORIGINAL
                   2409: #else
1.317     brouard  2410:   if(fb == fx){ /* Flat function in the direction */
                   2411:     xmin=xx;
1.224     brouard  2412:     *flat=1;
1.317     brouard  2413:   }else{
1.224     brouard  2414:     *flat=0;
                   2415: #endif
                   2416:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2417:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2418:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2419:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2420:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2421:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2422: #ifdef DEBUG
1.224     brouard  2423:   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);
                   2424:   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);
                   2425: #endif
                   2426: #ifdef LINMINORIGINAL
                   2427: #else
                   2428:                        }
1.126     brouard  2429: #endif
1.191     brouard  2430: #ifdef DEBUGLINMIN
                   2431:   printf("linmin end ");
1.202     brouard  2432:   fprintf(ficlog,"linmin end ");
1.191     brouard  2433: #endif
1.126     brouard  2434:   for (j=1;j<=n;j++) { 
1.203     brouard  2435: #ifdef LINMINORIGINAL
                   2436:     xi[j] *= xmin; 
                   2437: #else
                   2438: #ifdef DEBUGLINMIN
                   2439:     if(xxs <1.0)
                   2440:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2441: #endif
                   2442:     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) */
                   2443: #ifdef DEBUGLINMIN
                   2444:     if(xxs <1.0)
                   2445:       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 );
                   2446: #endif
                   2447: #endif
1.187     brouard  2448:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2449:   } 
1.191     brouard  2450: #ifdef DEBUGLINMIN
1.203     brouard  2451:   printf("\n");
1.191     brouard  2452:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2453:   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  2454:   for (j=1;j<=n;j++) { 
1.202     brouard  2455:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2456:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2457:     if(j % ncovmodel == 0){
1.191     brouard  2458:       printf("\n");
1.202     brouard  2459:       fprintf(ficlog,"\n");
                   2460:     }
1.191     brouard  2461:   }
1.203     brouard  2462: #else
1.191     brouard  2463: #endif
1.126     brouard  2464:   free_vector(xicom,1,n); 
                   2465:   free_vector(pcom,1,n); 
                   2466: } 
                   2467: 
                   2468: 
                   2469: /*************** powell ************************/
1.162     brouard  2470: /*
1.317     brouard  2471: Minimization of a function func of n variables. Input consists in an initial starting point
                   2472: p[1..n] ; an initial matrix xi[1..n][1..n]  whose columns contain the initial set of di-
                   2473: rections (usually the n unit vectors); and ftol, the fractional tolerance in the function value
                   2474: such that failure to decrease by more than this amount in one iteration signals doneness. On
1.162     brouard  2475: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2476: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2477:  */
1.224     brouard  2478: #ifdef LINMINORIGINAL
                   2479: #else
                   2480:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2481:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2482: #endif
1.126     brouard  2483: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2484:            double (*func)(double [])) 
                   2485: { 
1.224     brouard  2486: #ifdef LINMINORIGINAL
                   2487:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2488:              double (*func)(double [])); 
1.224     brouard  2489: #else 
1.241     brouard  2490:  void linmin(double p[], double xi[], int n, double *fret,
                   2491:             double (*func)(double []),int *flat); 
1.224     brouard  2492: #endif
1.239     brouard  2493:  int i,ibig,j,jk,k; 
1.126     brouard  2494:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2495:   double directest;
1.126     brouard  2496:   double fp,fptt;
                   2497:   double *xits;
                   2498:   int niterf, itmp;
                   2499: 
                   2500:   pt=vector(1,n); 
                   2501:   ptt=vector(1,n); 
                   2502:   xit=vector(1,n); 
                   2503:   xits=vector(1,n); 
                   2504:   *fret=(*func)(p); 
                   2505:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  2506:   rcurr_time = time(NULL);  
1.126     brouard  2507:   for (*iter=1;;++(*iter)) { 
                   2508:     ibig=0; 
                   2509:     del=0.0; 
1.157     brouard  2510:     rlast_time=rcurr_time;
                   2511:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2512:     rcurr_time = time(NULL);  
                   2513:     curr_time = *localtime(&rcurr_time);
1.337   ! brouard  2514:     /* 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); */
        !          2515:     /* 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); */
        !          2516:     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);
        !          2517:     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  2518: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.324     brouard  2519:     fp=(*fret); /* From former iteration or initial value */
1.192     brouard  2520:     for (i=1;i<=n;i++) {
1.126     brouard  2521:       fprintf(ficrespow," %.12lf", p[i]);
                   2522:     }
1.239     brouard  2523:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2524:     printf("\n#model=  1      +     age ");
                   2525:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2526:     if(nagesqr==1){
1.241     brouard  2527:        printf("  + age*age  ");
                   2528:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2529:     }
                   2530:     for(j=1;j <=ncovmodel-2;j++){
                   2531:       if(Typevar[j]==0) {
                   2532:        printf("  +      V%d  ",Tvar[j]);
                   2533:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2534:       }else if(Typevar[j]==1) {
                   2535:        printf("  +    V%d*age ",Tvar[j]);
                   2536:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2537:       }else if(Typevar[j]==2) {
                   2538:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2539:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2540:       }
                   2541:     }
1.126     brouard  2542:     printf("\n");
1.239     brouard  2543: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2544: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2545:     fprintf(ficlog,"\n");
1.239     brouard  2546:     for(i=1,jk=1; i <=nlstate; i++){
                   2547:       for(k=1; k <=(nlstate+ndeath); k++){
                   2548:        if (k != i) {
                   2549:          printf("%d%d ",i,k);
                   2550:          fprintf(ficlog,"%d%d ",i,k);
                   2551:          for(j=1; j <=ncovmodel; j++){
                   2552:            printf("%12.7f ",p[jk]);
                   2553:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2554:            jk++; 
                   2555:          }
                   2556:          printf("\n");
                   2557:          fprintf(ficlog,"\n");
                   2558:        }
                   2559:       }
                   2560:     }
1.241     brouard  2561:     if(*iter <=3 && *iter >1){
1.157     brouard  2562:       tml = *localtime(&rcurr_time);
                   2563:       strcpy(strcurr,asctime(&tml));
                   2564:       rforecast_time=rcurr_time; 
1.126     brouard  2565:       itmp = strlen(strcurr);
                   2566:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2567:        strcurr[itmp-1]='\0';
1.162     brouard  2568:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2569:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  2570:       for(niterf=10;niterf<=30;niterf+=10){
1.241     brouard  2571:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2572:        forecast_time = *localtime(&rforecast_time);
                   2573:        strcpy(strfor,asctime(&forecast_time));
                   2574:        itmp = strlen(strfor);
                   2575:        if(strfor[itmp-1]=='\n')
                   2576:          strfor[itmp-1]='\0';
                   2577:        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);
                   2578:        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  2579:       }
                   2580:     }
1.187     brouard  2581:     for (i=1;i<=n;i++) { /* For each direction i */
                   2582:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2583:       fptt=(*fret); 
                   2584: #ifdef DEBUG
1.203     brouard  2585:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2586:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2587: #endif
1.203     brouard  2588:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2589:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2590: #ifdef LINMINORIGINAL
1.188     brouard  2591:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2592: #else
                   2593:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2594:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2595: #endif
                   2596:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2597:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2598:                                /* because that direction will be replaced unless the gain del is small */
                   2599:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2600:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2601:                                /* with the new direction. */
                   2602:                                del=fabs(fptt-(*fret)); 
                   2603:                                ibig=i; 
1.126     brouard  2604:       } 
                   2605: #ifdef DEBUG
                   2606:       printf("%d %.12e",i,(*fret));
                   2607:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2608:       for (j=1;j<=n;j++) {
1.224     brouard  2609:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2610:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2611:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2612:       }
                   2613:       for(j=1;j<=n;j++) {
1.225     brouard  2614:                                printf(" p(%d)=%.12e",j,p[j]);
                   2615:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2616:       }
                   2617:       printf("\n");
                   2618:       fprintf(ficlog,"\n");
                   2619: #endif
1.187     brouard  2620:     } /* end loop on each direction i */
                   2621:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2622:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2623:     /* New value of last point Pn is not computed, P(n-1) */
1.319     brouard  2624:     for(j=1;j<=n;j++) {
                   2625:       if(flatdir[j] >0){
                   2626:         printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2627:         fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
1.302     brouard  2628:       }
1.319     brouard  2629:       /* printf("\n"); */
                   2630:       /* fprintf(ficlog,"\n"); */
                   2631:     }
1.243     brouard  2632:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2633:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2634:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2635:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2636:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2637:       /* decreased of more than 3.84  */
                   2638:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2639:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2640:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2641:                        
1.188     brouard  2642:       /* Starting the program with initial values given by a former maximization will simply change */
                   2643:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2644:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2645:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2646: #ifdef DEBUG
                   2647:       int k[2],l;
                   2648:       k[0]=1;
                   2649:       k[1]=-1;
                   2650:       printf("Max: %.12e",(*func)(p));
                   2651:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2652:       for (j=1;j<=n;j++) {
                   2653:        printf(" %.12e",p[j]);
                   2654:        fprintf(ficlog," %.12e",p[j]);
                   2655:       }
                   2656:       printf("\n");
                   2657:       fprintf(ficlog,"\n");
                   2658:       for(l=0;l<=1;l++) {
                   2659:        for (j=1;j<=n;j++) {
                   2660:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2661:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2662:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2663:        }
                   2664:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2665:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2666:       }
                   2667: #endif
                   2668: 
                   2669:       free_vector(xit,1,n); 
                   2670:       free_vector(xits,1,n); 
                   2671:       free_vector(ptt,1,n); 
                   2672:       free_vector(pt,1,n); 
                   2673:       return; 
1.192     brouard  2674:     } /* enough precision */ 
1.240     brouard  2675:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2676:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2677:       ptt[j]=2.0*p[j]-pt[j]; 
                   2678:       xit[j]=p[j]-pt[j]; 
                   2679:       pt[j]=p[j]; 
                   2680:     } 
1.181     brouard  2681:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2682: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2683:                if (*iter <=4) {
1.225     brouard  2684: #else
                   2685: #endif
1.224     brouard  2686: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2687: #else
1.161     brouard  2688:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2689: #endif
1.162     brouard  2690:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2691:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2692:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2693:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2694:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2695:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2696:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2697:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2698:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2699:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2700:       /* mu² and del² are equal when f3=f1 */
                   2701:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2702:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2703:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2704:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2705: #ifdef NRCORIGINAL
                   2706:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2707: #else
                   2708:       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  2709:       t= t- del*SQR(fp-fptt);
1.183     brouard  2710: #endif
1.202     brouard  2711:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2712: #ifdef DEBUG
1.181     brouard  2713:       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);
                   2714:       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  2715:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2716:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2717:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2718:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2719:       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);
                   2720:       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);
                   2721: #endif
1.183     brouard  2722: #ifdef POWELLORIGINAL
                   2723:       if (t < 0.0) { /* Then we use it for new direction */
                   2724: #else
1.182     brouard  2725:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2726:                                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  2727:         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  2728:         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  2729:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2730:       } 
1.181     brouard  2731:       if (directest < 0.0) { /* Then we use it for new direction */
                   2732: #endif
1.191     brouard  2733: #ifdef DEBUGLINMIN
1.234     brouard  2734:        printf("Before linmin in direction P%d-P0\n",n);
                   2735:        for (j=1;j<=n;j++) {
                   2736:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2737:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2738:          if(j % ncovmodel == 0){
                   2739:            printf("\n");
                   2740:            fprintf(ficlog,"\n");
                   2741:          }
                   2742:        }
1.224     brouard  2743: #endif
                   2744: #ifdef LINMINORIGINAL
1.234     brouard  2745:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2746: #else
1.234     brouard  2747:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2748:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2749: #endif
1.234     brouard  2750:        
1.191     brouard  2751: #ifdef DEBUGLINMIN
1.234     brouard  2752:        for (j=1;j<=n;j++) { 
                   2753:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2754:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2755:          if(j % ncovmodel == 0){
                   2756:            printf("\n");
                   2757:            fprintf(ficlog,"\n");
                   2758:          }
                   2759:        }
1.224     brouard  2760: #endif
1.234     brouard  2761:        for (j=1;j<=n;j++) { 
                   2762:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2763:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2764:        }
1.224     brouard  2765: #ifdef LINMINORIGINAL
                   2766: #else
1.234     brouard  2767:        for (j=1, flatd=0;j<=n;j++) {
                   2768:          if(flatdir[j]>0)
                   2769:            flatd++;
                   2770:        }
                   2771:        if(flatd >0){
1.255     brouard  2772:          printf("%d flat directions: ",flatd);
                   2773:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  2774:          for (j=1;j<=n;j++) { 
                   2775:            if(flatdir[j]>0){
                   2776:              printf("%d ",j);
                   2777:              fprintf(ficlog,"%d ",j);
                   2778:            }
                   2779:          }
                   2780:          printf("\n");
                   2781:          fprintf(ficlog,"\n");
1.319     brouard  2782: #ifdef FLATSUP
                   2783:           free_vector(xit,1,n); 
                   2784:           free_vector(xits,1,n); 
                   2785:           free_vector(ptt,1,n); 
                   2786:           free_vector(pt,1,n); 
                   2787:           return;
                   2788: #endif
1.234     brouard  2789:        }
1.191     brouard  2790: #endif
1.234     brouard  2791:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2792:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2793:        
1.126     brouard  2794: #ifdef DEBUG
1.234     brouard  2795:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2796:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2797:        for(j=1;j<=n;j++){
                   2798:          printf(" %lf",xit[j]);
                   2799:          fprintf(ficlog," %lf",xit[j]);
                   2800:        }
                   2801:        printf("\n");
                   2802:        fprintf(ficlog,"\n");
1.126     brouard  2803: #endif
1.192     brouard  2804:       } /* end of t or directest negative */
1.224     brouard  2805: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2806: #else
1.234     brouard  2807:       } /* end if (fptt < fp)  */
1.192     brouard  2808: #endif
1.225     brouard  2809: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2810:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2811: #else
1.224     brouard  2812: #endif
1.234     brouard  2813:                } /* loop iteration */ 
1.126     brouard  2814: } 
1.234     brouard  2815:   
1.126     brouard  2816: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2817:   
1.235     brouard  2818:   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  2819:   {
1.279     brouard  2820:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij 
                   2821:      *   (and selected quantitative values in nres)
                   2822:      *  by left multiplying the unit
                   2823:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   2824:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   2825:      * Wx is row vector: population in state 1, population in state 2, population dead
                   2826:      * or prevalence in state 1, prevalence in state 2, 0
                   2827:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   2828:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   2829:      * Output is prlim.
                   2830:      * Initial matrix pimij 
                   2831:      */
1.206     brouard  2832:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2833:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2834:   /*  0,                   0                  , 1} */
                   2835:   /*
                   2836:    * and after some iteration: */
                   2837:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2838:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2839:   /*  0,                   0                  , 1} */
                   2840:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2841:   /* {0.51571254859325999, 0.4842874514067399, */
                   2842:   /*  0.51326036147820708, 0.48673963852179264} */
                   2843:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2844:     
1.332     brouard  2845:     int i, ii,j,k, k1;
1.209     brouard  2846:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2847:   /* double **matprod2(); */ /* test */
1.218     brouard  2848:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2849:   double **newm;
1.209     brouard  2850:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2851:   int ncvloop=0;
1.288     brouard  2852:   int first=0;
1.169     brouard  2853:   
1.209     brouard  2854:   min=vector(1,nlstate);
                   2855:   max=vector(1,nlstate);
                   2856:   meandiff=vector(1,nlstate);
                   2857: 
1.218     brouard  2858:        /* Starting with matrix unity */
1.126     brouard  2859:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2860:     for (j=1;j<=nlstate+ndeath;j++){
                   2861:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2862:     }
1.169     brouard  2863:   
                   2864:   cov[1]=1.;
                   2865:   
                   2866:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2867:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2868:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2869:     ncvloop++;
1.126     brouard  2870:     newm=savm;
                   2871:     /* Covariates have to be included here again */
1.138     brouard  2872:     cov[2]=agefin;
1.319     brouard  2873:      if(nagesqr==1){
                   2874:       cov[3]= agefin*agefin;
                   2875:      }
1.332     brouard  2876:      /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   2877:      /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   2878:      for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   2879:        if(Typevar[k1]==1){ /* A product with age */
                   2880:         cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   2881:        }else{
                   2882:         cov[2+nagesqr+k1]=precov[nres][k1];
                   2883:        }
                   2884:      }/* End of loop on model equation */
                   2885:      
                   2886: /* Start of old code (replaced by a loop on position in the model equation */
                   2887:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only of the model *\/ */
                   2888:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   2889:     /*   /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; *\/ */
                   2890:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TnsdVar[TvarsD[k]])]; */
                   2891:     /*   /\* model = 1 +age + V1*V3 + age*V1 + V2 + V1 + age*V2 + V3 + V3*age + V1*V2  */
                   2892:     /*    * k                  1        2      3    4      5      6     7        8 */
                   2893:     /*    *cov[]   1    2      3        4      5    6      7      8     9       10 */
                   2894:     /*    *TypeVar[k]          2        1      0    0      1      0     1        2 */
                   2895:     /*    *Dummy[k]            0        2      0    0      2      0     2        0 */
                   2896:     /*    *Tvar[k]             4        1      2    1      2      3     3        5 */
                   2897:     /*    *nsd=3                              (1)  (2)           (3) */
                   2898:     /*    *TvarsD[nsd]                      [1]=2    1             3 */
                   2899:     /*    *TnsdVar                          [2]=2 [1]=1         [3]=3 */
                   2900:     /*    *TvarsDind[nsd](=k)               [1]=3 [2]=4         [3]=6 */
                   2901:     /*    *Tage[]                  [1]=1                  [2]=2      [3]=3 */
                   2902:     /*    *Tvard[]       [1][1]=1                                           [2][1]=1 */
                   2903:     /*    *                   [1][2]=3                                           [2][2]=2 */
                   2904:     /*    *Tprod[](=k)     [1]=1                                              [2]=8 */
                   2905:     /*    *TvarsDp(=Tvar)   [1]=1            [2]=2             [3]=3          [4]=5 */
                   2906:     /*    *TvarD (=k)       [1]=1            [2]=3 [3]=4       [3]=6          [4]=6 */
                   2907:     /*    *TvarsDpType */
                   2908:     /*    *si model= 1 + age + V3 + V2*age + V2 + V3*age */
                   2909:     /*    * nsd=1              (1)           (2) */
                   2910:     /*    *TvarsD[nsd]          3             2 */
                   2911:     /*    *TnsdVar           (3)=1          (2)=2 */
                   2912:     /*    *TvarsDind[nsd](=k)  [1]=1        [2]=3 */
                   2913:     /*    *Tage[]                  [1]=2           [2]= 3    */
                   2914:     /*    *\/ */
                   2915:     /*   /\* cov[++k1]=nbcode[TvarsD[k]][codtabm(ij,k)]; *\/ */
                   2916:     /*   /\* 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)); *\/ */
                   2917:     /* } */
                   2918:     /* for (k=1; k<=nsq;k++) { /\* For single quantitative varying covariates only of the model *\/ */
                   2919:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   2920:     /*   /\* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 *\/ */
                   2921:     /*   /\* cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   2922:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][resultmodel[nres][k1]] */
                   2923:     /*   /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   2924:     /*   /\* 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]); *\/ */
                   2925:     /* } */
                   2926:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   2927:     /*   if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   2928:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   2929:     /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   2930:     /*   } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   2931:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   2932:     /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   2933:     /*   } */
                   2934:     /*   /\* 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]); *\/ */
                   2935:     /* } */
                   2936:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   2937:     /*   /\* 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]); *\/ */
                   2938:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   2939:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   2940:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   2941:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   2942:     /*         }else{ */
                   2943:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   2944:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   2945:     /*         } */
                   2946:     /*   }else{ */
                   2947:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   2948:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   2949:     /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   2950:     /*         }else{ */
                   2951:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   2952:     /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   2953:     /*         } */
                   2954:     /*   } */
                   2955:     /* } /\* End product without age *\/ */
                   2956: /* ENd of old code */
1.138     brouard  2957:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2958:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2959:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2960:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2961:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.319     brouard  2962:     /* age and covariate values of ij are in 'cov' */
1.142     brouard  2963:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2964:     
1.126     brouard  2965:     savm=oldm;
                   2966:     oldm=newm;
1.209     brouard  2967: 
                   2968:     for(j=1; j<=nlstate; j++){
                   2969:       max[j]=0.;
                   2970:       min[j]=1.;
                   2971:     }
                   2972:     for(i=1;i<=nlstate;i++){
                   2973:       sumnew=0;
                   2974:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2975:       for(j=1; j<=nlstate; j++){ 
                   2976:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2977:        max[j]=FMAX(max[j],prlim[i][j]);
                   2978:        min[j]=FMIN(min[j],prlim[i][j]);
                   2979:       }
                   2980:     }
                   2981: 
1.126     brouard  2982:     maxmax=0.;
1.209     brouard  2983:     for(j=1; j<=nlstate; j++){
                   2984:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2985:       maxmax=FMAX(maxmax,meandiff[j]);
                   2986:       /* 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  2987:     } /* j loop */
1.203     brouard  2988:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2989:     /* 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  2990:     if(maxmax < ftolpl){
1.209     brouard  2991:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2992:       free_vector(min,1,nlstate);
                   2993:       free_vector(max,1,nlstate);
                   2994:       free_vector(meandiff,1,nlstate);
1.126     brouard  2995:       return prlim;
                   2996:     }
1.288     brouard  2997:   } /* agefin loop */
1.208     brouard  2998:     /* After some age loop it doesn't converge */
1.288     brouard  2999:   if(!first){
                   3000:     first=1;
                   3001:     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  3002:     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);
                   3003:   }else if (first >=1 && first <10){
                   3004:     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);
                   3005:     first++;
                   3006:   }else if (first ==10){
                   3007:     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);
                   3008:     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");
                   3009:     fprintf(ficlog,"Warning: the stable prevalence no convergence; too many cases, giving up noticing, even in log file\n");
                   3010:     first++;
1.288     brouard  3011:   }
                   3012: 
1.209     brouard  3013:   /* 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); */
                   3014:   free_vector(min,1,nlstate);
                   3015:   free_vector(max,1,nlstate);
                   3016:   free_vector(meandiff,1,nlstate);
1.208     brouard  3017:   
1.169     brouard  3018:   return prlim; /* should not reach here */
1.126     brouard  3019: }
                   3020: 
1.217     brouard  3021: 
                   3022:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   3023: 
1.218     brouard  3024:  /* 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) */
                   3025:  /* 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  3026:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  3027: {
1.264     brouard  3028:   /* 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  3029:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   3030:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   3031:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   3032:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   3033:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   3034:   /* Initial matrix pimij */
                   3035:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   3036:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   3037:   /*  0,                   0                  , 1} */
                   3038:   /*
                   3039:    * and after some iteration: */
                   3040:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   3041:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   3042:   /*  0,                   0                  , 1} */
                   3043:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   3044:   /* {0.51571254859325999, 0.4842874514067399, */
                   3045:   /*  0.51326036147820708, 0.48673963852179264} */
                   3046:   /* If we start from prlim again, prlim tends to a constant matrix */
                   3047: 
1.332     brouard  3048:   int i, ii,j,k, k1;
1.247     brouard  3049:   int first=0;
1.217     brouard  3050:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   3051:   /* double **matprod2(); */ /* test */
                   3052:   double **out, cov[NCOVMAX+1], **bmij();
                   3053:   double **newm;
1.218     brouard  3054:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   3055:   double        **oldm, **savm;  /* for use */
                   3056: 
1.217     brouard  3057:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   3058:   int ncvloop=0;
                   3059:   
                   3060:   min=vector(1,nlstate);
                   3061:   max=vector(1,nlstate);
                   3062:   meandiff=vector(1,nlstate);
                   3063: 
1.266     brouard  3064:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   3065:   oldm=oldms; savm=savms;
                   3066:   
                   3067:   /* Starting with matrix unity */
                   3068:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   3069:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  3070:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3071:     }
                   3072:   
                   3073:   cov[1]=1.;
                   3074:   
                   3075:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3076:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  3077:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  3078:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   3079:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  3080:     ncvloop++;
1.218     brouard  3081:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   3082:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  3083:     /* Covariates have to be included here again */
                   3084:     cov[2]=agefin;
1.319     brouard  3085:     if(nagesqr==1){
1.217     brouard  3086:       cov[3]= agefin*agefin;;
1.319     brouard  3087:     }
1.332     brouard  3088:     for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   3089:       if(Typevar[k1]==1){ /* A product with age */
                   3090:        cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.242     brouard  3091:       }else{
1.332     brouard  3092:        cov[2+nagesqr+k1]=precov[nres][k1];
1.242     brouard  3093:       }
1.332     brouard  3094:     }/* End of loop on model equation */
                   3095: 
                   3096: /* Old code */ 
                   3097: 
                   3098:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   3099:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   3100:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; */
                   3101:     /*   /\* 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)); *\/ */
                   3102:     /* } */
                   3103:     /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   3104:     /* /\*   /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3105:     /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3106:     /* /\*   /\\* 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])]); *\\/ *\/ */
                   3107:     /* /\* } *\/ */
                   3108:     /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3109:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3110:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3111:     /*   /\* 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]); *\/ */
                   3112:     /* } */
                   3113:     /* /\* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; *\/ */
                   3114:     /* /\* for (k=1; k<=cptcovprod;k++) /\\* Useless *\\/ *\/ */
                   3115:     /* /\*   /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\\/ *\/ */
                   3116:     /* /\*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3117:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   3118:     /*   /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age *\\/ ERROR ???*\/ */
                   3119:     /*   if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3120:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3121:     /*   } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3122:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   3123:     /*   } */
                   3124:     /*   /\* 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]); *\/ */
                   3125:     /* } */
                   3126:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   3127:     /*   /\* 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]); *\/ */
                   3128:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3129:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3130:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3131:     /*         }else{ */
                   3132:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3133:     /*         } */
                   3134:     /*   }else{ */
                   3135:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3136:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3137:     /*         }else{ */
                   3138:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3139:     /*         } */
                   3140:     /*   } */
                   3141:     /* } */
1.217     brouard  3142:     
                   3143:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3144:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3145:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   3146:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3147:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  3148:                /* ij should be linked to the correct index of cov */
                   3149:                /* age and covariate values ij are in 'cov', but we need to pass
                   3150:                 * ij for the observed prevalence at age and status and covariate
                   3151:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   3152:                 */
                   3153:     /* 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 *\/ */
                   3154:     /* 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 *\/ */
                   3155:     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  3156:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  3157:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   3158:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   3159:     /*         printf("%d newm= ",i); */
                   3160:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3161:     /*           printf("%f ",newm[i][j]); */
                   3162:     /*         } */
                   3163:     /*         printf("oldm * "); */
                   3164:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3165:     /*           printf("%f ",oldm[i][j]); */
                   3166:     /*         } */
1.268     brouard  3167:     /*         printf(" bmmij "); */
1.266     brouard  3168:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3169:     /*           printf("%f ",pmmij[i][j]); */
                   3170:     /*         } */
                   3171:     /*         printf("\n"); */
                   3172:     /*   } */
                   3173:     /* } */
1.217     brouard  3174:     savm=oldm;
                   3175:     oldm=newm;
1.266     brouard  3176: 
1.217     brouard  3177:     for(j=1; j<=nlstate; j++){
                   3178:       max[j]=0.;
                   3179:       min[j]=1.;
                   3180:     }
                   3181:     for(j=1; j<=nlstate; j++){ 
                   3182:       for(i=1;i<=nlstate;i++){
1.234     brouard  3183:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   3184:        bprlim[i][j]= newm[i][j];
                   3185:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   3186:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  3187:       }
                   3188:     }
1.218     brouard  3189:                
1.217     brouard  3190:     maxmax=0.;
                   3191:     for(i=1; i<=nlstate; i++){
1.318     brouard  3192:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column, could be nan! */
1.217     brouard  3193:       maxmax=FMAX(maxmax,meandiff[i]);
                   3194:       /* 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  3195:     } /* i loop */
1.217     brouard  3196:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  3197:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3198:     if(maxmax < ftolpl){
1.220     brouard  3199:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3200:       free_vector(min,1,nlstate);
                   3201:       free_vector(max,1,nlstate);
                   3202:       free_vector(meandiff,1,nlstate);
                   3203:       return bprlim;
                   3204:     }
1.288     brouard  3205:   } /* agefin loop */
1.217     brouard  3206:     /* After some age loop it doesn't converge */
1.288     brouard  3207:   if(!first){
1.247     brouard  3208:     first=1;
                   3209:     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\
                   3210: 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);
                   3211:   }
                   3212:   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  3213: 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);
                   3214:   /* 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); */
                   3215:   free_vector(min,1,nlstate);
                   3216:   free_vector(max,1,nlstate);
                   3217:   free_vector(meandiff,1,nlstate);
                   3218:   
                   3219:   return bprlim; /* should not reach here */
                   3220: }
                   3221: 
1.126     brouard  3222: /*************** transition probabilities ***************/ 
                   3223: 
                   3224: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   3225: {
1.138     brouard  3226:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  3227:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  3228:      model to the ncovmodel covariates (including constant and age).
                   3229:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3230:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3231:      ncth covariate in the global vector x is given by the formula:
                   3232:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3233:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3234:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3235:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  3236:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  3237:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  3238:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  3239:   */
                   3240:   double s1, lnpijopii;
1.126     brouard  3241:   /*double t34;*/
1.164     brouard  3242:   int i,j, nc, ii, jj;
1.126     brouard  3243: 
1.223     brouard  3244:   for(i=1; i<= nlstate; i++){
                   3245:     for(j=1; j<i;j++){
                   3246:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3247:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3248:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3249:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3250:       }
                   3251:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3252:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3253:     }
                   3254:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3255:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3256:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3257:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3258:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3259:       }
                   3260:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3261:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3262:     }
                   3263:   }
1.218     brouard  3264:   
1.223     brouard  3265:   for(i=1; i<= nlstate; i++){
                   3266:     s1=0;
                   3267:     for(j=1; j<i; j++){
                   3268:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.330     brouard  3269:       /* printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1.223     brouard  3270:     }
                   3271:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3272:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.330     brouard  3273:       /* printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1.223     brouard  3274:     }
                   3275:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3276:     ps[i][i]=1./(s1+1.);
                   3277:     /* Computing other pijs */
                   3278:     for(j=1; j<i; j++)
1.325     brouard  3279:       ps[i][j]= exp(ps[i][j])*ps[i][i];/* Bug valgrind */
1.223     brouard  3280:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3281:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3282:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3283:   } /* end i */
1.218     brouard  3284:   
1.223     brouard  3285:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3286:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3287:       ps[ii][jj]=0;
                   3288:       ps[ii][ii]=1;
                   3289:     }
                   3290:   }
1.294     brouard  3291: 
                   3292: 
1.223     brouard  3293:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3294:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3295:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3296:   /*   } */
                   3297:   /*   printf("\n "); */
                   3298:   /* } */
                   3299:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3300:   /*
                   3301:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  3302:                goto end;*/
1.266     brouard  3303:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  3304: }
                   3305: 
1.218     brouard  3306: /*************** backward transition probabilities ***************/ 
                   3307: 
                   3308:  /* 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 ) */
                   3309: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   3310:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   3311: {
1.302     brouard  3312:   /* 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  3313:    * 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  3314:    */
1.218     brouard  3315:   int i, ii, j,k;
1.222     brouard  3316:   
                   3317:   double **out, **pmij();
                   3318:   double sumnew=0.;
1.218     brouard  3319:   double agefin;
1.292     brouard  3320:   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  3321:   double **dnewm, **dsavm, **doldm;
                   3322:   double **bbmij;
                   3323:   
1.218     brouard  3324:   doldm=ddoldms; /* global pointers */
1.222     brouard  3325:   dnewm=ddnewms;
                   3326:   dsavm=ddsavms;
1.318     brouard  3327: 
                   3328:   /* Debug */
                   3329:   /* printf("Bmij ij=%d, cov[2}=%f\n", ij, cov[2]); */
1.222     brouard  3330:   agefin=cov[2];
1.268     brouard  3331:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  3332:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  3333:      the observed prevalence (with this covariate ij) at beginning of transition */
                   3334:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  3335: 
                   3336:   /* P_x */
1.325     brouard  3337:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm *//* Bug valgrind */
1.268     brouard  3338:   /* outputs pmmij which is a stochastic matrix in row */
                   3339: 
                   3340:   /* Diag(w_x) */
1.292     brouard  3341:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  3342:   sumnew=0.;
1.269     brouard  3343:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  3344:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  3345:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  3346:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   3347:   }
                   3348:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   3349:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3350:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  3351:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  3352:     }
                   3353:   }else{
                   3354:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3355:       for (j=1;j<=nlstate+ndeath;j++)
                   3356:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   3357:     }
                   3358:     /* if(sumnew <0.9){ */
                   3359:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   3360:     /* } */
                   3361:   }
                   3362:   k3=0.0;  /* We put the last diagonal to 0 */
                   3363:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   3364:       doldm[ii][ii]= k3;
                   3365:   }
                   3366:   /* End doldm, At the end doldm is diag[(w_i)] */
                   3367:   
1.292     brouard  3368:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   3369:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  3370: 
1.292     brouard  3371:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  3372:   /* 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  3373:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  3374:     sumnew=0.;
1.222     brouard  3375:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  3376:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  3377:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  3378:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  3379:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  3380:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  3381:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3382:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  3383:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3384:        /* }else */
1.268     brouard  3385:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   3386:     } /*End ii */
                   3387:   } /* 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 */
                   3388: 
1.292     brouard  3389:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  3390:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  3391:   /* end bmij */
1.266     brouard  3392:   return ps; /*pointer is unchanged */
1.218     brouard  3393: }
1.217     brouard  3394: /*************** transition probabilities ***************/ 
                   3395: 
1.218     brouard  3396: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  3397: {
                   3398:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3399:      computes the probability to be observed in state j being in state i by appying the
                   3400:      model to the ncovmodel covariates (including constant and age).
                   3401:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3402:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3403:      ncth covariate in the global vector x is given by the formula:
                   3404:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3405:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3406:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3407:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3408:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   3409:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3410:   */
                   3411:   double s1, lnpijopii;
                   3412:   /*double t34;*/
                   3413:   int i,j, nc, ii, jj;
                   3414: 
1.234     brouard  3415:   for(i=1; i<= nlstate; i++){
                   3416:     for(j=1; j<i;j++){
                   3417:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3418:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3419:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3420:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3421:       }
                   3422:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3423:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3424:     }
                   3425:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3426:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3427:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3428:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3429:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3430:       }
                   3431:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3432:     }
                   3433:   }
                   3434:   
                   3435:   for(i=1; i<= nlstate; i++){
                   3436:     s1=0;
                   3437:     for(j=1; j<i; j++){
                   3438:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3439:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3440:     }
                   3441:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3442:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3443:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3444:     }
                   3445:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3446:     ps[i][i]=1./(s1+1.);
                   3447:     /* Computing other pijs */
                   3448:     for(j=1; j<i; j++)
                   3449:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3450:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3451:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3452:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3453:   } /* end i */
                   3454:   
                   3455:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3456:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3457:       ps[ii][jj]=0;
                   3458:       ps[ii][ii]=1;
                   3459:     }
                   3460:   }
1.296     brouard  3461:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  3462:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3463:     s1=0.;
                   3464:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   3465:       s1+=ps[ii][jj];
                   3466:     }
                   3467:     for(ii=1; ii<= nlstate; ii++){
                   3468:       ps[ii][jj]=ps[ii][jj]/s1;
                   3469:     }
                   3470:   }
                   3471:   /* Transposition */
                   3472:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3473:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   3474:       s1=ps[ii][jj];
                   3475:       ps[ii][jj]=ps[jj][ii];
                   3476:       ps[jj][ii]=s1;
                   3477:     }
                   3478:   }
                   3479:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3480:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3481:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3482:   /*   } */
                   3483:   /*   printf("\n "); */
                   3484:   /* } */
                   3485:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3486:   /*
                   3487:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3488:     goto end;*/
                   3489:   return ps;
1.217     brouard  3490: }
                   3491: 
                   3492: 
1.126     brouard  3493: /**************** Product of 2 matrices ******************/
                   3494: 
1.145     brouard  3495: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  3496: {
                   3497:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3498:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3499:   /* in, b, out are matrice of pointers which should have been initialized 
                   3500:      before: only the contents of out is modified. The function returns
                   3501:      a pointer to pointers identical to out */
1.145     brouard  3502:   int i, j, k;
1.126     brouard  3503:   for(i=nrl; i<= nrh; i++)
1.145     brouard  3504:     for(k=ncolol; k<=ncoloh; k++){
                   3505:       out[i][k]=0.;
                   3506:       for(j=ncl; j<=nch; j++)
                   3507:        out[i][k] +=in[i][j]*b[j][k];
                   3508:     }
1.126     brouard  3509:   return out;
                   3510: }
                   3511: 
                   3512: 
                   3513: /************* Higher Matrix Product ***************/
                   3514: 
1.235     brouard  3515: 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  3516: {
1.336     brouard  3517:   /* Already optimized with precov.
                   3518:      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  3519:      'nhstepm*hstepm*stepm' months (i.e. until
                   3520:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3521:      nhstepm*hstepm matrices. 
                   3522:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3523:      (typically every 2 years instead of every month which is too big 
                   3524:      for the memory).
                   3525:      Model is determined by parameters x and covariates have to be 
                   3526:      included manually here. 
                   3527: 
                   3528:      */
                   3529: 
1.330     brouard  3530:   int i, j, d, h, k, k1;
1.131     brouard  3531:   double **out, cov[NCOVMAX+1];
1.126     brouard  3532:   double **newm;
1.187     brouard  3533:   double agexact;
1.214     brouard  3534:   double agebegin, ageend;
1.126     brouard  3535: 
                   3536:   /* Hstepm could be zero and should return the unit matrix */
                   3537:   for (i=1;i<=nlstate+ndeath;i++)
                   3538:     for (j=1;j<=nlstate+ndeath;j++){
                   3539:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3540:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3541:     }
                   3542:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3543:   for(h=1; h <=nhstepm; h++){
                   3544:     for(d=1; d <=hstepm; d++){
                   3545:       newm=savm;
                   3546:       /* Covariates have to be included here again */
                   3547:       cov[1]=1.;
1.214     brouard  3548:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3549:       cov[2]=agexact;
1.319     brouard  3550:       if(nagesqr==1){
1.227     brouard  3551:        cov[3]= agexact*agexact;
1.319     brouard  3552:       }
1.330     brouard  3553:       /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   3554:       /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   3555:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.332     brouard  3556:        if(Typevar[k1]==1){ /* A product with age */
                   3557:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   3558:        }else{
                   3559:          cov[2+nagesqr+k1]=precov[nres][k1];
                   3560:        }
                   3561:       }/* End of loop on model equation */
                   3562:        /* Old code */ 
                   3563: /*     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /\* Single dummy  *\/ */
                   3564: /* /\*    V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) *\/ */
                   3565: /* /\*       for (k=1; k<=nsd;k++) { /\\* For single dummy covariates only *\\/ *\/ */
                   3566: /* /\* /\\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\\/ *\/ */
                   3567: /*     /\* codtabm(ij,k)  (1 & (ij-1) >> (k-1))+1 *\/ */
                   3568: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3569: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3570: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
                   3571: /* /\*    nsd         1   2                              3 *\/ /\* Counting single dummies covar fixed or tv *\/ */
                   3572: /* /\*TvarsD[nsd]     4   3                              1 *\/ /\* ID of single dummy cova fixed or timevary*\/ */
                   3573: /* /\*TvarsDind[k]    2   3                              9 *\/ /\* position K of single dummy cova *\/ */
                   3574: /*       /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];or [codtabm(ij,TnsdVar[TvarsD[k]] *\/ */
                   3575: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]]; */
                   3576: /*       /\* 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]])); *\/ */
                   3577: /*       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); */
                   3578: /*       printf("hpxij new Dummy precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3579: /*     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /\* Single quantitative variables  *\/ */
                   3580: /*       /\* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline *\/ */
                   3581: /*       cov[2+nagesqr+k1]=Tqresult[nres][resultmodel[nres][k1]];  */
                   3582: /*       /\* for (k=1; k<=nsq;k++) { /\\* For single varying covariates only *\\/ *\/ */
                   3583: /*       /\*   /\\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\\/ *\/ */
                   3584: /*       /\*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   3585: /*       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]]); */
                   3586: /*       printf("hpxij new Quanti precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3587: /*     }else if( Dummy[k1]==2 ){ /\* For dummy with age product *\/ */
                   3588: /*       /\* Tvar[k1] Variable in the age product age*V1 is 1 *\/ */
                   3589: /*       /\* [Tinvresult[nres][V1] is its value in the resultline nres *\/ */
                   3590: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvar[k1]]*cov[2]; */
                   3591: /*       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]); */
                   3592: /*       printf("hpxij new Dummy with age product precov[nres=%d][k1=%d]=%.4f * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3593: 
                   3594: /*       /\* cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];    *\/ */
                   3595: /*       /\* for (k=1; k<=cptcovage;k++){ /\\* For product with age V1+V1*age +V4 +age*V3 *\\/ *\/ */
                   3596: /*       /\* 1+2 Tage[1]=2 TVar[2]=1 Dummy[2]=2, Tage[2]=4 TVar[4]=3 Dummy[4]=3 quant*\/ */
                   3597: /*       /\* *\/ */
1.330     brouard  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 *\/ */
1.332     brouard  3601: /* /\*cptcovage=2                   1               2      *\/ */
                   3602: /* /\*Tage[k]=                      5               8      *\/  */
                   3603: /*     }else if( Dummy[k1]==3 ){ /\* For quant with age product *\/ */
                   3604: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];        */
                   3605: /*       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]]); */
                   3606: /*       printf("hpxij new Quanti with age product precov[nres=%d][k1=%d] * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3607: /*       /\* if(Dummy[Tage[k]]== 2){ /\\* dummy with age *\\/ *\/ */
                   3608: /*       /\* /\\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\\* dummy with age *\\\/ *\\/ *\/ */
                   3609: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\\/ *\/ */
                   3610: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\\/ *\/ */
                   3611: /*       /\*   cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\/ */
                   3612: /*       /\*   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); *\/ */
                   3613: /*       /\* } else if(Dummy[Tage[k]]== 3){ /\\* quantitative with age *\\/ *\/ */
                   3614: /*       /\*   cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; *\/ */
                   3615: /*       /\* } *\/ */
                   3616: /*       /\* 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]); *\/ */
                   3617: /*     }else if(Typevar[k1]==2 ){ /\* For product (not with age) *\/ */
                   3618: /* /\*       for (k=1; k<=cptcovprod;k++){ /\\*  For product without age *\\/ *\/ */
                   3619: /* /\* /\\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\\/ *\/ */
                   3620: /* /\* /\\*    k        1  2   3   4     5    6    7     8    9 *\\/ *\/ */
                   3621: /* /\* /\\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\\/ *\/ */
                   3622: /* /\* /\\*cptcovprod=1            1               2            *\\/ *\/ */
                   3623: /* /\* /\\*Tprod[]=                4               7            *\\/ *\/ */
                   3624: /* /\* /\\*Tvard[][1]             4               1             *\\/ *\/ */
                   3625: /* /\* /\\*Tvard[][2]               3               2           *\\/ *\/ */
1.330     brouard  3626:          
1.332     brouard  3627: /*       /\* 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])]); *\/ */
                   3628: /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3629: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];     */
                   3630: /*       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]]); */
                   3631: /*       printf("hpxij new Product no age product precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3632: 
                   3633: /*       /\* if(Dummy[Tvardk[k1][1]]==0){ *\/ */
                   3634: /*       /\*   if(Dummy[Tvardk[k1][2]]==0){ /\\* Product of dummies *\\/ *\/ */
                   3635: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3636: /*           /\* cov[2+nagesqr+k1]=Tinvresult[nres][Tvardk[k1][1]] * Tinvresult[nres][Tvardk[k1][2]];   *\/ */
                   3637: /*           /\* 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]])]; *\/ */
                   3638: /*         /\* }else{ /\\* Product of dummy by quantitative *\\/ *\/ */
                   3639: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,TnsdVar[Tvard[k][1]])] * Tqresult[nres][k]; *\/ */
                   3640: /*           /\* cov[2+nagesqr+k1]=Tresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]; *\/ */
                   3641: /*       /\*   } *\/ */
                   3642: /*       /\* }else{ /\\* Product of quantitative by...*\\/ *\/ */
                   3643: /*       /\*   if(Dummy[Tvard[k][2]]==0){  /\\* quant by dummy *\\/ *\/ */
                   3644: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][Tvard[k][1]]; *\\/ *\/ */
                   3645: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3646: /*       /\*   }else{ /\\* Product of two quant *\\/ *\/ */
                   3647: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\\/ *\/ */
                   3648: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3649: /*       /\*   } *\/ */
                   3650: /*       /\* }/\\*end of products quantitative *\\/ *\/ */
                   3651: /*     }/\*end of products *\/ */
                   3652:       /* } /\* End of loop on model equation *\/ */
1.235     brouard  3653:       /* for (k=1; k<=cptcovn;k++)  */
                   3654:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3655:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3656:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3657:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3658:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3659:       
                   3660:       
1.126     brouard  3661:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3662:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.319     brouard  3663:       /* right multiplication of oldm by the current matrix */
1.126     brouard  3664:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3665:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3666:       /* if((int)age == 70){ */
                   3667:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3668:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3669:       /*         printf("%d pmmij ",i); */
                   3670:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3671:       /*           printf("%f ",pmmij[i][j]); */
                   3672:       /*         } */
                   3673:       /*         printf(" oldm "); */
                   3674:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3675:       /*           printf("%f ",oldm[i][j]); */
                   3676:       /*         } */
                   3677:       /*         printf("\n"); */
                   3678:       /*       } */
                   3679:       /* } */
1.126     brouard  3680:       savm=oldm;
                   3681:       oldm=newm;
                   3682:     }
                   3683:     for(i=1; i<=nlstate+ndeath; i++)
                   3684:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  3685:        po[i][j][h]=newm[i][j];
                   3686:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3687:       }
1.128     brouard  3688:     /*printf("h=%d ",h);*/
1.126     brouard  3689:   } /* end h */
1.267     brouard  3690:   /*     printf("\n H=%d \n",h); */
1.126     brouard  3691:   return po;
                   3692: }
                   3693: 
1.217     brouard  3694: /************* Higher Back Matrix Product ***************/
1.218     brouard  3695: /* 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  3696: 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  3697: {
1.332     brouard  3698:   /* For dummy covariates given in each resultline (for historical, computes the corresponding combination ij),
                   3699:      computes the transition matrix starting at age 'age' over
1.217     brouard  3700:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3701:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3702:      nhstepm*hstepm matrices.
                   3703:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3704:      (typically every 2 years instead of every month which is too big
1.217     brouard  3705:      for the memory).
1.218     brouard  3706:      Model is determined by parameters x and covariates have to be
1.266     brouard  3707:      included manually here. Then we use a call to bmij(x and cov)
                   3708:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  3709:   */
1.217     brouard  3710: 
1.332     brouard  3711:   int i, j, d, h, k, k1;
1.266     brouard  3712:   double **out, cov[NCOVMAX+1], **bmij();
                   3713:   double **newm, ***newmm;
1.217     brouard  3714:   double agexact;
                   3715:   double agebegin, ageend;
1.222     brouard  3716:   double **oldm, **savm;
1.217     brouard  3717: 
1.266     brouard  3718:   newmm=po; /* To be saved */
                   3719:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  3720:   /* Hstepm could be zero and should return the unit matrix */
                   3721:   for (i=1;i<=nlstate+ndeath;i++)
                   3722:     for (j=1;j<=nlstate+ndeath;j++){
                   3723:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3724:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3725:     }
                   3726:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3727:   for(h=1; h <=nhstepm; h++){
                   3728:     for(d=1; d <=hstepm; d++){
                   3729:       newm=savm;
                   3730:       /* Covariates have to be included here again */
                   3731:       cov[1]=1.;
1.271     brouard  3732:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  3733:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
1.318     brouard  3734:         /* Debug */
                   3735:       /* printf("hBxij age=%lf, agexact=%lf\n", age, agexact); */
1.217     brouard  3736:       cov[2]=agexact;
1.332     brouard  3737:       if(nagesqr==1){
1.222     brouard  3738:        cov[3]= agexact*agexact;
1.332     brouard  3739:       }
                   3740:       /** New code */
                   3741:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   3742:        if(Typevar[k1]==1){ /* A product with age */
                   3743:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.325     brouard  3744:        }else{
1.332     brouard  3745:          cov[2+nagesqr+k1]=precov[nres][k1];
1.325     brouard  3746:        }
1.332     brouard  3747:       }/* End of loop on model equation */
                   3748:       /** End of new code */
                   3749:   /** This was old code */
                   3750:       /* for (k=1; k<=nsd;k++){ /\* For single dummy covariates only *\//\* cptcovn error *\/ */
                   3751:       /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3752:       /* /\* /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3753:       /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])];/\* Bug valgrind *\/ */
                   3754:       /*   /\* 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)); *\/ */
                   3755:       /* } */
                   3756:       /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3757:       /*       /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3758:       /*       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3759:       /*       /\* 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]); *\/ */
                   3760:       /* } */
                   3761:       /* for (k=1; k<=cptcovage;k++){ /\* Should start at cptcovn+1 *\//\* For product with age *\/ */
                   3762:       /*       /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age error!!!*\\/ *\/ */
                   3763:       /*       if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3764:       /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3765:       /*       } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3766:       /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];  */
                   3767:       /*       } */
                   3768:       /*       /\* 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]); *\/ */
                   3769:       /* } */
                   3770:       /* for (k=1; k<=cptcovprod;k++){ /\* Useless because included in cptcovn *\/ */
                   3771:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3772:       /*       if(Dummy[Tvard[k][1]]==0){ */
                   3773:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3774:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][1])]; */
                   3775:       /*         }else{ */
                   3776:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3777:       /*         } */
                   3778:       /*       }else{ */
                   3779:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3780:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3781:       /*         }else{ */
                   3782:       /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3783:       /*         } */
                   3784:       /*       } */
                   3785:       /* }                      */
                   3786:       /* /\*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*\/ */
                   3787:       /* /\*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*\/ */
                   3788: /** End of old code */
                   3789:       
1.218     brouard  3790:       /* Careful transposed matrix */
1.266     brouard  3791:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  3792:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3793:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3794:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.325     brouard  3795:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);/* Bug valgrind */
1.217     brouard  3796:       /* if((int)age == 70){ */
                   3797:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3798:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3799:       /*         printf("%d pmmij ",i); */
                   3800:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3801:       /*           printf("%f ",pmmij[i][j]); */
                   3802:       /*         } */
                   3803:       /*         printf(" oldm "); */
                   3804:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3805:       /*           printf("%f ",oldm[i][j]); */
                   3806:       /*         } */
                   3807:       /*         printf("\n"); */
                   3808:       /*       } */
                   3809:       /* } */
                   3810:       savm=oldm;
                   3811:       oldm=newm;
                   3812:     }
                   3813:     for(i=1; i<=nlstate+ndeath; i++)
                   3814:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3815:        po[i][j][h]=newm[i][j];
1.268     brouard  3816:        /* if(h==nhstepm) */
                   3817:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  3818:       }
1.268     brouard  3819:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  3820:   } /* end h */
1.268     brouard  3821:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  3822:   return po;
                   3823: }
                   3824: 
                   3825: 
1.162     brouard  3826: #ifdef NLOPT
                   3827:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3828:   double fret;
                   3829:   double *xt;
                   3830:   int j;
                   3831:   myfunc_data *d2 = (myfunc_data *) pd;
                   3832: /* xt = (p1-1); */
                   3833:   xt=vector(1,n); 
                   3834:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3835: 
                   3836:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3837:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3838:   printf("Function = %.12lf ",fret);
                   3839:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3840:   printf("\n");
                   3841:  free_vector(xt,1,n);
                   3842:   return fret;
                   3843: }
                   3844: #endif
1.126     brouard  3845: 
                   3846: /*************** log-likelihood *************/
                   3847: double func( double *x)
                   3848: {
1.336     brouard  3849:   int i, ii, j, k, mi, d, kk, kf=0;
1.226     brouard  3850:   int ioffset=0;
                   3851:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3852:   double **out;
                   3853:   double lli; /* Individual log likelihood */
                   3854:   int s1, s2;
1.228     brouard  3855:   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  3856: 
1.226     brouard  3857:   double bbh, survp;
                   3858:   double agexact;
1.336     brouard  3859:   double agebegin, ageend;
1.226     brouard  3860:   /*extern weight */
                   3861:   /* We are differentiating ll according to initial status */
                   3862:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3863:   /*for(i=1;i<imx;i++) 
                   3864:     printf(" %d\n",s[4][i]);
                   3865:   */
1.162     brouard  3866: 
1.226     brouard  3867:   ++countcallfunc;
1.162     brouard  3868: 
1.226     brouard  3869:   cov[1]=1.;
1.126     brouard  3870: 
1.226     brouard  3871:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3872:   ioffset=0;
1.226     brouard  3873:   if(mle==1){
                   3874:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3875:       /* Computes the values of the ncovmodel covariates of the model
                   3876:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3877:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   3878:         to be observed in j being in i according to the model.
                   3879:       */
1.243     brouard  3880:       ioffset=2+nagesqr ;
1.233     brouard  3881:    /* Fixed */
1.336     brouard  3882:       for (kf=1; kf<=ncovf;kf++){ /* For each fixed covariate dummu or quant or prod */
1.319     brouard  3883:        /* # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi */
                   3884:         /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   3885:        /*  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  3886:         /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.336     brouard  3887:        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  3888:        /* V1*V2 (7)  TvarFind[2]=7, TvarFind[3]=9 */
1.234     brouard  3889:       }
1.226     brouard  3890:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.319     brouard  3891:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
1.226     brouard  3892:         has been calculated etc */
                   3893:       /* For an individual i, wav[i] gives the number of effective waves */
                   3894:       /* We compute the contribution to Likelihood of each effective transition
                   3895:         mw[mi][i] is real wave of the mi th effectve wave */
                   3896:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   3897:         s2=s[mw[mi+1][i]][i];
                   3898:         And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
                   3899:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   3900:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   3901:       */
1.336     brouard  3902:       for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
                   3903:       /* Wave varying (but not age varying) */
1.319     brouard  3904:        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*/
                   3905:          /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; but where is the crossproduct? */
1.242     brouard  3906:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
1.234     brouard  3907:        }
                   3908:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3909:          for (j=1;j<=nlstate+ndeath;j++){
                   3910:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3911:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3912:          }
1.336     brouard  3913: 
                   3914:        agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   3915:        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  3916:        for(d=0; d<dh[mi][i]; d++){
                   3917:          newm=savm;
                   3918:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3919:          cov[2]=agexact;
                   3920:          if(nagesqr==1)
                   3921:            cov[3]= agexact*agexact;  /* Should be changed here */
                   3922:          for (kk=1; kk<=cptcovage;kk++) {
1.318     brouard  3923:            if(!FixedV[Tvar[Tage[kk]]])
                   3924:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   3925:            else
                   3926:              cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
1.234     brouard  3927:          }
                   3928:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3929:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3930:          savm=oldm;
                   3931:          oldm=newm;
                   3932:        } /* end mult */
                   3933:        
                   3934:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   3935:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   3936:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   3937:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   3938:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   3939:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   3940:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   3941:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  3942:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   3943:                                 * -stepm/2 to stepm/2 .
                   3944:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   3945:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   3946:                                 */
1.234     brouard  3947:        s1=s[mw[mi][i]][i];
                   3948:        s2=s[mw[mi+1][i]][i];
                   3949:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3950:        /* bias bh is positive if real duration
                   3951:         * is higher than the multiple of stepm and negative otherwise.
                   3952:         */
                   3953:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   3954:        if( s2 > nlstate){ 
                   3955:          /* i.e. if s2 is a death state and if the date of death is known 
                   3956:             then the contribution to the likelihood is the probability to 
                   3957:             die between last step unit time and current  step unit time, 
                   3958:             which is also equal to probability to die before dh 
                   3959:             minus probability to die before dh-stepm . 
                   3960:             In version up to 0.92 likelihood was computed
                   3961:             as if date of death was unknown. Death was treated as any other
                   3962:             health state: the date of the interview describes the actual state
                   3963:             and not the date of a change in health state. The former idea was
                   3964:             to consider that at each interview the state was recorded
                   3965:             (healthy, disable or death) and IMaCh was corrected; but when we
                   3966:             introduced the exact date of death then we should have modified
                   3967:             the contribution of an exact death to the likelihood. This new
                   3968:             contribution is smaller and very dependent of the step unit
                   3969:             stepm. It is no more the probability to die between last interview
                   3970:             and month of death but the probability to survive from last
                   3971:             interview up to one month before death multiplied by the
                   3972:             probability to die within a month. Thanks to Chris
                   3973:             Jackson for correcting this bug.  Former versions increased
                   3974:             mortality artificially. The bad side is that we add another loop
                   3975:             which slows down the processing. The difference can be up to 10%
                   3976:             lower mortality.
                   3977:          */
                   3978:          /* If, at the beginning of the maximization mostly, the
                   3979:             cumulative probability or probability to be dead is
                   3980:             constant (ie = 1) over time d, the difference is equal to
                   3981:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   3982:             s1 at precedent wave, to be dead a month before current
                   3983:             wave is equal to probability, being at state s1 at
                   3984:             precedent wave, to be dead at mont of the current
                   3985:             wave. Then the observed probability (that this person died)
                   3986:             is null according to current estimated parameter. In fact,
                   3987:             it should be very low but not zero otherwise the log go to
                   3988:             infinity.
                   3989:          */
1.183     brouard  3990: /* #ifdef INFINITYORIGINAL */
                   3991: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3992: /* #else */
                   3993: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   3994: /*         lli=log(mytinydouble); */
                   3995: /*       else */
                   3996: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3997: /* #endif */
1.226     brouard  3998:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3999:          
1.226     brouard  4000:        } else if  ( s2==-1 ) { /* alive */
                   4001:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4002:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4003:          /*survp += out[s1][j]; */
                   4004:          lli= log(survp);
                   4005:        }
1.336     brouard  4006:        /* else if  (s2==-4) {  */
                   4007:        /*   for (j=3,survp=0. ; j<=nlstate; j++)   */
                   4008:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4009:        /*   lli= log(survp);  */
                   4010:        /* }  */
                   4011:        /* else if  (s2==-5) {  */
                   4012:        /*   for (j=1,survp=0. ; j<=2; j++)   */
                   4013:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4014:        /*   lli= log(survp);  */
                   4015:        /* }  */
1.226     brouard  4016:        else{
                   4017:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4018:          /*  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 */
                   4019:        } 
                   4020:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   4021:        /*if(lli ==000.0)*/
                   4022:        /*printf("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); */
                   4023:        ipmx +=1;
                   4024:        sw += weight[i];
                   4025:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4026:        /* if (lli < log(mytinydouble)){ */
                   4027:        /*   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); */
                   4028:        /*   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]); */
                   4029:        /* } */
                   4030:       } /* end of wave */
                   4031:     } /* end of individual */
                   4032:   }  else if(mle==2){
                   4033:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.319     brouard  4034:       ioffset=2+nagesqr ;
                   4035:       for (k=1; k<=ncovf;k++)
                   4036:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];
1.226     brouard  4037:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  4038:        for(k=1; k <= ncovv ; k++){
                   4039:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
                   4040:        }
1.226     brouard  4041:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4042:          for (j=1;j<=nlstate+ndeath;j++){
                   4043:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4044:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4045:          }
                   4046:        for(d=0; d<=dh[mi][i]; d++){
                   4047:          newm=savm;
                   4048:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4049:          cov[2]=agexact;
                   4050:          if(nagesqr==1)
                   4051:            cov[3]= agexact*agexact;
                   4052:          for (kk=1; kk<=cptcovage;kk++) {
                   4053:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4054:          }
                   4055:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4056:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4057:          savm=oldm;
                   4058:          oldm=newm;
                   4059:        } /* end mult */
                   4060:       
                   4061:        s1=s[mw[mi][i]][i];
                   4062:        s2=s[mw[mi+1][i]][i];
                   4063:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4064:        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 */
                   4065:        ipmx +=1;
                   4066:        sw += weight[i];
                   4067:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4068:       } /* end of wave */
                   4069:     } /* end of individual */
                   4070:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   4071:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4072:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4073:       for(mi=1; mi<= wav[i]-1; mi++){
                   4074:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4075:          for (j=1;j<=nlstate+ndeath;j++){
                   4076:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4077:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4078:          }
                   4079:        for(d=0; d<dh[mi][i]; d++){
                   4080:          newm=savm;
                   4081:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4082:          cov[2]=agexact;
                   4083:          if(nagesqr==1)
                   4084:            cov[3]= agexact*agexact;
                   4085:          for (kk=1; kk<=cptcovage;kk++) {
                   4086:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4087:          }
                   4088:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4089:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4090:          savm=oldm;
                   4091:          oldm=newm;
                   4092:        } /* end mult */
                   4093:       
                   4094:        s1=s[mw[mi][i]][i];
                   4095:        s2=s[mw[mi+1][i]][i];
                   4096:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4097:        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 */
                   4098:        ipmx +=1;
                   4099:        sw += weight[i];
                   4100:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4101:       } /* end of wave */
                   4102:     } /* end of individual */
                   4103:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   4104:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4105:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4106:       for(mi=1; mi<= wav[i]-1; mi++){
                   4107:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4108:          for (j=1;j<=nlstate+ndeath;j++){
                   4109:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4110:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4111:          }
                   4112:        for(d=0; d<dh[mi][i]; d++){
                   4113:          newm=savm;
                   4114:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4115:          cov[2]=agexact;
                   4116:          if(nagesqr==1)
                   4117:            cov[3]= agexact*agexact;
                   4118:          for (kk=1; kk<=cptcovage;kk++) {
                   4119:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4120:          }
1.126     brouard  4121:        
1.226     brouard  4122:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4123:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4124:          savm=oldm;
                   4125:          oldm=newm;
                   4126:        } /* end mult */
                   4127:       
                   4128:        s1=s[mw[mi][i]][i];
                   4129:        s2=s[mw[mi+1][i]][i];
                   4130:        if( s2 > nlstate){ 
                   4131:          lli=log(out[s1][s2] - savm[s1][s2]);
                   4132:        } else if  ( s2==-1 ) { /* alive */
                   4133:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4134:            survp += out[s1][j];
                   4135:          lli= log(survp);
                   4136:        }else{
                   4137:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4138:        }
                   4139:        ipmx +=1;
                   4140:        sw += weight[i];
                   4141:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.126     brouard  4142: /*     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  4143:       } /* end of wave */
                   4144:     } /* end of individual */
                   4145:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   4146:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4147:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4148:       for(mi=1; mi<= wav[i]-1; mi++){
                   4149:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4150:          for (j=1;j<=nlstate+ndeath;j++){
                   4151:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4152:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4153:          }
                   4154:        for(d=0; d<dh[mi][i]; d++){
                   4155:          newm=savm;
                   4156:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4157:          cov[2]=agexact;
                   4158:          if(nagesqr==1)
                   4159:            cov[3]= agexact*agexact;
                   4160:          for (kk=1; kk<=cptcovage;kk++) {
                   4161:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4162:          }
1.126     brouard  4163:        
1.226     brouard  4164:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4165:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4166:          savm=oldm;
                   4167:          oldm=newm;
                   4168:        } /* end mult */
                   4169:       
                   4170:        s1=s[mw[mi][i]][i];
                   4171:        s2=s[mw[mi+1][i]][i];
                   4172:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4173:        ipmx +=1;
                   4174:        sw += weight[i];
                   4175:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4176:        /*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]);*/
                   4177:       } /* end of wave */
                   4178:     } /* end of individual */
                   4179:   } /* End of if */
                   4180:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   4181:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   4182:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4183:   return -l;
1.126     brouard  4184: }
                   4185: 
                   4186: /*************** log-likelihood *************/
                   4187: double funcone( double *x)
                   4188: {
1.228     brouard  4189:   /* Same as func but slower because of a lot of printf and if */
1.335     brouard  4190:   int i, ii, j, k, mi, d, kk, kf=0;
1.228     brouard  4191:   int ioffset=0;
1.131     brouard  4192:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  4193:   double **out;
                   4194:   double lli; /* Individual log likelihood */
                   4195:   double llt;
                   4196:   int s1, s2;
1.228     brouard  4197:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   4198: 
1.126     brouard  4199:   double bbh, survp;
1.187     brouard  4200:   double agexact;
1.214     brouard  4201:   double agebegin, ageend;
1.126     brouard  4202:   /*extern weight */
                   4203:   /* We are differentiating ll according to initial status */
                   4204:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   4205:   /*for(i=1;i<imx;i++) 
                   4206:     printf(" %d\n",s[4][i]);
                   4207:   */
                   4208:   cov[1]=1.;
                   4209: 
                   4210:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  4211:   ioffset=0;
                   4212:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.336     brouard  4213:     /* Computes the values of the ncovmodel covariates of the model
                   4214:        depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   4215:        Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   4216:        to be observed in j being in i according to the model.
                   4217:     */
1.243     brouard  4218:     /* ioffset=2+nagesqr+cptcovage; */
                   4219:     ioffset=2+nagesqr;
1.232     brouard  4220:     /* Fixed */
1.224     brouard  4221:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  4222:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
1.335     brouard  4223:     for (kf=1; kf<=ncovf;kf++){ /* Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
                   4224:       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  4225: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   4226: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   4227: /*    cov[2+6]=covar[2][i]; V2  */
                   4228: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   4229: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   4230: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   4231: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   4232: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   4233: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  4234:     }
1.336     brouard  4235:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   4236:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
                   4237:         has been calculated etc */
                   4238:       /* For an individual i, wav[i] gives the number of effective waves */
                   4239:       /* We compute the contribution to Likelihood of each effective transition
                   4240:         mw[mi][i] is real wave of the mi th effectve wave */
                   4241:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   4242:         s2=s[mw[mi+1][i]][i];
                   4243:         And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
                   4244:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   4245:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   4246:       */
                   4247:     /* This part may be useless now because everythin should be in covar */
1.232     brouard  4248:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   4249:     /*   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?)*\/ */
                   4250:     /* } */
1.231     brouard  4251:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   4252:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   4253:     /* } */
1.225     brouard  4254:     
1.233     brouard  4255: 
                   4256:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.232     brouard  4257:     /* Wave varying (but not age varying) */
                   4258:       for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242     brouard  4259:        /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
                   4260:        cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
                   4261:       }
1.232     brouard  4262:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
1.242     brouard  4263:       /* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4264:       /* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
                   4265:       /* k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
                   4266:       /* cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
                   4267:       /* 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]); */
1.232     brouard  4268:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  4269:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4270:       /*       /\* 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]); *\/ */
                   4271:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  4272:       /* } */
1.126     brouard  4273:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  4274:        for (j=1;j<=nlstate+ndeath;j++){
                   4275:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4276:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4277:        }
1.214     brouard  4278:       
                   4279:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4280:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   4281:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  4282:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  4283:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4284:          and mw[mi+1][i]. dh depends on stepm.*/
                   4285:        newm=savm;
1.247     brouard  4286:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  4287:        cov[2]=agexact;
                   4288:        if(nagesqr==1)
                   4289:          cov[3]= agexact*agexact;
                   4290:        for (kk=1; kk<=cptcovage;kk++) {
                   4291:          if(!FixedV[Tvar[Tage[kk]]])
                   4292:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4293:          else
                   4294:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
                   4295:        }
                   4296:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   4297:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4298:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4299:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4300:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   4301:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   4302:        savm=oldm;
                   4303:        oldm=newm;
1.126     brouard  4304:       } /* end mult */
1.336     brouard  4305:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   4306:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   4307:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   4308:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   4309:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   4310:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   4311:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   4312:         * probability in order to take into account the bias as a fraction of the way
                   4313:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   4314:                                 * -stepm/2 to stepm/2 .
                   4315:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   4316:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   4317:                                 */
1.126     brouard  4318:       s1=s[mw[mi][i]][i];
                   4319:       s2=s[mw[mi+1][i]][i];
1.217     brouard  4320:       /* if(s2==-1){ */
1.268     brouard  4321:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  4322:       /*       /\* exit(1); *\/ */
                   4323:       /* } */
1.126     brouard  4324:       bbh=(double)bh[mi][i]/(double)stepm; 
                   4325:       /* bias is positive if real duration
                   4326:        * is higher than the multiple of stepm and negative otherwise.
                   4327:        */
                   4328:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  4329:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4330:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  4331:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   4332:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4333:        lli= log(survp);
1.126     brouard  4334:       }else if (mle==1){
1.242     brouard  4335:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  4336:       } else if(mle==2){
1.242     brouard  4337:        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  4338:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  4339:        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  4340:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  4341:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  4342:       } else{  /* mle=0 back to 1 */
1.242     brouard  4343:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4344:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  4345:       } /* End of if */
                   4346:       ipmx +=1;
                   4347:       sw += weight[i];
                   4348:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.335     brouard  4349:       /* printf("Funcone 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],(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
1.126     brouard  4350:       if(globpr){
1.246     brouard  4351:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  4352:  %11.6f %11.6f %11.6f ", \
1.242     brouard  4353:                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  4354:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.335     brouard  4355:  /*    printf("%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\ */
                   4356:  /* %11.6f %11.6f %11.6f ", \ */
                   4357:  /*            num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw, */
                   4358:  /*            2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
1.242     brouard  4359:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   4360:          llt +=ll[k]*gipmx/gsw;
                   4361:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
1.335     brouard  4362:          /* printf(" %10.6f",-ll[k]*gipmx/gsw); */
1.242     brouard  4363:        }
                   4364:        fprintf(ficresilk," %10.6f\n", -llt);
1.335     brouard  4365:        /* printf(" %10.6f\n", -llt); */
1.126     brouard  4366:       }
1.335     brouard  4367:     } /* end of wave */
                   4368:   } /* end of individual */
                   4369:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
1.232     brouard  4370: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
1.335     brouard  4371:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4372:   if(globpr==0){ /* First time we count the contributions and weights */
                   4373:     gipmx=ipmx;
                   4374:     gsw=sw;
                   4375:   }
1.232     brouard  4376: return -l;
1.126     brouard  4377: }
                   4378: 
                   4379: 
                   4380: /*************** function likelione ***********/
1.292     brouard  4381: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  4382: {
                   4383:   /* This routine should help understanding what is done with 
                   4384:      the selection of individuals/waves and
                   4385:      to check the exact contribution to the likelihood.
                   4386:      Plotting could be done.
                   4387:    */
                   4388:   int k;
                   4389: 
                   4390:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  4391:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  4392:     strcat(fileresilk,fileresu);
1.126     brouard  4393:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   4394:       printf("Problem with resultfile: %s\n", fileresilk);
                   4395:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   4396:     }
1.214     brouard  4397:     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");
                   4398:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  4399:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   4400:     for(k=1; k<=nlstate; k++) 
                   4401:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   4402:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   4403:   }
                   4404: 
1.292     brouard  4405:   *fretone=(*func)(p);
1.126     brouard  4406:   if(*globpri !=0){
                   4407:     fclose(ficresilk);
1.205     brouard  4408:     if (mle ==0)
                   4409:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   4410:     else if(mle >=1)
                   4411:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   4412:     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  4413:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  4414:       
                   4415:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  4416:       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  4417: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   4418:     }
1.207     brouard  4419:     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  4420: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4421:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  4422: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4423:     fflush(fichtm);
1.205     brouard  4424:   }
1.126     brouard  4425:   return;
                   4426: }
                   4427: 
                   4428: 
                   4429: /*********** Maximum Likelihood Estimation ***************/
                   4430: 
                   4431: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   4432: {
1.319     brouard  4433:   int i,j,k, jk, jkk=0, iter=0;
1.126     brouard  4434:   double **xi;
                   4435:   double fret;
                   4436:   double fretone; /* Only one call to likelihood */
                   4437:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  4438: 
                   4439: #ifdef NLOPT
                   4440:   int creturn;
                   4441:   nlopt_opt opt;
                   4442:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   4443:   double *lb;
                   4444:   double minf; /* the minimum objective value, upon return */
                   4445:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   4446:   myfunc_data dinst, *d = &dinst;
                   4447: #endif
                   4448: 
                   4449: 
1.126     brouard  4450:   xi=matrix(1,npar,1,npar);
                   4451:   for (i=1;i<=npar;i++)
                   4452:     for (j=1;j<=npar;j++)
                   4453:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   4454:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  4455:   strcpy(filerespow,"POW_"); 
1.126     brouard  4456:   strcat(filerespow,fileres);
                   4457:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   4458:     printf("Problem with resultfile: %s\n", filerespow);
                   4459:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   4460:   }
                   4461:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   4462:   for (i=1;i<=nlstate;i++)
                   4463:     for(j=1;j<=nlstate+ndeath;j++)
                   4464:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   4465:   fprintf(ficrespow,"\n");
1.162     brouard  4466: #ifdef POWELL
1.319     brouard  4467: #ifdef LINMINORIGINAL
                   4468: #else /* LINMINORIGINAL */
                   4469:   
                   4470:   flatdir=ivector(1,npar); 
                   4471:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   4472: #endif /*LINMINORIGINAL */
                   4473: 
                   4474: #ifdef FLATSUP
                   4475:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4476:   /* reorganizing p by suppressing flat directions */
                   4477:   for(i=1, jk=1; i <=nlstate; i++){
                   4478:     for(k=1; k <=(nlstate+ndeath); k++){
                   4479:       if (k != i) {
                   4480:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4481:         if(flatdir[jk]==1){
                   4482:           printf(" To be skipped %d%d flatdir[%d]=%d ",i,k,jk, flatdir[jk]);
                   4483:         }
                   4484:         for(j=1; j <=ncovmodel; j++){
                   4485:           printf("%12.7f ",p[jk]);
                   4486:           jk++; 
                   4487:         }
                   4488:         printf("\n");
                   4489:       }
                   4490:     }
                   4491:   }
                   4492: /* skipping */
                   4493:   /* for(i=1, jk=1, jkk=1;(flatdir[jk]==0)&& (i <=nlstate); i++){ */
                   4494:   for(i=1, jk=1, jkk=1;i <=nlstate; i++){
                   4495:     for(k=1; k <=(nlstate+ndeath); k++){
                   4496:       if (k != i) {
                   4497:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4498:         if(flatdir[jk]==1){
                   4499:           printf(" To be skipped %d%d flatdir[%d]=%d jk=%d p[%d] ",i,k,jk, flatdir[jk],jk, jk);
                   4500:           for(j=1; j <=ncovmodel;  jk++,j++){
                   4501:             printf(" p[%d]=%12.7f",jk, p[jk]);
                   4502:             /*q[jjk]=p[jk];*/
                   4503:           }
                   4504:         }else{
                   4505:           printf(" To be kept %d%d flatdir[%d]=%d jk=%d q[%d]=p[%d] ",i,k,jk, flatdir[jk],jk, jkk, jk);
                   4506:           for(j=1; j <=ncovmodel;  jk++,jkk++,j++){
                   4507:             printf(" p[%d]=%12.7f=q[%d]",jk, p[jk],jkk);
                   4508:             /*q[jjk]=p[jk];*/
                   4509:           }
                   4510:         }
                   4511:         printf("\n");
                   4512:       }
                   4513:       fflush(stdout);
                   4514:     }
                   4515:   }
                   4516:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4517: #else  /* FLATSUP */
1.126     brouard  4518:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.319     brouard  4519: #endif  /* FLATSUP */
                   4520: 
                   4521: #ifdef LINMINORIGINAL
                   4522: #else
                   4523:       free_ivector(flatdir,1,npar); 
                   4524: #endif  /* LINMINORIGINAL*/
                   4525: #endif /* POWELL */
1.126     brouard  4526: 
1.162     brouard  4527: #ifdef NLOPT
                   4528: #ifdef NEWUOA
                   4529:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   4530: #else
                   4531:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   4532: #endif
                   4533:   lb=vector(0,npar-1);
                   4534:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   4535:   nlopt_set_lower_bounds(opt, lb);
                   4536:   nlopt_set_initial_step1(opt, 0.1);
                   4537:   
                   4538:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   4539:   d->function = func;
                   4540:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   4541:   nlopt_set_min_objective(opt, myfunc, d);
                   4542:   nlopt_set_xtol_rel(opt, ftol);
                   4543:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   4544:     printf("nlopt failed! %d\n",creturn); 
                   4545:   }
                   4546:   else {
                   4547:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   4548:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   4549:     iter=1; /* not equal */
                   4550:   }
                   4551:   nlopt_destroy(opt);
                   4552: #endif
1.319     brouard  4553: #ifdef FLATSUP
                   4554:   /* npared = npar -flatd/ncovmodel; */
                   4555:   /* xired= matrix(1,npared,1,npared); */
                   4556:   /* paramred= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */
                   4557:   /* powell(pred,xired,npared,ftol,&iter,&fret,flatdir,func); */
                   4558:   /* free_matrix(xire,1,npared,1,npared); */
                   4559: #else  /* FLATSUP */
                   4560: #endif /* FLATSUP */
1.126     brouard  4561:   free_matrix(xi,1,npar,1,npar);
                   4562:   fclose(ficrespow);
1.203     brouard  4563:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   4564:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  4565:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  4566: 
                   4567: }
                   4568: 
                   4569: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  4570: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  4571: {
                   4572:   double  **a,**y,*x,pd;
1.203     brouard  4573:   /* double **hess; */
1.164     brouard  4574:   int i, j;
1.126     brouard  4575:   int *indx;
                   4576: 
                   4577:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  4578:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  4579:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   4580:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   4581:   double gompertz(double p[]);
1.203     brouard  4582:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  4583: 
                   4584:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   4585:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   4586:   for (i=1;i<=npar;i++){
1.203     brouard  4587:     printf("%d-",i);fflush(stdout);
                   4588:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  4589:    
                   4590:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   4591:     
                   4592:     /*  printf(" %f ",p[i]);
                   4593:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   4594:   }
                   4595:   
                   4596:   for (i=1;i<=npar;i++) {
                   4597:     for (j=1;j<=npar;j++)  {
                   4598:       if (j>i) { 
1.203     brouard  4599:        printf(".%d-%d",i,j);fflush(stdout);
                   4600:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   4601:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  4602:        
                   4603:        hess[j][i]=hess[i][j];    
                   4604:        /*printf(" %lf ",hess[i][j]);*/
                   4605:       }
                   4606:     }
                   4607:   }
                   4608:   printf("\n");
                   4609:   fprintf(ficlog,"\n");
                   4610: 
                   4611:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4612:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4613:   
                   4614:   a=matrix(1,npar,1,npar);
                   4615:   y=matrix(1,npar,1,npar);
                   4616:   x=vector(1,npar);
                   4617:   indx=ivector(1,npar);
                   4618:   for (i=1;i<=npar;i++)
                   4619:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   4620:   ludcmp(a,npar,indx,&pd);
                   4621: 
                   4622:   for (j=1;j<=npar;j++) {
                   4623:     for (i=1;i<=npar;i++) x[i]=0;
                   4624:     x[j]=1;
                   4625:     lubksb(a,npar,indx,x);
                   4626:     for (i=1;i<=npar;i++){ 
                   4627:       matcov[i][j]=x[i];
                   4628:     }
                   4629:   }
                   4630: 
                   4631:   printf("\n#Hessian matrix#\n");
                   4632:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   4633:   for (i=1;i<=npar;i++) { 
                   4634:     for (j=1;j<=npar;j++) { 
1.203     brouard  4635:       printf("%.6e ",hess[i][j]);
                   4636:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  4637:     }
                   4638:     printf("\n");
                   4639:     fprintf(ficlog,"\n");
                   4640:   }
                   4641: 
1.203     brouard  4642:   /* printf("\n#Covariance matrix#\n"); */
                   4643:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   4644:   /* for (i=1;i<=npar;i++) {  */
                   4645:   /*   for (j=1;j<=npar;j++) {  */
                   4646:   /*     printf("%.6e ",matcov[i][j]); */
                   4647:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   4648:   /*   } */
                   4649:   /*   printf("\n"); */
                   4650:   /*   fprintf(ficlog,"\n"); */
                   4651:   /* } */
                   4652: 
1.126     brouard  4653:   /* Recompute Inverse */
1.203     brouard  4654:   /* for (i=1;i<=npar;i++) */
                   4655:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   4656:   /* ludcmp(a,npar,indx,&pd); */
                   4657: 
                   4658:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   4659: 
                   4660:   /* for (j=1;j<=npar;j++) { */
                   4661:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   4662:   /*   x[j]=1; */
                   4663:   /*   lubksb(a,npar,indx,x); */
                   4664:   /*   for (i=1;i<=npar;i++){  */
                   4665:   /*     y[i][j]=x[i]; */
                   4666:   /*     printf("%.3e ",y[i][j]); */
                   4667:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   4668:   /*   } */
                   4669:   /*   printf("\n"); */
                   4670:   /*   fprintf(ficlog,"\n"); */
                   4671:   /* } */
                   4672: 
                   4673:   /* Verifying the inverse matrix */
                   4674: #ifdef DEBUGHESS
                   4675:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  4676: 
1.203     brouard  4677:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   4678:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  4679: 
                   4680:   for (j=1;j<=npar;j++) {
                   4681:     for (i=1;i<=npar;i++){ 
1.203     brouard  4682:       printf("%.2f ",y[i][j]);
                   4683:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  4684:     }
                   4685:     printf("\n");
                   4686:     fprintf(ficlog,"\n");
                   4687:   }
1.203     brouard  4688: #endif
1.126     brouard  4689: 
                   4690:   free_matrix(a,1,npar,1,npar);
                   4691:   free_matrix(y,1,npar,1,npar);
                   4692:   free_vector(x,1,npar);
                   4693:   free_ivector(indx,1,npar);
1.203     brouard  4694:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  4695: 
                   4696: 
                   4697: }
                   4698: 
                   4699: /*************** hessian matrix ****************/
                   4700: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  4701: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  4702:   int i;
                   4703:   int l=1, lmax=20;
1.203     brouard  4704:   double k1,k2, res, fx;
1.132     brouard  4705:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  4706:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   4707:   int k=0,kmax=10;
                   4708:   double l1;
                   4709: 
                   4710:   fx=func(x);
                   4711:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  4712:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  4713:     l1=pow(10,l);
                   4714:     delts=delt;
                   4715:     for(k=1 ; k <kmax; k=k+1){
                   4716:       delt = delta*(l1*k);
                   4717:       p2[theta]=x[theta] +delt;
1.145     brouard  4718:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  4719:       p2[theta]=x[theta]-delt;
                   4720:       k2=func(p2)-fx;
                   4721:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  4722:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  4723:       
1.203     brouard  4724: #ifdef DEBUGHESSII
1.126     brouard  4725:       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);
                   4726:       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);
                   4727: #endif
                   4728:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   4729:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   4730:        k=kmax;
                   4731:       }
                   4732:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  4733:        k=kmax; l=lmax*10;
1.126     brouard  4734:       }
                   4735:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   4736:        delts=delt;
                   4737:       }
1.203     brouard  4738:     } /* End loop k */
1.126     brouard  4739:   }
                   4740:   delti[theta]=delts;
                   4741:   return res; 
                   4742:   
                   4743: }
                   4744: 
1.203     brouard  4745: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  4746: {
                   4747:   int i;
1.164     brouard  4748:   int l=1, lmax=20;
1.126     brouard  4749:   double k1,k2,k3,k4,res,fx;
1.132     brouard  4750:   double p2[MAXPARM+1];
1.203     brouard  4751:   int k, kmax=1;
                   4752:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  4753: 
                   4754:   int firstime=0;
1.203     brouard  4755:   
1.126     brouard  4756:   fx=func(x);
1.203     brouard  4757:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  4758:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  4759:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4760:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4761:     k1=func(p2)-fx;
                   4762:   
1.203     brouard  4763:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4764:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4765:     k2=func(p2)-fx;
                   4766:   
1.203     brouard  4767:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4768:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4769:     k3=func(p2)-fx;
                   4770:   
1.203     brouard  4771:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4772:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4773:     k4=func(p2)-fx;
1.203     brouard  4774:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   4775:     if(k1*k2*k3*k4 <0.){
1.208     brouard  4776:       firstime=1;
1.203     brouard  4777:       kmax=kmax+10;
1.208     brouard  4778:     }
                   4779:     if(kmax >=10 || firstime ==1){
1.246     brouard  4780:       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);
                   4781:       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  4782:       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);
                   4783:       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);
                   4784:     }
                   4785: #ifdef DEBUGHESSIJ
                   4786:     v1=hess[thetai][thetai];
                   4787:     v2=hess[thetaj][thetaj];
                   4788:     cv12=res;
                   4789:     /* Computing eigen value of Hessian matrix */
                   4790:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4791:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4792:     if ((lc2 <0) || (lc1 <0) ){
                   4793:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4794:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4795:       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);
                   4796:       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);
                   4797:     }
1.126     brouard  4798: #endif
                   4799:   }
                   4800:   return res;
                   4801: }
                   4802: 
1.203     brouard  4803:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   4804: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   4805: /* { */
                   4806: /*   int i; */
                   4807: /*   int l=1, lmax=20; */
                   4808: /*   double k1,k2,k3,k4,res,fx; */
                   4809: /*   double p2[MAXPARM+1]; */
                   4810: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   4811: /*   int k=0,kmax=10; */
                   4812: /*   double l1; */
                   4813:   
                   4814: /*   fx=func(x); */
                   4815: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   4816: /*     l1=pow(10,l); */
                   4817: /*     delts=delt; */
                   4818: /*     for(k=1 ; k <kmax; k=k+1){ */
                   4819: /*       delt = delti*(l1*k); */
                   4820: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   4821: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4822: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4823: /*       k1=func(p2)-fx; */
                   4824:       
                   4825: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4826: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4827: /*       k2=func(p2)-fx; */
                   4828:       
                   4829: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4830: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4831: /*       k3=func(p2)-fx; */
                   4832:       
                   4833: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4834: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4835: /*       k4=func(p2)-fx; */
                   4836: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   4837: /* #ifdef DEBUGHESSIJ */
                   4838: /*       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); */
                   4839: /*       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); */
                   4840: /* #endif */
                   4841: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   4842: /*     k=kmax; */
                   4843: /*       } */
                   4844: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   4845: /*     k=kmax; l=lmax*10; */
                   4846: /*       } */
                   4847: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   4848: /*     delts=delt; */
                   4849: /*       } */
                   4850: /*     } /\* End loop k *\/ */
                   4851: /*   } */
                   4852: /*   delti[theta]=delts; */
                   4853: /*   return res;  */
                   4854: /* } */
                   4855: 
                   4856: 
1.126     brouard  4857: /************** Inverse of matrix **************/
                   4858: void ludcmp(double **a, int n, int *indx, double *d) 
                   4859: { 
                   4860:   int i,imax,j,k; 
                   4861:   double big,dum,sum,temp; 
                   4862:   double *vv; 
                   4863:  
                   4864:   vv=vector(1,n); 
                   4865:   *d=1.0; 
                   4866:   for (i=1;i<=n;i++) { 
                   4867:     big=0.0; 
                   4868:     for (j=1;j<=n;j++) 
                   4869:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  4870:     if (big == 0.0){
                   4871:       printf(" Singular Hessian matrix at row %d:\n",i);
                   4872:       for (j=1;j<=n;j++) {
                   4873:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   4874:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   4875:       }
                   4876:       fflush(ficlog);
                   4877:       fclose(ficlog);
                   4878:       nrerror("Singular matrix in routine ludcmp"); 
                   4879:     }
1.126     brouard  4880:     vv[i]=1.0/big; 
                   4881:   } 
                   4882:   for (j=1;j<=n;j++) { 
                   4883:     for (i=1;i<j;i++) { 
                   4884:       sum=a[i][j]; 
                   4885:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   4886:       a[i][j]=sum; 
                   4887:     } 
                   4888:     big=0.0; 
                   4889:     for (i=j;i<=n;i++) { 
                   4890:       sum=a[i][j]; 
                   4891:       for (k=1;k<j;k++) 
                   4892:        sum -= a[i][k]*a[k][j]; 
                   4893:       a[i][j]=sum; 
                   4894:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   4895:        big=dum; 
                   4896:        imax=i; 
                   4897:       } 
                   4898:     } 
                   4899:     if (j != imax) { 
                   4900:       for (k=1;k<=n;k++) { 
                   4901:        dum=a[imax][k]; 
                   4902:        a[imax][k]=a[j][k]; 
                   4903:        a[j][k]=dum; 
                   4904:       } 
                   4905:       *d = -(*d); 
                   4906:       vv[imax]=vv[j]; 
                   4907:     } 
                   4908:     indx[j]=imax; 
                   4909:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   4910:     if (j != n) { 
                   4911:       dum=1.0/(a[j][j]); 
                   4912:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   4913:     } 
                   4914:   } 
                   4915:   free_vector(vv,1,n);  /* Doesn't work */
                   4916: ;
                   4917: } 
                   4918: 
                   4919: void lubksb(double **a, int n, int *indx, double b[]) 
                   4920: { 
                   4921:   int i,ii=0,ip,j; 
                   4922:   double sum; 
                   4923:  
                   4924:   for (i=1;i<=n;i++) { 
                   4925:     ip=indx[i]; 
                   4926:     sum=b[ip]; 
                   4927:     b[ip]=b[i]; 
                   4928:     if (ii) 
                   4929:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   4930:     else if (sum) ii=i; 
                   4931:     b[i]=sum; 
                   4932:   } 
                   4933:   for (i=n;i>=1;i--) { 
                   4934:     sum=b[i]; 
                   4935:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   4936:     b[i]=sum/a[i][i]; 
                   4937:   } 
                   4938: } 
                   4939: 
                   4940: void pstamp(FILE *fichier)
                   4941: {
1.196     brouard  4942:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  4943: }
                   4944: 
1.297     brouard  4945: void date2dmy(double date,double *day, double *month, double *year){
                   4946:   double yp=0., yp1=0., yp2=0.;
                   4947:   
                   4948:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   4949:                        fractional in yp1 */
                   4950:   *year=yp;
                   4951:   yp2=modf((yp1*12),&yp);
                   4952:   *month=yp;
                   4953:   yp1=modf((yp2*30.5),&yp);
                   4954:   *day=yp;
                   4955:   if(*day==0) *day=1;
                   4956:   if(*month==0) *month=1;
                   4957: }
                   4958: 
1.253     brouard  4959: 
                   4960: 
1.126     brouard  4961: /************ Frequencies ********************/
1.251     brouard  4962: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  4963:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   4964:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  4965: {  /* Some frequencies as well as proposing some starting values */
1.332     brouard  4966:   /* Frequencies of any combination of dummy covariate used in the model equation */ 
1.265     brouard  4967:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  4968:   int iind=0, iage=0;
                   4969:   int mi; /* Effective wave */
                   4970:   int first;
                   4971:   double ***freq; /* Frequencies */
1.268     brouard  4972:   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 */
                   4973:   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  4974:   double *meanq, *stdq, *idq;
1.226     brouard  4975:   double **meanqt;
                   4976:   double *pp, **prop, *posprop, *pospropt;
                   4977:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   4978:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   4979:   double agebegin, ageend;
                   4980:     
                   4981:   pp=vector(1,nlstate);
1.251     brouard  4982:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  4983:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   4984:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   4985:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   4986:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  4987:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  4988:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  4989:   meanqt=matrix(1,lastpass,1,nqtveff);
                   4990:   strcpy(fileresp,"P_");
                   4991:   strcat(fileresp,fileresu);
                   4992:   /*strcat(fileresphtm,fileresu);*/
                   4993:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   4994:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   4995:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   4996:     exit(0);
                   4997:   }
1.240     brouard  4998:   
1.226     brouard  4999:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   5000:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   5001:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5002:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5003:     fflush(ficlog);
                   5004:     exit(70); 
                   5005:   }
                   5006:   else{
                   5007:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  5008: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  5009: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5010:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5011:   }
1.319     brouard  5012:   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  5013:   
1.226     brouard  5014:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   5015:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   5016:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5017:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5018:     fflush(ficlog);
                   5019:     exit(70); 
1.240     brouard  5020:   } else{
1.226     brouard  5021:     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  5022: ,<hr size=\"2\" color=\"#EC5E5E\"> \n                                  \
1.214     brouard  5023: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5024:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5025:   }
1.319     brouard  5026:   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  5027:   
1.253     brouard  5028:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   5029:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  5030:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  5031:   j1=0;
1.126     brouard  5032:   
1.227     brouard  5033:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
1.335     brouard  5034:   j=cptcoveff;  /* Only simple dummy covariates used in the model */
1.330     brouard  5035:   /* j=cptcovn;  /\* Only dummy covariates of the model *\/ */
1.226     brouard  5036:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  5037:   
                   5038:   
1.226     brouard  5039:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   5040:      reference=low_education V1=0,V2=0
                   5041:      med_educ                V1=1 V2=0, 
                   5042:      high_educ               V1=0 V2=1
1.330     brouard  5043:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcovn 
1.226     brouard  5044:   */
1.249     brouard  5045:   dateintsum=0;
                   5046:   k2cpt=0;
                   5047: 
1.253     brouard  5048:   if(cptcoveff == 0 )
1.265     brouard  5049:     nl=1;  /* Constant and age model only */
1.253     brouard  5050:   else
                   5051:     nl=2;
1.265     brouard  5052: 
                   5053:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   5054:   /* Loop on nj=1 or 2 if dummy covariates j!=0
1.335     brouard  5055:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
1.265     brouard  5056:    *     freq[s1][s2][iage] =0.
                   5057:    *     Loop on iind
                   5058:    *       ++freq[s1][s2][iage] weighted
                   5059:    *     end iind
                   5060:    *     if covariate and j!0
                   5061:    *       headers Variable on one line
                   5062:    *     endif cov j!=0
                   5063:    *     header of frequency table by age
                   5064:    *     Loop on age
                   5065:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   5066:    *       pos+=freq[s1][s2][iage] weighted
                   5067:    *       Loop on s1 initial state
                   5068:    *         fprintf(ficresp
                   5069:    *       end s1
                   5070:    *     end age
                   5071:    *     if j!=0 computes starting values
                   5072:    *     end compute starting values
                   5073:    *   end j1
                   5074:    * end nl 
                   5075:    */
1.253     brouard  5076:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   5077:     if(nj==1)
                   5078:       j=0;  /* First pass for the constant */
1.265     brouard  5079:     else{
1.335     brouard  5080:       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  5081:     }
1.251     brouard  5082:     first=1;
1.332     brouard  5083:     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  5084:       posproptt=0.;
1.330     brouard  5085:       /*printf("cptcovn=%d Tvaraff=%d", cptcovn,Tvaraff[1]);
1.251     brouard  5086:        scanf("%d", i);*/
                   5087:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  5088:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  5089:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  5090:            freq[i][s2][m]=0;
1.251     brouard  5091:       
                   5092:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  5093:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  5094:          prop[i][m]=0;
                   5095:        posprop[i]=0;
                   5096:        pospropt[i]=0;
                   5097:       }
1.283     brouard  5098:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  5099:         idq[z1]=0.;
                   5100:         meanq[z1]=0.;
                   5101:         stdq[z1]=0.;
1.283     brouard  5102:       }
                   5103:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  5104:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  5105:       /*         meanqt[m][z1]=0.; */
                   5106:       /*       } */
                   5107:       /* }       */
1.251     brouard  5108:       /* dateintsum=0; */
                   5109:       /* k2cpt=0; */
                   5110:       
1.265     brouard  5111:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  5112:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   5113:        bool=1;
                   5114:        if(j !=0){
                   5115:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.335     brouard  5116:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   5117:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
1.251     brouard  5118:                /* if(Tvaraff[z1] ==-20){ */
                   5119:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   5120:                /* }else  if(Tvaraff[z1] ==-10){ */
                   5121:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
1.330     brouard  5122:                /* }else  */ /* TODO TODO codtabm(j1,z1) or codtabm(j1,Tvaraff[z1]]z1)*/
1.335     brouard  5123:                /* 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); */
                   5124:                if(Tvaraff[z1]<1 || Tvaraff[z1]>=NCOVMAX)
                   5125:                  printf("Error Tvaraff[z1]=%d<1 or >=%d, cptcoveff=%d model=%s\n",Tvaraff[z1],NCOVMAX, cptcoveff, model);
1.332     brouard  5126:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]){ /* for combination j1 of covariates */
1.265     brouard  5127:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  5128:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
1.332     brouard  5129:                  /* 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", */
                   5130:                  /*   bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),*/
                   5131:                   /*   j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
1.251     brouard  5132:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   5133:                } /* Onlyf fixed */
                   5134:              } /* end z1 */
1.335     brouard  5135:            } /* cptcoveff > 0 */
1.251     brouard  5136:          } /* end any */
                   5137:        }/* end j==0 */
1.265     brouard  5138:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  5139:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  5140:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  5141:            m=mw[mi][iind];
                   5142:            if(j!=0){
                   5143:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
1.335     brouard  5144:                for (z1=1; z1<=cptcoveff; z1++) {
1.251     brouard  5145:                  if( Fixed[Tmodelind[z1]]==1){
                   5146:                    iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
1.332     brouard  5147:                    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  5148:                                                                                      value is -1, we don't select. It differs from the 
                   5149:                                                                                      constant and age model which counts them. */
                   5150:                      bool=0; /* not selected */
                   5151:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
1.334     brouard  5152:                    /* i1=Tvaraff[z1]; */
                   5153:                    /* i2=TnsdVar[i1]; */
                   5154:                    /* i3=nbcode[i1][i2]; */
                   5155:                    /* i4=covar[i1][iind]; */
                   5156:                    /* if(i4 != i3){ */
                   5157:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) { /* Bug valgrind */
1.251     brouard  5158:                      bool=0;
                   5159:                    }
                   5160:                  }
                   5161:                }
                   5162:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   5163:            } /* end j==0 */
                   5164:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  5165:            if(bool==1){ /*Selected */
1.251     brouard  5166:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   5167:                 and mw[mi+1][iind]. dh depends on stepm. */
                   5168:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   5169:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   5170:              if(m >=firstpass && m <=lastpass){
                   5171:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   5172:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   5173:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   5174:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   5175:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   5176:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   5177:                if (m<lastpass) {
                   5178:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   5179:                  /*   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]); */
                   5180:                  if(s[m][iind]==-1)
                   5181:                    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.));
                   5182:                  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  5183:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
                   5184:                    if(!isnan(covar[ncovcol+z1][iind])){
1.332     brouard  5185:                      idq[z1]=idq[z1]+weight[iind];
                   5186:                      meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   5187:                      /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
                   5188:                      stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
1.311     brouard  5189:                    }
1.284     brouard  5190:                  }
1.251     brouard  5191:                  /* if((int)agev[m][iind] == 55) */
                   5192:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   5193:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   5194:                  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  5195:                }
1.251     brouard  5196:              } /* end if between passes */  
                   5197:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   5198:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   5199:                k2cpt++;
                   5200:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  5201:              }
1.251     brouard  5202:            }else{
                   5203:              bool=1;
                   5204:            }/* end bool 2 */
                   5205:          } /* end m */
1.284     brouard  5206:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   5207:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   5208:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   5209:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   5210:          /* } */
1.251     brouard  5211:        } /* end bool */
                   5212:       } /* end iind = 1 to imx */
1.319     brouard  5213:       /* prop[s][age] is fed for any initial and valid live state as well as
1.251     brouard  5214:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   5215:       
                   5216:       
                   5217:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.335     brouard  5218:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
1.265     brouard  5219:         pstamp(ficresp);
1.335     brouard  5220:       if  (cptcoveff>0 && j!=0){
1.265     brouard  5221:         pstamp(ficresp);
1.251     brouard  5222:        printf( "\n#********** Variable "); 
                   5223:        fprintf(ficresp, "\n#********** Variable "); 
                   5224:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   5225:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   5226:        fprintf(ficlog, "\n#********** Variable "); 
1.330     brouard  5227:        for (z1=1; z1<=cptcovs; z1++){
1.251     brouard  5228:          if(!FixedV[Tvaraff[z1]]){
1.330     brouard  5229:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5230:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5231:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5232:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5233:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.250     brouard  5234:          }else{
1.330     brouard  5235:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5236:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5237:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5238:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5239:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.251     brouard  5240:          }
                   5241:        }
                   5242:        printf( "**********\n#");
                   5243:        fprintf(ficresp, "**********\n#");
                   5244:        fprintf(ficresphtm, "**********</h3>\n");
                   5245:        fprintf(ficresphtmfr, "**********</h3>\n");
                   5246:        fprintf(ficlog, "**********\n");
                   5247:       }
1.284     brouard  5248:       /*
                   5249:        Printing means of quantitative variables if any
                   5250:       */
                   5251:       for (z1=1; z1<= nqfveff; z1++) {
1.311     brouard  5252:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.312     brouard  5253:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
1.284     brouard  5254:        if(weightopt==1){
                   5255:          printf(" Weighted mean and standard deviation of");
                   5256:          fprintf(ficlog," Weighted mean and standard deviation of");
                   5257:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   5258:        }
1.311     brouard  5259:        /* mu = \frac{w x}{\sum w}
                   5260:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
                   5261:        */
                   5262:        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]));
                   5263:        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]));
                   5264:        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  5265:       }
                   5266:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   5267:       /*       for(m=1;m<=lastpass;m++){ */
                   5268:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   5269:       /*   } */
                   5270:       /* } */
1.283     brouard  5271: 
1.251     brouard  5272:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.335     brouard  5273:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
1.265     brouard  5274:         fprintf(ficresp, " Age");
1.335     brouard  5275:       if(nj==2) for (z1=1; z1<=cptcoveff; z1++) {
                   5276:          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]]);
                   5277:          fprintf(ficresp, " V%d=%d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5278:        }
1.251     brouard  5279:       for(i=1; i<=nlstate;i++) {
1.335     brouard  5280:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  5281:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   5282:       }
1.335     brouard  5283:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  5284:       fprintf(ficresphtm, "\n");
                   5285:       
                   5286:       /* Header of frequency table by age */
                   5287:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   5288:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  5289:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  5290:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5291:          if(s2!=0 && m!=0)
                   5292:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  5293:        }
1.226     brouard  5294:       }
1.251     brouard  5295:       fprintf(ficresphtmfr, "\n");
                   5296:     
                   5297:       /* For each age */
                   5298:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   5299:        fprintf(ficresphtm,"<tr>");
                   5300:        if(iage==iagemax+1){
                   5301:          fprintf(ficlog,"1");
                   5302:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   5303:        }else if(iage==iagemax+2){
                   5304:          fprintf(ficlog,"0");
                   5305:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   5306:        }else if(iage==iagemax+3){
                   5307:          fprintf(ficlog,"Total");
                   5308:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   5309:        }else{
1.240     brouard  5310:          if(first==1){
1.251     brouard  5311:            first=0;
                   5312:            printf("See log file for details...\n");
                   5313:          }
                   5314:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   5315:          fprintf(ficlog,"Age %d", iage);
                   5316:        }
1.265     brouard  5317:        for(s1=1; s1 <=nlstate ; s1++){
                   5318:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   5319:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  5320:        }
1.265     brouard  5321:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5322:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  5323:            pos += freq[s1][m][iage];
                   5324:          if(pp[s1]>=1.e-10){
1.251     brouard  5325:            if(first==1){
1.265     brouard  5326:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5327:            }
1.265     brouard  5328:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5329:          }else{
                   5330:            if(first==1)
1.265     brouard  5331:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   5332:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  5333:          }
                   5334:        }
                   5335:       
1.265     brouard  5336:        for(s1=1; s1 <=nlstate ; s1++){ 
                   5337:          /* posprop[s1]=0; */
                   5338:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   5339:            pp[s1] += freq[s1][m][iage];
                   5340:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   5341:       
                   5342:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   5343:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   5344:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5345:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5346:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5347:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5348:        }
                   5349:        
                   5350:        /* Writing ficresp */
1.335     brouard  5351:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5352:           if( iage <= iagemax){
                   5353:            fprintf(ficresp," %d",iage);
                   5354:           }
                   5355:         }else if( nj==2){
                   5356:           if( iage <= iagemax){
                   5357:            fprintf(ficresp," %d",iage);
1.335     brouard  5358:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.265     brouard  5359:           }
1.240     brouard  5360:        }
1.265     brouard  5361:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  5362:          if(pos>=1.e-5){
1.251     brouard  5363:            if(first==1)
1.265     brouard  5364:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   5365:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  5366:          }else{
                   5367:            if(first==1)
1.265     brouard  5368:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   5369:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  5370:          }
                   5371:          if( iage <= iagemax){
                   5372:            if(pos>=1.e-5){
1.335     brouard  5373:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5374:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5375:               }else if( nj==2){
                   5376:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5377:               }
                   5378:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5379:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   5380:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   5381:            } else{
1.335     brouard  5382:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
1.265     brouard  5383:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  5384:            }
1.240     brouard  5385:          }
1.265     brouard  5386:          pospropt[s1] +=posprop[s1];
                   5387:        } /* end loop s1 */
1.251     brouard  5388:        /* pospropt=0.; */
1.265     brouard  5389:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  5390:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5391:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  5392:              if(first==1){
1.265     brouard  5393:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5394:              }
1.265     brouard  5395:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   5396:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5397:            }
1.265     brouard  5398:            if(s1!=0 && m!=0)
                   5399:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  5400:          }
1.265     brouard  5401:        } /* end loop s1 */
1.251     brouard  5402:        posproptt=0.; 
1.265     brouard  5403:        for(s1=1; s1 <=nlstate; s1++){
                   5404:          posproptt += pospropt[s1];
1.251     brouard  5405:        }
                   5406:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  5407:        fprintf(ficresphtm,"</tr>\n");
1.335     brouard  5408:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
1.265     brouard  5409:          if(iage <= iagemax)
                   5410:            fprintf(ficresp,"\n");
1.240     brouard  5411:        }
1.251     brouard  5412:        if(first==1)
                   5413:          printf("Others in log...\n");
                   5414:        fprintf(ficlog,"\n");
                   5415:       } /* end loop age iage */
1.265     brouard  5416:       
1.251     brouard  5417:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  5418:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5419:        if(posproptt < 1.e-5){
1.265     brouard  5420:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  5421:        }else{
1.265     brouard  5422:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  5423:        }
1.226     brouard  5424:       }
1.251     brouard  5425:       fprintf(ficresphtm,"</tr>\n");
                   5426:       fprintf(ficresphtm,"</table>\n");
                   5427:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  5428:       if(posproptt < 1.e-5){
1.251     brouard  5429:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   5430:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  5431:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   5432:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  5433:        invalidvarcomb[j1]=1;
1.226     brouard  5434:       }else{
1.251     brouard  5435:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
                   5436:        invalidvarcomb[j1]=0;
1.226     brouard  5437:       }
1.251     brouard  5438:       fprintf(ficresphtmfr,"</table>\n");
                   5439:       fprintf(ficlog,"\n");
                   5440:       if(j!=0){
                   5441:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  5442:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5443:          for(k=1; k <=(nlstate+ndeath); k++){
                   5444:            if (k != i) {
1.265     brouard  5445:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  5446:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  5447:                  if(j1==1){ /* All dummy covariates to zero */
                   5448:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   5449:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  5450:                    printf("%d%d ",i,k);
                   5451:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5452:                    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]));
                   5453:                    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]));
                   5454:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  5455:                  }
1.253     brouard  5456:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   5457:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   5458:                    x[iage]= (double)iage;
                   5459:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  5460:                    /* 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  5461:                  }
1.268     brouard  5462:                  /* Some are not finite, but linreg will ignore these ages */
                   5463:                  no=0;
1.253     brouard  5464:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  5465:                  pstart[s1]=b;
                   5466:                  pstart[s1-1]=a;
1.252     brouard  5467:                }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 */ 
                   5468:                  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]);
                   5469:                  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  5470:                  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  5471:                  printf("%d%d ",i,k);
                   5472:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5473:                  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  5474:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   5475:                  ;
                   5476:                }
                   5477:                /* printf("%12.7f )", param[i][jj][k]); */
                   5478:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5479:                s1++; 
1.251     brouard  5480:              } /* end jj */
                   5481:            } /* end k!= i */
                   5482:          } /* end k */
1.265     brouard  5483:        } /* end i, s1 */
1.251     brouard  5484:       } /* end j !=0 */
                   5485:     } /* end selected combination of covariate j1 */
                   5486:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   5487:       printf("#Freqsummary: Starting values for the constants:\n");
                   5488:       fprintf(ficlog,"\n");
1.265     brouard  5489:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5490:        for(k=1; k <=(nlstate+ndeath); k++){
                   5491:          if (k != i) {
                   5492:            printf("%d%d ",i,k);
                   5493:            fprintf(ficlog,"%d%d ",i,k);
                   5494:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  5495:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  5496:              if(jj==1){ /* Age has to be done */
1.265     brouard  5497:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   5498:                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]));
                   5499:                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  5500:              }
                   5501:              /* printf("%12.7f )", param[i][jj][k]); */
                   5502:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5503:              s1++; 
1.250     brouard  5504:            }
1.251     brouard  5505:            printf("\n");
                   5506:            fprintf(ficlog,"\n");
1.250     brouard  5507:          }
                   5508:        }
1.284     brouard  5509:       } /* end of state i */
1.251     brouard  5510:       printf("#Freqsummary\n");
                   5511:       fprintf(ficlog,"\n");
1.265     brouard  5512:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   5513:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   5514:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   5515:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5516:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5517:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   5518:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   5519:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  5520:          /* } */
                   5521:        }
1.265     brouard  5522:       } /* end loop s1 */
1.251     brouard  5523:       
                   5524:       printf("\n");
                   5525:       fprintf(ficlog,"\n");
                   5526:     } /* end j=0 */
1.249     brouard  5527:   } /* end j */
1.252     brouard  5528: 
1.253     brouard  5529:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  5530:     for(i=1, jk=1; i <=nlstate; i++){
                   5531:       for(j=1; j <=nlstate+ndeath; j++){
                   5532:        if(j!=i){
                   5533:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5534:          printf("%1d%1d",i,j);
                   5535:          fprintf(ficparo,"%1d%1d",i,j);
                   5536:          for(k=1; k<=ncovmodel;k++){
                   5537:            /*    printf(" %lf",param[i][j][k]); */
                   5538:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   5539:            p[jk]=pstart[jk];
                   5540:            printf(" %f ",pstart[jk]);
                   5541:            fprintf(ficparo," %f ",pstart[jk]);
                   5542:            jk++;
                   5543:          }
                   5544:          printf("\n");
                   5545:          fprintf(ficparo,"\n");
                   5546:        }
                   5547:       }
                   5548:     }
                   5549:   } /* end mle=-2 */
1.226     brouard  5550:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  5551:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  5552:   
1.226     brouard  5553:   fclose(ficresp);
                   5554:   fclose(ficresphtm);
                   5555:   fclose(ficresphtmfr);
1.283     brouard  5556:   free_vector(idq,1,nqfveff);
1.226     brouard  5557:   free_vector(meanq,1,nqfveff);
1.284     brouard  5558:   free_vector(stdq,1,nqfveff);
1.226     brouard  5559:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  5560:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   5561:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  5562:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5563:   free_vector(pospropt,1,nlstate);
                   5564:   free_vector(posprop,1,nlstate);
1.251     brouard  5565:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5566:   free_vector(pp,1,nlstate);
                   5567:   /* End of freqsummary */
                   5568: }
1.126     brouard  5569: 
1.268     brouard  5570: /* Simple linear regression */
                   5571: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   5572: 
                   5573:   /* y=a+bx regression */
                   5574:   double   sumx = 0.0;                        /* sum of x                      */
                   5575:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   5576:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   5577:   double   sumy = 0.0;                        /* sum of y                      */
                   5578:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   5579:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   5580:   double yhat;
                   5581:   
                   5582:   double denom=0;
                   5583:   int i;
                   5584:   int ne=*no;
                   5585:   
                   5586:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5587:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5588:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5589:       continue;
                   5590:     }
                   5591:     ne=ne+1;
                   5592:     sumx  += x[i];       
                   5593:     sumx2 += x[i]*x[i];  
                   5594:     sumxy += x[i] * y[i];
                   5595:     sumy  += y[i];      
                   5596:     sumy2 += y[i]*y[i]; 
                   5597:     denom = (ne * sumx2 - sumx*sumx);
                   5598:     /* 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); */
                   5599:   } 
                   5600:   
                   5601:   denom = (ne * sumx2 - sumx*sumx);
                   5602:   if (denom == 0) {
                   5603:     // vertical, slope m is infinity
                   5604:     *b = INFINITY;
                   5605:     *a = 0;
                   5606:     if (r) *r = 0;
                   5607:     return 1;
                   5608:   }
                   5609:   
                   5610:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   5611:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   5612:   if (r!=NULL) {
                   5613:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   5614:       sqrt((sumx2 - sumx*sumx/ne) *
                   5615:           (sumy2 - sumy*sumy/ne));
                   5616:   }
                   5617:   *no=ne;
                   5618:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5619:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5620:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5621:       continue;
                   5622:     }
                   5623:     ne=ne+1;
                   5624:     yhat = y[i] - *a -*b* x[i];
                   5625:     sume2  += yhat * yhat ;       
                   5626:     
                   5627:     denom = (ne * sumx2 - sumx*sumx);
                   5628:     /* 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); */
                   5629:   } 
                   5630:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   5631:   *sa= *sb * sqrt(sumx2/ne);
                   5632:   
                   5633:   return 0; 
                   5634: }
                   5635: 
1.126     brouard  5636: /************ Prevalence ********************/
1.227     brouard  5637: 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)
                   5638: {  
                   5639:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   5640:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   5641:      We still use firstpass and lastpass as another selection.
                   5642:   */
1.126     brouard  5643:  
1.227     brouard  5644:   int i, m, jk, j1, bool, z1,j, iv;
                   5645:   int mi; /* Effective wave */
                   5646:   int iage;
                   5647:   double agebegin, ageend;
                   5648: 
                   5649:   double **prop;
                   5650:   double posprop; 
                   5651:   double  y2; /* in fractional years */
                   5652:   int iagemin, iagemax;
                   5653:   int first; /** to stop verbosity which is redirected to log file */
                   5654: 
                   5655:   iagemin= (int) agemin;
                   5656:   iagemax= (int) agemax;
                   5657:   /*pp=vector(1,nlstate);*/
1.251     brouard  5658:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  5659:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   5660:   j1=0;
1.222     brouard  5661:   
1.227     brouard  5662:   /*j=cptcoveff;*/
                   5663:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  5664:   
1.288     brouard  5665:   first=0;
1.335     brouard  5666:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of simple dummy covariates */
1.227     brouard  5667:     for (i=1; i<=nlstate; i++)  
1.251     brouard  5668:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  5669:        prop[i][iage]=0.0;
                   5670:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   5671:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   5672:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   5673:     
                   5674:     for (i=1; i<=imx; i++) { /* Each individual */
                   5675:       bool=1;
                   5676:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   5677:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   5678:        m=mw[mi][i];
                   5679:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   5680:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   5681:        for (z1=1; z1<=cptcoveff; z1++){
                   5682:          if( Fixed[Tmodelind[z1]]==1){
                   5683:            iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
1.332     brouard  5684:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality */
1.227     brouard  5685:              bool=0;
                   5686:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
1.332     brouard  5687:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) {
1.227     brouard  5688:              bool=0;
                   5689:            }
                   5690:        }
                   5691:        if(bool==1){ /* Otherwise we skip that wave/person */
                   5692:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   5693:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   5694:          if(m >=firstpass && m <=lastpass){
                   5695:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   5696:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   5697:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   5698:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  5699:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  5700:                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); 
                   5701:                exit(1);
                   5702:              }
                   5703:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   5704:                /*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]]);*/
                   5705:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   5706:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   5707:              } /* end valid statuses */ 
                   5708:            } /* end selection of dates */
                   5709:          } /* end selection of waves */
                   5710:        } /* end bool */
                   5711:       } /* end wave */
                   5712:     } /* end individual */
                   5713:     for(i=iagemin; i <= iagemax+3; i++){  
                   5714:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   5715:        posprop += prop[jk][i]; 
                   5716:       } 
                   5717:       
                   5718:       for(jk=1; jk <=nlstate ; jk++){      
                   5719:        if( i <=  iagemax){ 
                   5720:          if(posprop>=1.e-5){ 
                   5721:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   5722:          } else{
1.288     brouard  5723:            if(!first){
                   5724:              first=1;
1.266     brouard  5725:              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]);
                   5726:            }else{
1.288     brouard  5727:              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  5728:            }
                   5729:          }
                   5730:        } 
                   5731:       }/* end jk */ 
                   5732:     }/* end i */ 
1.222     brouard  5733:      /*} *//* end i1 */
1.227     brouard  5734:   } /* end j1 */
1.222     brouard  5735:   
1.227     brouard  5736:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   5737:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  5738:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  5739: }  /* End of prevalence */
1.126     brouard  5740: 
                   5741: /************* Waves Concatenation ***************/
                   5742: 
                   5743: 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)
                   5744: {
1.298     brouard  5745:   /* 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  5746:      Death is a valid wave (if date is known).
                   5747:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   5748:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  5749:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  5750:   */
1.126     brouard  5751: 
1.224     brouard  5752:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  5753:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   5754:      double sum=0., jmean=0.;*/
1.224     brouard  5755:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  5756:   int j, k=0,jk, ju, jl;
                   5757:   double sum=0.;
                   5758:   first=0;
1.214     brouard  5759:   firstwo=0;
1.217     brouard  5760:   firsthree=0;
1.218     brouard  5761:   firstfour=0;
1.164     brouard  5762:   jmin=100000;
1.126     brouard  5763:   jmax=-1;
                   5764:   jmean=0.;
1.224     brouard  5765: 
                   5766: /* Treating live states */
1.214     brouard  5767:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  5768:     mi=0;  /* First valid wave */
1.227     brouard  5769:     mli=0; /* Last valid wave */
1.309     brouard  5770:     m=firstpass;  /* Loop on waves */
                   5771:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
1.227     brouard  5772:       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 */
                   5773:        mli=m-1;/* mw[++mi][i]=m-1; */
                   5774:       }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  5775:        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  5776:        mli=m;
1.224     brouard  5777:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   5778:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  5779:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  5780:       }
1.309     brouard  5781:       else{ /* m = lastpass, eventual special issue with warning */
1.224     brouard  5782: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  5783:        break;
1.224     brouard  5784: #else
1.317     brouard  5785:        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  5786:          if(firsthree == 0){
1.302     brouard  5787:            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  5788:            firsthree=1;
1.317     brouard  5789:          }else if(firsthree >=1 && firsthree < 10){
                   5790:            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);
                   5791:            firsthree++;
                   5792:          }else if(firsthree == 10){
                   5793:            printf("Information, too many Information flags: no more reported to log either\n");
                   5794:            fprintf(ficlog,"Information, too many Information flags: no more reported to log either\n");
                   5795:            firsthree++;
                   5796:          }else{
                   5797:            firsthree++;
1.227     brouard  5798:          }
1.309     brouard  5799:          mw[++mi][i]=m; /* Valid transition with unknown status */
1.227     brouard  5800:          mli=m;
                   5801:        }
                   5802:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   5803:          nbwarn++;
1.309     brouard  5804:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
1.227     brouard  5805:            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);
                   5806:            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);
                   5807:          }
                   5808:          break;
                   5809:        }
                   5810:        break;
1.224     brouard  5811: #endif
1.227     brouard  5812:       }/* End m >= lastpass */
1.126     brouard  5813:     }/* end while */
1.224     brouard  5814: 
1.227     brouard  5815:     /* 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  5816:     /* After last pass */
1.224     brouard  5817: /* Treating death states */
1.214     brouard  5818:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  5819:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   5820:       /* } */
1.126     brouard  5821:       mi++;    /* Death is another wave */
                   5822:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  5823:       /* Only death is a correct wave */
1.126     brouard  5824:       mw[mi][i]=m;
1.257     brouard  5825:     } /* else not in a death state */
1.224     brouard  5826: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  5827:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  5828:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.309     brouard  5829:        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  5830:          nbwarn++;
                   5831:          if(firstfiv==0){
1.309     brouard  5832:            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  5833:            firstfiv=1;
                   5834:          }else{
1.309     brouard  5835:            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  5836:          }
1.309     brouard  5837:            s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
                   5838:        }else{ /* Month of Death occured afer last wave month, potential bias */
1.227     brouard  5839:          nberr++;
                   5840:          if(firstwo==0){
1.309     brouard  5841:            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  5842:            firstwo=1;
                   5843:          }
1.309     brouard  5844:          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  5845:        }
1.257     brouard  5846:       }else{ /* if date of interview is unknown */
1.227     brouard  5847:        /* death is known but not confirmed by death status at any wave */
                   5848:        if(firstfour==0){
1.309     brouard  5849:          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  5850:          firstfour=1;
                   5851:        }
1.309     brouard  5852:        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  5853:       }
1.224     brouard  5854:     } /* end if date of death is known */
                   5855: #endif
1.309     brouard  5856:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
                   5857:     /* wav[i]=mw[mi][i];   */
1.126     brouard  5858:     if(mi==0){
                   5859:       nbwarn++;
                   5860:       if(first==0){
1.227     brouard  5861:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   5862:        first=1;
1.126     brouard  5863:       }
                   5864:       if(first==1){
1.227     brouard  5865:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  5866:       }
                   5867:     } /* end mi==0 */
                   5868:   } /* End individuals */
1.214     brouard  5869:   /* wav and mw are no more changed */
1.223     brouard  5870:        
1.317     brouard  5871:   printf("Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   5872:   fprintf(ficlog,"Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   5873: 
                   5874: 
1.126     brouard  5875:   for(i=1; i<=imx; i++){
                   5876:     for(mi=1; mi<wav[i];mi++){
                   5877:       if (stepm <=0)
1.227     brouard  5878:        dh[mi][i]=1;
1.126     brouard  5879:       else{
1.260     brouard  5880:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  5881:          if (agedc[i] < 2*AGESUP) {
                   5882:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   5883:            if(j==0) j=1;  /* Survives at least one month after exam */
                   5884:            else if(j<0){
                   5885:              nberr++;
                   5886:              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]);
                   5887:              j=1; /* Temporary Dangerous patch */
                   5888:              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);
                   5889:              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]);
                   5890:              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);
                   5891:            }
                   5892:            k=k+1;
                   5893:            if (j >= jmax){
                   5894:              jmax=j;
                   5895:              ijmax=i;
                   5896:            }
                   5897:            if (j <= jmin){
                   5898:              jmin=j;
                   5899:              ijmin=i;
                   5900:            }
                   5901:            sum=sum+j;
                   5902:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   5903:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   5904:          }
                   5905:        }
                   5906:        else{
                   5907:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  5908: /*       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  5909:                                        
1.227     brouard  5910:          k=k+1;
                   5911:          if (j >= jmax) {
                   5912:            jmax=j;
                   5913:            ijmax=i;
                   5914:          }
                   5915:          else if (j <= jmin){
                   5916:            jmin=j;
                   5917:            ijmin=i;
                   5918:          }
                   5919:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   5920:          /*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]);*/
                   5921:          if(j<0){
                   5922:            nberr++;
                   5923:            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]);
                   5924:            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]);
                   5925:          }
                   5926:          sum=sum+j;
                   5927:        }
                   5928:        jk= j/stepm;
                   5929:        jl= j -jk*stepm;
                   5930:        ju= j -(jk+1)*stepm;
                   5931:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   5932:          if(jl==0){
                   5933:            dh[mi][i]=jk;
                   5934:            bh[mi][i]=0;
                   5935:          }else{ /* We want a negative bias in order to only have interpolation ie
                   5936:                  * to avoid the price of an extra matrix product in likelihood */
                   5937:            dh[mi][i]=jk+1;
                   5938:            bh[mi][i]=ju;
                   5939:          }
                   5940:        }else{
                   5941:          if(jl <= -ju){
                   5942:            dh[mi][i]=jk;
                   5943:            bh[mi][i]=jl;       /* bias is positive if real duration
                   5944:                                 * is higher than the multiple of stepm and negative otherwise.
                   5945:                                 */
                   5946:          }
                   5947:          else{
                   5948:            dh[mi][i]=jk+1;
                   5949:            bh[mi][i]=ju;
                   5950:          }
                   5951:          if(dh[mi][i]==0){
                   5952:            dh[mi][i]=1; /* At least one step */
                   5953:            bh[mi][i]=ju; /* At least one step */
                   5954:            /*  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);*/
                   5955:          }
                   5956:        } /* end if mle */
1.126     brouard  5957:       }
                   5958:     } /* end wave */
                   5959:   }
                   5960:   jmean=sum/k;
                   5961:   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  5962:   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  5963: }
1.126     brouard  5964: 
                   5965: /*********** Tricode ****************************/
1.220     brouard  5966:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  5967:  {
                   5968:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   5969:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   5970:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   5971:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   5972:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   5973:     */
1.130     brouard  5974: 
1.242     brouard  5975:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   5976:    int modmaxcovj=0; /* Modality max of covariates j */
                   5977:    int cptcode=0; /* Modality max of covariates j */
                   5978:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  5979: 
                   5980: 
1.242     brouard  5981:    /* cptcoveff=0;  */
                   5982:    /* *cptcov=0; */
1.126     brouard  5983:  
1.242     brouard  5984:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  5985:    for (k=1; k <= maxncov; k++)
                   5986:      for(j=1; j<=2; j++)
                   5987:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  5988: 
1.242     brouard  5989:    /* Loop on covariates without age and products and no quantitative variable */
1.335     brouard  5990:    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  5991:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
                   5992:      if(Dummy[k]==0 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
                   5993:        switch(Fixed[k]) {
                   5994:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.311     brouard  5995:         modmaxcovj=0;
                   5996:         modmincovj=0;
1.242     brouard  5997:         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*/
                   5998:           ij=(int)(covar[Tvar[k]][i]);
                   5999:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   6000:            * If product of Vn*Vm, still boolean *:
                   6001:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   6002:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   6003:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   6004:              modality of the nth covariate of individual i. */
                   6005:           if (ij > modmaxcovj)
                   6006:             modmaxcovj=ij; 
                   6007:           else if (ij < modmincovj) 
                   6008:             modmincovj=ij; 
1.287     brouard  6009:           if (ij <0 || ij >1 ){
1.311     brouard  6010:             printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6011:             fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6012:             fflush(ficlog);
                   6013:             exit(1);
1.287     brouard  6014:           }
                   6015:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  6016:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   6017:             exit(1);
                   6018:           }else
                   6019:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   6020:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   6021:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   6022:           /* getting the maximum value of the modality of the covariate
                   6023:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   6024:              female ies 1, then modmaxcovj=1.
                   6025:           */
                   6026:         } /* end for loop on individuals i */
                   6027:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6028:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6029:         cptcode=modmaxcovj;
                   6030:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   6031:         /*for (i=0; i<=cptcode; i++) {*/
                   6032:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   6033:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6034:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6035:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   6036:             if( j != -1){
                   6037:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   6038:                                  covariate for which somebody answered excluding 
                   6039:                                  undefined. Usually 2: 0 and 1. */
                   6040:             }
                   6041:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   6042:                                     covariate for which somebody answered including 
                   6043:                                     undefined. Usually 3: -1, 0 and 1. */
                   6044:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   6045:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   6046:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  6047:                        
1.242     brouard  6048:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   6049:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   6050:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   6051:         /* modmincovj=3; modmaxcovj = 7; */
                   6052:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   6053:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   6054:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   6055:         /* nbcode[Tvar[j]][ij]=k; */
                   6056:         /* nbcode[Tvar[j]][1]=0; */
                   6057:         /* nbcode[Tvar[j]][2]=1; */
                   6058:         /* nbcode[Tvar[j]][3]=2; */
                   6059:         /* To be continued (not working yet). */
                   6060:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  6061: 
                   6062:         /* 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*/
                   6063:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   6064:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   6065:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   6066:         /*, could be restored in the future */
                   6067:         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  6068:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   6069:             break;
                   6070:           }
                   6071:           ij++;
1.287     brouard  6072:           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  6073:           cptcode = ij; /* New max modality for covar j */
                   6074:         } /* end of loop on modality i=-1 to 1 or more */
                   6075:         break;
                   6076:        case 1: /* Testing on varying covariate, could be simple and
                   6077:                * should look at waves or product of fixed *
                   6078:                * varying. No time to test -1, assuming 0 and 1 only */
                   6079:         ij=0;
                   6080:         for(i=0; i<=1;i++){
                   6081:           nbcode[Tvar[k]][++ij]=i;
                   6082:         }
                   6083:         break;
                   6084:        default:
                   6085:         break;
                   6086:        } /* end switch */
                   6087:      } /* end dummy test */
1.334     brouard  6088:      if(Dummy[k]==1 && Typevar[k] !=1){ /* Quantitative covariate and not age product */ 
1.311     brouard  6089:        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  6090:         if(Tvar[k]<=0 || Tvar[k]>=NCOVMAX){
                   6091:           printf("Error k=%d \n",k);
                   6092:           exit(1);
                   6093:         }
1.311     brouard  6094:         if(isnan(covar[Tvar[k]][i])){
                   6095:           printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6096:           fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6097:           fflush(ficlog);
                   6098:           exit(1);
                   6099:          }
                   6100:        }
1.335     brouard  6101:      } /* end Quanti */
1.287     brouard  6102:    } /* 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  6103:   
                   6104:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   6105:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   6106:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   6107:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   6108:      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 */ 
                   6109:      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 */
                   6110:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   6111:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   6112:   
                   6113:    ij=0;
                   6114:    /* 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  6115:    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 */
                   6116:      /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
1.242     brouard  6117:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   6118:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
1.335     brouard  6119:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy simple and non empty in the model */
                   6120:        /* Typevar[k] =0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for product */
                   6121:        /* 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  6122:        /* If product not in single variable we don't print results */
                   6123:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
1.335     brouard  6124:        ++ij;/*    V5 + V4 + V3 + V4*V3 + V5*age + V2 +  V1*V2 + V1*age + V1, *//* V5 quanti, V2 quanti, V4, V3, V1 dummies */
                   6125:        /* k=       1    2   3     4       5       6      7       8        9  */
                   6126:        /* Tvar[k]= 5    4    3    6       5       2      7       1        1  */
                   6127:        /* ij            1    2                                            3  */  
                   6128:        /* Tvaraff[ij]=  4    3                                            1  */
                   6129:        /* Tmodelind[ij]=2    3                                            9  */
                   6130:        /* TmodelInvind[ij]=2 1                                            1  */
1.242     brouard  6131:        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*/
                   6132:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   6133:        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 */
                   6134:        if(Fixed[k]!=0)
                   6135:         anyvaryingduminmodel=1;
                   6136:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   6137:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6138:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   6139:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   6140:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   6141:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6142:      } 
                   6143:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   6144:    /* ij--; */
                   6145:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
1.335     brouard  6146:    *cptcov=ij; /* cptcov= Number of total real effective simple dummies (fixed or time  arying) effective (used as cptcoveff in other functions)
1.242     brouard  6147:                * because they can be excluded from the model and real
                   6148:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   6149:    for(j=ij+1; j<= cptcovt; j++){
                   6150:      Tvaraff[j]=0;
                   6151:      Tmodelind[j]=0;
                   6152:    }
                   6153:    for(j=ntveff+1; j<= cptcovt; j++){
                   6154:      TmodelInvind[j]=0;
                   6155:    }
                   6156:    /* To be sorted */
                   6157:    ;
                   6158:  }
1.126     brouard  6159: 
1.145     brouard  6160: 
1.126     brouard  6161: /*********** Health Expectancies ****************/
                   6162: 
1.235     brouard  6163:  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  6164: 
                   6165: {
                   6166:   /* Health expectancies, no variances */
1.329     brouard  6167:   /* cij is the combination in the list of combination of dummy covariates */
                   6168:   /* strstart is a string of time at start of computing */
1.164     brouard  6169:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  6170:   int nhstepma, nstepma; /* Decreasing with age */
                   6171:   double age, agelim, hf;
                   6172:   double ***p3mat;
                   6173:   double eip;
                   6174: 
1.238     brouard  6175:   /* pstamp(ficreseij); */
1.126     brouard  6176:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   6177:   fprintf(ficreseij,"# Age");
                   6178:   for(i=1; i<=nlstate;i++){
                   6179:     for(j=1; j<=nlstate;j++){
                   6180:       fprintf(ficreseij," e%1d%1d ",i,j);
                   6181:     }
                   6182:     fprintf(ficreseij," e%1d. ",i);
                   6183:   }
                   6184:   fprintf(ficreseij,"\n");
                   6185: 
                   6186:   
                   6187:   if(estepm < stepm){
                   6188:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6189:   }
                   6190:   else  hstepm=estepm;   
                   6191:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6192:    * This is mainly to measure the difference between two models: for example
                   6193:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6194:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6195:    * progression in between and thus overestimating or underestimating according
                   6196:    * to the curvature of the survival function. If, for the same date, we 
                   6197:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6198:    * to compare the new estimate of Life expectancy with the same linear 
                   6199:    * hypothesis. A more precise result, taking into account a more precise
                   6200:    * curvature will be obtained if estepm is as small as stepm. */
                   6201: 
                   6202:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6203:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6204:      nhstepm is the number of hstepm from age to agelim 
                   6205:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  6206:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  6207:      and note for a fixed period like estepm months */
                   6208:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6209:      survival function given by stepm (the optimization length). Unfortunately it
                   6210:      means that if the survival funtion is printed only each two years of age and if
                   6211:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6212:      results. So we changed our mind and took the option of the best precision.
                   6213:   */
                   6214:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6215: 
                   6216:   agelim=AGESUP;
                   6217:   /* If stepm=6 months */
                   6218:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   6219:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   6220:     
                   6221: /* nhstepm age range expressed in number of stepm */
                   6222:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6223:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6224:   /* if (stepm >= YEARM) hstepm=1;*/
                   6225:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6226:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6227: 
                   6228:   for (age=bage; age<=fage; age ++){ 
                   6229:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6230:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6231:     /* if (stepm >= YEARM) hstepm=1;*/
                   6232:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   6233: 
                   6234:     /* If stepm=6 months */
                   6235:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6236:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
1.330     brouard  6237:     /* 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  6238:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  6239:     
                   6240:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6241:     
                   6242:     printf("%d|",(int)age);fflush(stdout);
                   6243:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6244:     
                   6245:     /* Computing expectancies */
                   6246:     for(i=1; i<=nlstate;i++)
                   6247:       for(j=1; j<=nlstate;j++)
                   6248:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6249:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   6250:          
                   6251:          /* 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]);*/
                   6252: 
                   6253:        }
                   6254: 
                   6255:     fprintf(ficreseij,"%3.0f",age );
                   6256:     for(i=1; i<=nlstate;i++){
                   6257:       eip=0;
                   6258:       for(j=1; j<=nlstate;j++){
                   6259:        eip +=eij[i][j][(int)age];
                   6260:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   6261:       }
                   6262:       fprintf(ficreseij,"%9.4f", eip );
                   6263:     }
                   6264:     fprintf(ficreseij,"\n");
                   6265:     
                   6266:   }
                   6267:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6268:   printf("\n");
                   6269:   fprintf(ficlog,"\n");
                   6270:   
                   6271: }
                   6272: 
1.235     brouard  6273:  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  6274: 
                   6275: {
                   6276:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  6277:      to initial status i, ei. .
1.126     brouard  6278:   */
1.336     brouard  6279:   /* Very time consuming function, but already optimized with precov */
1.126     brouard  6280:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   6281:   int nhstepma, nstepma; /* Decreasing with age */
                   6282:   double age, agelim, hf;
                   6283:   double ***p3matp, ***p3matm, ***varhe;
                   6284:   double **dnewm,**doldm;
                   6285:   double *xp, *xm;
                   6286:   double **gp, **gm;
                   6287:   double ***gradg, ***trgradg;
                   6288:   int theta;
                   6289: 
                   6290:   double eip, vip;
                   6291: 
                   6292:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   6293:   xp=vector(1,npar);
                   6294:   xm=vector(1,npar);
                   6295:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   6296:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   6297:   
                   6298:   pstamp(ficresstdeij);
                   6299:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   6300:   fprintf(ficresstdeij,"# Age");
                   6301:   for(i=1; i<=nlstate;i++){
                   6302:     for(j=1; j<=nlstate;j++)
                   6303:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   6304:     fprintf(ficresstdeij," e%1d. ",i);
                   6305:   }
                   6306:   fprintf(ficresstdeij,"\n");
                   6307: 
                   6308:   pstamp(ficrescveij);
                   6309:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   6310:   fprintf(ficrescveij,"# Age");
                   6311:   for(i=1; i<=nlstate;i++)
                   6312:     for(j=1; j<=nlstate;j++){
                   6313:       cptj= (j-1)*nlstate+i;
                   6314:       for(i2=1; i2<=nlstate;i2++)
                   6315:        for(j2=1; j2<=nlstate;j2++){
                   6316:          cptj2= (j2-1)*nlstate+i2;
                   6317:          if(cptj2 <= cptj)
                   6318:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   6319:        }
                   6320:     }
                   6321:   fprintf(ficrescveij,"\n");
                   6322:   
                   6323:   if(estepm < stepm){
                   6324:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6325:   }
                   6326:   else  hstepm=estepm;   
                   6327:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6328:    * This is mainly to measure the difference between two models: for example
                   6329:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6330:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6331:    * progression in between and thus overestimating or underestimating according
                   6332:    * to the curvature of the survival function. If, for the same date, we 
                   6333:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6334:    * to compare the new estimate of Life expectancy with the same linear 
                   6335:    * hypothesis. A more precise result, taking into account a more precise
                   6336:    * curvature will be obtained if estepm is as small as stepm. */
                   6337: 
                   6338:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6339:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6340:      nhstepm is the number of hstepm from age to agelim 
                   6341:      nstepm is the number of stepm from age to agelin. 
                   6342:      Look at hpijx to understand the reason of that which relies in memory size
                   6343:      and note for a fixed period like estepm months */
                   6344:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6345:      survival function given by stepm (the optimization length). Unfortunately it
                   6346:      means that if the survival funtion is printed only each two years of age and if
                   6347:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6348:      results. So we changed our mind and took the option of the best precision.
                   6349:   */
                   6350:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6351: 
                   6352:   /* If stepm=6 months */
                   6353:   /* nhstepm age range expressed in number of stepm */
                   6354:   agelim=AGESUP;
                   6355:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   6356:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6357:   /* if (stepm >= YEARM) hstepm=1;*/
                   6358:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6359:   
                   6360:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6361:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6362:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   6363:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   6364:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   6365:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   6366: 
                   6367:   for (age=bage; age<=fage; age ++){ 
                   6368:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6369:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6370:     /* if (stepm >= YEARM) hstepm=1;*/
                   6371:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  6372:                
1.126     brouard  6373:     /* If stepm=6 months */
                   6374:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6375:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   6376:     
                   6377:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  6378:                
1.126     brouard  6379:     /* Computing  Variances of health expectancies */
                   6380:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   6381:        decrease memory allocation */
                   6382:     for(theta=1; theta <=npar; theta++){
                   6383:       for(i=1; i<=npar; i++){ 
1.222     brouard  6384:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6385:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  6386:       }
1.235     brouard  6387:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   6388:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  6389:                        
1.126     brouard  6390:       for(j=1; j<= nlstate; j++){
1.222     brouard  6391:        for(i=1; i<=nlstate; i++){
                   6392:          for(h=0; h<=nhstepm-1; h++){
                   6393:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   6394:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   6395:          }
                   6396:        }
1.126     brouard  6397:       }
1.218     brouard  6398:                        
1.126     brouard  6399:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  6400:        for(h=0; h<=nhstepm-1; h++){
                   6401:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   6402:        }
1.126     brouard  6403:     }/* End theta */
                   6404:     
                   6405:     
                   6406:     for(h=0; h<=nhstepm-1; h++)
                   6407:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  6408:        for(theta=1; theta <=npar; theta++)
                   6409:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  6410:     
1.218     brouard  6411:                
1.222     brouard  6412:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  6413:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  6414:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  6415:                
1.222     brouard  6416:     printf("%d|",(int)age);fflush(stdout);
                   6417:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6418:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  6419:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  6420:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   6421:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   6422:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   6423:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   6424:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  6425:       }
                   6426:     }
1.320     brouard  6427:     /* if((int)age ==50){ */
                   6428:     /*   printf(" age=%d cij=%d nres=%d varhe[%d][%d]=%f ",(int)age, cij, nres, 1,2,varhe[1][2]); */
                   6429:     /* } */
1.126     brouard  6430:     /* Computing expectancies */
1.235     brouard  6431:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  6432:     for(i=1; i<=nlstate;i++)
                   6433:       for(j=1; j<=nlstate;j++)
1.222     brouard  6434:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6435:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  6436:                                        
1.222     brouard  6437:          /* 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  6438:                                        
1.222     brouard  6439:        }
1.269     brouard  6440: 
                   6441:     /* Standard deviation of expectancies ij */                
1.126     brouard  6442:     fprintf(ficresstdeij,"%3.0f",age );
                   6443:     for(i=1; i<=nlstate;i++){
                   6444:       eip=0.;
                   6445:       vip=0.;
                   6446:       for(j=1; j<=nlstate;j++){
1.222     brouard  6447:        eip += eij[i][j][(int)age];
                   6448:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   6449:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   6450:        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  6451:       }
                   6452:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   6453:     }
                   6454:     fprintf(ficresstdeij,"\n");
1.218     brouard  6455:                
1.269     brouard  6456:     /* Variance of expectancies ij */          
1.126     brouard  6457:     fprintf(ficrescveij,"%3.0f",age );
                   6458:     for(i=1; i<=nlstate;i++)
                   6459:       for(j=1; j<=nlstate;j++){
1.222     brouard  6460:        cptj= (j-1)*nlstate+i;
                   6461:        for(i2=1; i2<=nlstate;i2++)
                   6462:          for(j2=1; j2<=nlstate;j2++){
                   6463:            cptj2= (j2-1)*nlstate+i2;
                   6464:            if(cptj2 <= cptj)
                   6465:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   6466:          }
1.126     brouard  6467:       }
                   6468:     fprintf(ficrescveij,"\n");
1.218     brouard  6469:                
1.126     brouard  6470:   }
                   6471:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   6472:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   6473:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   6474:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   6475:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6476:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6477:   printf("\n");
                   6478:   fprintf(ficlog,"\n");
1.218     brouard  6479:        
1.126     brouard  6480:   free_vector(xm,1,npar);
                   6481:   free_vector(xp,1,npar);
                   6482:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   6483:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   6484:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   6485: }
1.218     brouard  6486:  
1.126     brouard  6487: /************ Variance ******************/
1.235     brouard  6488:  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  6489:  {
1.279     brouard  6490:    /** Variance of health expectancies 
                   6491:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   6492:     * double **newm;
                   6493:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   6494:     */
1.218     brouard  6495:   
                   6496:    /* int movingaverage(); */
                   6497:    double **dnewm,**doldm;
                   6498:    double **dnewmp,**doldmp;
                   6499:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  6500:    int first=0;
1.218     brouard  6501:    int k;
                   6502:    double *xp;
1.279     brouard  6503:    double **gp, **gm;  /**< for var eij */
                   6504:    double ***gradg, ***trgradg; /**< for var eij */
                   6505:    double **gradgp, **trgradgp; /**< for var p point j */
                   6506:    double *gpp, *gmp; /**< for var p point j */
                   6507:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
1.218     brouard  6508:    double ***p3mat;
                   6509:    double age,agelim, hf;
                   6510:    /* double ***mobaverage; */
                   6511:    int theta;
                   6512:    char digit[4];
                   6513:    char digitp[25];
                   6514: 
                   6515:    char fileresprobmorprev[FILENAMELENGTH];
                   6516: 
                   6517:    if(popbased==1){
                   6518:      if(mobilav!=0)
                   6519:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   6520:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   6521:    }
                   6522:    else 
                   6523:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  6524: 
1.218     brouard  6525:    /* if (mobilav!=0) { */
                   6526:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6527:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   6528:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   6529:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   6530:    /*   } */
                   6531:    /* } */
                   6532: 
                   6533:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   6534:    sprintf(digit,"%-d",ij);
                   6535:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   6536:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   6537:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   6538:    strcat(fileresprobmorprev,fileresu);
                   6539:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   6540:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   6541:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   6542:    }
                   6543:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6544:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6545:    pstamp(ficresprobmorprev);
                   6546:    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  6547:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
1.337   ! brouard  6548: 
        !          6549:    /* We use TinvDoQresult[nres][resultmodel[nres][j] we sort according to the equation model and the resultline: it is a choice */
        !          6550:    /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ /\* To be done*\/ */
        !          6551:    /*   fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
        !          6552:    /* } */
        !          6553:    for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */ /* To be done*/
        !          6554:      fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  6555:    }
1.337   ! brouard  6556:    /* for(j=1;j<=cptcoveff;j++)  */
        !          6557:    /*   fprintf(ficresprobmorprev," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,TnsdVar[Tvaraff[j]])]); */
1.238     brouard  6558:    fprintf(ficresprobmorprev,"\n");
                   6559: 
1.218     brouard  6560:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   6561:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6562:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   6563:      for(i=1; i<=nlstate;i++)
                   6564:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   6565:    }  
                   6566:    fprintf(ficresprobmorprev,"\n");
                   6567:   
                   6568:    fprintf(ficgp,"\n# Routine varevsij");
                   6569:    fprintf(ficgp,"\nunset title \n");
                   6570:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   6571:    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");
                   6572:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  6573: 
1.218     brouard  6574:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6575:    pstamp(ficresvij);
                   6576:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   6577:    if(popbased==1)
                   6578:      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);
                   6579:    else
                   6580:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   6581:    fprintf(ficresvij,"# Age");
                   6582:    for(i=1; i<=nlstate;i++)
                   6583:      for(j=1; j<=nlstate;j++)
                   6584:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   6585:    fprintf(ficresvij,"\n");
                   6586: 
                   6587:    xp=vector(1,npar);
                   6588:    dnewm=matrix(1,nlstate,1,npar);
                   6589:    doldm=matrix(1,nlstate,1,nlstate);
                   6590:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   6591:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6592: 
                   6593:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   6594:    gpp=vector(nlstate+1,nlstate+ndeath);
                   6595:    gmp=vector(nlstate+1,nlstate+ndeath);
                   6596:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  6597:   
1.218     brouard  6598:    if(estepm < stepm){
                   6599:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   6600:    }
                   6601:    else  hstepm=estepm;   
                   6602:    /* For example we decided to compute the life expectancy with the smallest unit */
                   6603:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6604:       nhstepm is the number of hstepm from age to agelim 
                   6605:       nstepm is the number of stepm from age to agelim. 
                   6606:       Look at function hpijx to understand why because of memory size limitations, 
                   6607:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   6608:       survival function given by stepm (the optimization length). Unfortunately it
                   6609:       means that if the survival funtion is printed every two years of age and if
                   6610:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6611:       results. So we changed our mind and took the option of the best precision.
                   6612:    */
                   6613:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6614:    agelim = AGESUP;
                   6615:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6616:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6617:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6618:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6619:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   6620:      gp=matrix(0,nhstepm,1,nlstate);
                   6621:      gm=matrix(0,nhstepm,1,nlstate);
                   6622:                
                   6623:                
                   6624:      for(theta=1; theta <=npar; theta++){
                   6625:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   6626:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6627:        }
1.279     brouard  6628:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   6629:        * returns into prlim .
1.288     brouard  6630:        */
1.242     brouard  6631:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  6632: 
                   6633:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  6634:        if (popbased==1) {
                   6635:         if(mobilav ==0){
                   6636:           for(i=1; i<=nlstate;i++)
                   6637:             prlim[i][i]=probs[(int)age][i][ij];
                   6638:         }else{ /* mobilav */ 
                   6639:           for(i=1; i<=nlstate;i++)
                   6640:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6641:         }
                   6642:        }
1.295     brouard  6643:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  6644:        */                      
                   6645:        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  6646:        /**< 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  6647:        * at horizon h in state j including mortality.
                   6648:        */
1.218     brouard  6649:        for(j=1; j<= nlstate; j++){
                   6650:         for(h=0; h<=nhstepm; h++){
                   6651:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   6652:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6653:         }
                   6654:        }
1.279     brouard  6655:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  6656:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  6657:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  6658:        */
                   6659:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6660:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   6661:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  6662:        }
                   6663:        
                   6664:        /* Again with minus shift */
1.218     brouard  6665:                        
                   6666:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   6667:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6668: 
1.242     brouard  6669:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  6670:                        
                   6671:        if (popbased==1) {
                   6672:         if(mobilav ==0){
                   6673:           for(i=1; i<=nlstate;i++)
                   6674:             prlim[i][i]=probs[(int)age][i][ij];
                   6675:         }else{ /* mobilav */ 
                   6676:           for(i=1; i<=nlstate;i++)
                   6677:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6678:         }
                   6679:        }
                   6680:                        
1.235     brouard  6681:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  6682:                        
                   6683:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   6684:         for(h=0; h<=nhstepm; h++){
                   6685:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   6686:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6687:         }
                   6688:        }
                   6689:        /* This for computing probability of death (h=1 means
                   6690:          computed over hstepm matrices product = hstepm*stepm months) 
                   6691:          as a weighted average of prlim.
                   6692:        */
                   6693:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6694:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   6695:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   6696:        }    
1.279     brouard  6697:        /* end shifting computations */
                   6698: 
                   6699:        /**< Computing gradient matrix at horizon h 
                   6700:        */
1.218     brouard  6701:        for(j=1; j<= nlstate; j++) /* vareij */
                   6702:         for(h=0; h<=nhstepm; h++){
                   6703:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   6704:         }
1.279     brouard  6705:        /**< Gradient of overall mortality p.3 (or p.j) 
                   6706:        */
                   6707:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
1.218     brouard  6708:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   6709:        }
                   6710:                        
                   6711:      } /* End theta */
1.279     brouard  6712:      
                   6713:      /* We got the gradient matrix for each theta and state j */               
1.218     brouard  6714:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   6715:                
                   6716:      for(h=0; h<=nhstepm; h++) /* veij */
                   6717:        for(j=1; j<=nlstate;j++)
                   6718:         for(theta=1; theta <=npar; theta++)
                   6719:           trgradg[h][j][theta]=gradg[h][theta][j];
                   6720:                
                   6721:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   6722:        for(theta=1; theta <=npar; theta++)
                   6723:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  6724:      /**< as well as its transposed matrix 
                   6725:       */               
1.218     brouard  6726:                
                   6727:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6728:      for(i=1;i<=nlstate;i++)
                   6729:        for(j=1;j<=nlstate;j++)
                   6730:         vareij[i][j][(int)age] =0.;
1.279     brouard  6731: 
                   6732:      /* Computing trgradg by matcov by gradg at age and summing over h
                   6733:       * and k (nhstepm) formula 15 of article
                   6734:       * Lievre-Brouard-Heathcote
                   6735:       */
                   6736:      
1.218     brouard  6737:      for(h=0;h<=nhstepm;h++){
                   6738:        for(k=0;k<=nhstepm;k++){
                   6739:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   6740:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   6741:         for(i=1;i<=nlstate;i++)
                   6742:           for(j=1;j<=nlstate;j++)
                   6743:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   6744:        }
                   6745:      }
                   6746:                
1.279     brouard  6747:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
                   6748:       * p.j overall mortality formula 49 but computed directly because
                   6749:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   6750:       * wix is independent of theta.
                   6751:       */
1.218     brouard  6752:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   6753:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   6754:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   6755:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   6756:         varppt[j][i]=doldmp[j][i];
                   6757:      /* end ppptj */
                   6758:      /*  x centered again */
                   6759:                
1.242     brouard  6760:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  6761:                
                   6762:      if (popbased==1) {
                   6763:        if(mobilav ==0){
                   6764:         for(i=1; i<=nlstate;i++)
                   6765:           prlim[i][i]=probs[(int)age][i][ij];
                   6766:        }else{ /* mobilav */ 
                   6767:         for(i=1; i<=nlstate;i++)
                   6768:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   6769:        }
                   6770:      }
                   6771:                
                   6772:      /* This for computing probability of death (h=1 means
                   6773:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   6774:        as a weighted average of prlim.
                   6775:      */
1.235     brouard  6776:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  6777:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6778:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   6779:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   6780:      }    
                   6781:      /* end probability of death */
                   6782:                
                   6783:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   6784:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6785:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   6786:        for(i=1; i<=nlstate;i++){
                   6787:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   6788:        }
                   6789:      } 
                   6790:      fprintf(ficresprobmorprev,"\n");
                   6791:                
                   6792:      fprintf(ficresvij,"%.0f ",age );
                   6793:      for(i=1; i<=nlstate;i++)
                   6794:        for(j=1; j<=nlstate;j++){
                   6795:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   6796:        }
                   6797:      fprintf(ficresvij,"\n");
                   6798:      free_matrix(gp,0,nhstepm,1,nlstate);
                   6799:      free_matrix(gm,0,nhstepm,1,nlstate);
                   6800:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   6801:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   6802:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6803:    } /* End age */
                   6804:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   6805:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   6806:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   6807:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   6808:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   6809:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   6810:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   6811:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   6812:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   6813:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   6814:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6815:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6816:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   6817:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   6818:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   6819:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   6820:    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);
                   6821:    /*  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  6822:     */
1.218     brouard  6823:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   6824:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  6825: 
1.218     brouard  6826:    free_vector(xp,1,npar);
                   6827:    free_matrix(doldm,1,nlstate,1,nlstate);
                   6828:    free_matrix(dnewm,1,nlstate,1,npar);
                   6829:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6830:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   6831:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6832:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6833:    fclose(ficresprobmorprev);
                   6834:    fflush(ficgp);
                   6835:    fflush(fichtm); 
                   6836:  }  /* end varevsij */
1.126     brouard  6837: 
                   6838: /************ Variance of prevlim ******************/
1.269     brouard  6839:  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  6840: {
1.205     brouard  6841:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  6842:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  6843: 
1.268     brouard  6844:   double **dnewmpar,**doldm;
1.126     brouard  6845:   int i, j, nhstepm, hstepm;
                   6846:   double *xp;
                   6847:   double *gp, *gm;
                   6848:   double **gradg, **trgradg;
1.208     brouard  6849:   double **mgm, **mgp;
1.126     brouard  6850:   double age,agelim;
                   6851:   int theta;
                   6852:   
                   6853:   pstamp(ficresvpl);
1.288     brouard  6854:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  6855:   fprintf(ficresvpl,"# Age ");
                   6856:   if(nresult >=1)
                   6857:     fprintf(ficresvpl," Result# ");
1.126     brouard  6858:   for(i=1; i<=nlstate;i++)
                   6859:       fprintf(ficresvpl," %1d-%1d",i,i);
                   6860:   fprintf(ficresvpl,"\n");
                   6861: 
                   6862:   xp=vector(1,npar);
1.268     brouard  6863:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  6864:   doldm=matrix(1,nlstate,1,nlstate);
                   6865:   
                   6866:   hstepm=1*YEARM; /* Every year of age */
                   6867:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   6868:   agelim = AGESUP;
                   6869:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6870:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6871:     if (stepm >= YEARM) hstepm=1;
                   6872:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6873:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  6874:     mgp=matrix(1,npar,1,nlstate);
                   6875:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  6876:     gp=vector(1,nlstate);
                   6877:     gm=vector(1,nlstate);
                   6878: 
                   6879:     for(theta=1; theta <=npar; theta++){
                   6880:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   6881:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6882:       }
1.288     brouard  6883:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6884:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6885:       /* else */
                   6886:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6887:       for(i=1;i<=nlstate;i++){
1.126     brouard  6888:        gp[i] = prlim[i][i];
1.208     brouard  6889:        mgp[theta][i] = prlim[i][i];
                   6890:       }
1.126     brouard  6891:       for(i=1; i<=npar; i++) /* Computes gradient */
                   6892:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6893:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6894:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6895:       /* else */
                   6896:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6897:       for(i=1;i<=nlstate;i++){
1.126     brouard  6898:        gm[i] = prlim[i][i];
1.208     brouard  6899:        mgm[theta][i] = prlim[i][i];
                   6900:       }
1.126     brouard  6901:       for(i=1;i<=nlstate;i++)
                   6902:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  6903:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  6904:     } /* End theta */
                   6905: 
                   6906:     trgradg =matrix(1,nlstate,1,npar);
                   6907: 
                   6908:     for(j=1; j<=nlstate;j++)
                   6909:       for(theta=1; theta <=npar; theta++)
                   6910:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  6911:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6912:     /*   printf("\nmgm mgp %d ",(int)age); */
                   6913:     /*   for(j=1; j<=nlstate;j++){ */
                   6914:     /*         printf(" %d ",j); */
                   6915:     /*         for(theta=1; theta <=npar; theta++) */
                   6916:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   6917:     /*         printf("\n "); */
                   6918:     /*   } */
                   6919:     /* } */
                   6920:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6921:     /*   printf("\n gradg %d ",(int)age); */
                   6922:     /*   for(j=1; j<=nlstate;j++){ */
                   6923:     /*         printf("%d ",j); */
                   6924:     /*         for(theta=1; theta <=npar; theta++) */
                   6925:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   6926:     /*         printf("\n "); */
                   6927:     /*   } */
                   6928:     /* } */
1.126     brouard  6929: 
                   6930:     for(i=1;i<=nlstate;i++)
                   6931:       varpl[i][(int)age] =0.;
1.209     brouard  6932:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  6933:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6934:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6935:     }else{
1.268     brouard  6936:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6937:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6938:     }
1.126     brouard  6939:     for(i=1;i<=nlstate;i++)
                   6940:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   6941: 
                   6942:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  6943:     if(nresult >=1)
                   6944:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  6945:     for(i=1; i<=nlstate;i++){
1.126     brouard  6946:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  6947:       /* for(j=1;j<=nlstate;j++) */
                   6948:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   6949:     }
1.126     brouard  6950:     fprintf(ficresvpl,"\n");
                   6951:     free_vector(gp,1,nlstate);
                   6952:     free_vector(gm,1,nlstate);
1.208     brouard  6953:     free_matrix(mgm,1,npar,1,nlstate);
                   6954:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  6955:     free_matrix(gradg,1,npar,1,nlstate);
                   6956:     free_matrix(trgradg,1,nlstate,1,npar);
                   6957:   } /* End age */
                   6958: 
                   6959:   free_vector(xp,1,npar);
                   6960:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  6961:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   6962: 
                   6963: }
                   6964: 
                   6965: 
                   6966: /************ Variance of backprevalence limit ******************/
1.269     brouard  6967:  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  6968: {
                   6969:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   6970:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   6971: 
                   6972:   double **dnewmpar,**doldm;
                   6973:   int i, j, nhstepm, hstepm;
                   6974:   double *xp;
                   6975:   double *gp, *gm;
                   6976:   double **gradg, **trgradg;
                   6977:   double **mgm, **mgp;
                   6978:   double age,agelim;
                   6979:   int theta;
                   6980:   
                   6981:   pstamp(ficresvbl);
                   6982:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   6983:   fprintf(ficresvbl,"# Age ");
                   6984:   if(nresult >=1)
                   6985:     fprintf(ficresvbl," Result# ");
                   6986:   for(i=1; i<=nlstate;i++)
                   6987:       fprintf(ficresvbl," %1d-%1d",i,i);
                   6988:   fprintf(ficresvbl,"\n");
                   6989: 
                   6990:   xp=vector(1,npar);
                   6991:   dnewmpar=matrix(1,nlstate,1,npar);
                   6992:   doldm=matrix(1,nlstate,1,nlstate);
                   6993:   
                   6994:   hstepm=1*YEARM; /* Every year of age */
                   6995:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   6996:   agelim = AGEINF;
                   6997:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   6998:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6999:     if (stepm >= YEARM) hstepm=1;
                   7000:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7001:     gradg=matrix(1,npar,1,nlstate);
                   7002:     mgp=matrix(1,npar,1,nlstate);
                   7003:     mgm=matrix(1,npar,1,nlstate);
                   7004:     gp=vector(1,nlstate);
                   7005:     gm=vector(1,nlstate);
                   7006: 
                   7007:     for(theta=1; theta <=npar; theta++){
                   7008:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   7009:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7010:       }
                   7011:       if(mobilavproj > 0 )
                   7012:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7013:       else
                   7014:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7015:       for(i=1;i<=nlstate;i++){
                   7016:        gp[i] = bprlim[i][i];
                   7017:        mgp[theta][i] = bprlim[i][i];
                   7018:       }
                   7019:      for(i=1; i<=npar; i++) /* Computes gradient */
                   7020:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   7021:        if(mobilavproj > 0 )
                   7022:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7023:        else
                   7024:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7025:       for(i=1;i<=nlstate;i++){
                   7026:        gm[i] = bprlim[i][i];
                   7027:        mgm[theta][i] = bprlim[i][i];
                   7028:       }
                   7029:       for(i=1;i<=nlstate;i++)
                   7030:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   7031:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   7032:     } /* End theta */
                   7033: 
                   7034:     trgradg =matrix(1,nlstate,1,npar);
                   7035: 
                   7036:     for(j=1; j<=nlstate;j++)
                   7037:       for(theta=1; theta <=npar; theta++)
                   7038:        trgradg[j][theta]=gradg[theta][j];
                   7039:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7040:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7041:     /*   for(j=1; j<=nlstate;j++){ */
                   7042:     /*         printf(" %d ",j); */
                   7043:     /*         for(theta=1; theta <=npar; theta++) */
                   7044:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7045:     /*         printf("\n "); */
                   7046:     /*   } */
                   7047:     /* } */
                   7048:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7049:     /*   printf("\n gradg %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 ",theta,gradg[theta][j]); */
                   7054:     /*         printf("\n "); */
                   7055:     /*   } */
                   7056:     /* } */
                   7057: 
                   7058:     for(i=1;i<=nlstate;i++)
                   7059:       varbpl[i][(int)age] =0.;
                   7060:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   7061:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7062:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7063:     }else{
                   7064:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7065:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7066:     }
                   7067:     for(i=1;i<=nlstate;i++)
                   7068:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7069: 
                   7070:     fprintf(ficresvbl,"%.0f ",age );
                   7071:     if(nresult >=1)
                   7072:       fprintf(ficresvbl,"%d ",nres );
                   7073:     for(i=1; i<=nlstate;i++)
                   7074:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   7075:     fprintf(ficresvbl,"\n");
                   7076:     free_vector(gp,1,nlstate);
                   7077:     free_vector(gm,1,nlstate);
                   7078:     free_matrix(mgm,1,npar,1,nlstate);
                   7079:     free_matrix(mgp,1,npar,1,nlstate);
                   7080:     free_matrix(gradg,1,npar,1,nlstate);
                   7081:     free_matrix(trgradg,1,nlstate,1,npar);
                   7082:   } /* End age */
                   7083: 
                   7084:   free_vector(xp,1,npar);
                   7085:   free_matrix(doldm,1,nlstate,1,npar);
                   7086:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  7087: 
                   7088: }
                   7089: 
                   7090: /************ Variance of one-step probabilities  ******************/
                   7091: 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  7092:  {
                   7093:    int i, j=0,  k1, l1, tj;
                   7094:    int k2, l2, j1,  z1;
                   7095:    int k=0, l;
                   7096:    int first=1, first1, first2;
1.326     brouard  7097:    int nres=0; /* New */
1.222     brouard  7098:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   7099:    double **dnewm,**doldm;
                   7100:    double *xp;
                   7101:    double *gp, *gm;
                   7102:    double **gradg, **trgradg;
                   7103:    double **mu;
                   7104:    double age, cov[NCOVMAX+1];
                   7105:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   7106:    int theta;
                   7107:    char fileresprob[FILENAMELENGTH];
                   7108:    char fileresprobcov[FILENAMELENGTH];
                   7109:    char fileresprobcor[FILENAMELENGTH];
                   7110:    double ***varpij;
                   7111: 
                   7112:    strcpy(fileresprob,"PROB_"); 
                   7113:    strcat(fileresprob,fileres);
                   7114:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   7115:      printf("Problem with resultfile: %s\n", fileresprob);
                   7116:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   7117:    }
                   7118:    strcpy(fileresprobcov,"PROBCOV_"); 
                   7119:    strcat(fileresprobcov,fileresu);
                   7120:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   7121:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   7122:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   7123:    }
                   7124:    strcpy(fileresprobcor,"PROBCOR_"); 
                   7125:    strcat(fileresprobcor,fileresu);
                   7126:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   7127:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   7128:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   7129:    }
                   7130:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7131:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7132:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7133:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7134:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7135:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7136:    pstamp(ficresprob);
                   7137:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   7138:    fprintf(ficresprob,"# Age");
                   7139:    pstamp(ficresprobcov);
                   7140:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   7141:    fprintf(ficresprobcov,"# Age");
                   7142:    pstamp(ficresprobcor);
                   7143:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   7144:    fprintf(ficresprobcor,"# Age");
1.126     brouard  7145: 
                   7146: 
1.222     brouard  7147:    for(i=1; i<=nlstate;i++)
                   7148:      for(j=1; j<=(nlstate+ndeath);j++){
                   7149:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   7150:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   7151:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   7152:      }  
                   7153:    /* fprintf(ficresprob,"\n");
                   7154:       fprintf(ficresprobcov,"\n");
                   7155:       fprintf(ficresprobcor,"\n");
                   7156:    */
                   7157:    xp=vector(1,npar);
                   7158:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7159:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7160:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   7161:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   7162:    first=1;
                   7163:    fprintf(ficgp,"\n# Routine varprob");
                   7164:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   7165:    fprintf(fichtm,"\n");
                   7166: 
1.288     brouard  7167:    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  7168:    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);
                   7169:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  7170: and drawn. It helps understanding how is the covariance between two incidences.\
                   7171:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  7172:    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  7173: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   7174: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   7175: standard deviations wide on each axis. <br>\
                   7176:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   7177:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   7178: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   7179: 
1.222     brouard  7180:    cov[1]=1;
                   7181:    /* tj=cptcoveff; */
1.225     brouard  7182:    tj = (int) pow(2,cptcoveff);
1.222     brouard  7183:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   7184:    j1=0;
1.332     brouard  7185: 
                   7186:    for(nres=1;nres <=nresult; nres++){ /* For each resultline */
                   7187:    for(j1=1; j1<=tj;j1++){ /* For any combination of dummy covariates, fixed and varying */
1.334     brouard  7188:      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  7189:      if(tj != 1 && TKresult[nres]!= j1)
                   7190:        continue;
                   7191: 
                   7192:    /* for(j1=1; j1<=tj;j1++){  /\* For each valid combination of covariates or only once*\/ */
                   7193:      /* for(nres=1;nres <=1; nres++){ /\* For each resultline *\/ */
                   7194:      /* /\* for(nres=1;nres <=nresult; nres++){ /\\* For each resultline *\\/ *\/ */
1.222     brouard  7195:      if  (cptcovn>0) {
1.334     brouard  7196:        fprintf(ficresprob, "\n#********** Variable ");
                   7197:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   7198:        fprintf(ficgp, "\n#********** Variable ");
                   7199:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   7200:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   7201: 
                   7202:        /* Including quantitative variables of the resultline to be done */
                   7203:        for (z1=1; z1<=cptcovs; z1++){ /* Loop on each variable of this resultline  */
                   7204:         printf("Varprob modelresult[%d][%d]=%d model=%s \n",nres, z1, modelresult[nres][z1], model);
                   7205:         fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=%s \n",nres, z1, modelresult[nres][z1], model);
                   7206:         /* fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=%s resultline[%d]=%s \n",nres, z1, modelresult[nres][z1], model, nres, resultline[nres]); */
                   7207:         if(Dummy[modelresult[nres][z1]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to z1 in resultline  */
                   7208:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed referenced to model equation */
                   7209:             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  */
                   7210:             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  */
                   7211:             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  */
                   7212:             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  */
                   7213:             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  */
                   7214:             fprintf(ficresprob,"fixed ");
                   7215:             fprintf(ficresprobcov,"fixed ");
                   7216:             fprintf(ficgp,"fixed ");
                   7217:             fprintf(fichtmcov,"fixed ");
                   7218:             fprintf(ficresprobcor,"fixed ");
                   7219:           }else{
                   7220:             fprintf(ficresprob,"varyi ");
                   7221:             fprintf(ficresprobcov,"varyi ");
                   7222:             fprintf(ficgp,"varyi ");
                   7223:             fprintf(fichtmcov,"varyi ");
                   7224:             fprintf(ficresprobcor,"varyi ");
                   7225:           }
                   7226:         }else if(Dummy[modelresult[nres][z1]]==1){ /* Quanti variable */
                   7227:           /* For each selected (single) quantitative value */
1.337   ! brouard  7228:           fprintf(ficresprob," V%d=%lg ",Tvqresult[nres][z1],Tqresult[nres][z1]);
1.334     brouard  7229:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed */
                   7230:             fprintf(ficresprob,"fixed ");
                   7231:             fprintf(ficresprobcov,"fixed ");
                   7232:             fprintf(ficgp,"fixed ");
                   7233:             fprintf(fichtmcov,"fixed ");
                   7234:             fprintf(ficresprobcor,"fixed ");
                   7235:           }else{
                   7236:             fprintf(ficresprob,"varyi ");
                   7237:             fprintf(ficresprobcov,"varyi ");
                   7238:             fprintf(ficgp,"varyi ");
                   7239:             fprintf(fichtmcov,"varyi ");
                   7240:             fprintf(ficresprobcor,"varyi ");
                   7241:           }
                   7242:         }else{
                   7243:           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 */
                   7244:           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 */
                   7245:           exit(1);
                   7246:         }
                   7247:        } /* End loop on variable of this resultline */
                   7248:        /* for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]); */
1.222     brouard  7249:        fprintf(ficresprob, "**********\n#\n");
                   7250:        fprintf(ficresprobcov, "**********\n#\n");
                   7251:        fprintf(ficgp, "**********\n#\n");
                   7252:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   7253:        fprintf(ficresprobcor, "**********\n#");    
                   7254:        if(invalidvarcomb[j1]){
                   7255:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   7256:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   7257:         continue;
                   7258:        }
                   7259:      }
                   7260:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   7261:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7262:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   7263:      gm=vector(1,(nlstate)*(nlstate+ndeath));
1.334     brouard  7264:      for (age=bage; age<=fage; age ++){ /* Fo each age we feed the model equation with covariates, using precov as in hpxij() ? */
1.222     brouard  7265:        cov[2]=age;
                   7266:        if(nagesqr==1)
                   7267:         cov[3]= age*age;
1.334     brouard  7268:        /* New code end of combination but for each resultline */
                   7269:        for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   7270:         if(Typevar[k1]==1){ /* A product with age */
                   7271:           cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.326     brouard  7272:         }else{
1.334     brouard  7273:           cov[2+nagesqr+k1]=precov[nres][k1];
1.326     brouard  7274:         }
1.334     brouard  7275:        }/* End of loop on model equation */
                   7276: /* Old code */
                   7277:        /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   7278:        /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)]; *\/ */
                   7279:        /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   7280:        /*       /\* Here comes the value of the covariate 'j1' after renumbering k with single dummy covariates *\/ */
                   7281:        /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(j1,TnsdVar[TvarsD[k]])]; */
                   7282:        /*       /\*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*\//\* j1 1 2 3 4 */
                   7283:        /*                                                                  * 1  1 1 1 1 */
                   7284:        /*                                                                  * 2  2 1 1 1 */
                   7285:        /*                                                                  * 3  1 2 1 1 */
                   7286:        /*                                                                  *\/ */
                   7287:        /*       /\* nbcode[1][1]=0 nbcode[1][2]=1;*\/ */
                   7288:        /* } */
                   7289:        /* /\* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   7290:        /* /\* ) p nbcode[Tvar[Tage[k]]][(1 & (ij-1) >> (k-1))+1] *\/ */
                   7291:        /* /\*for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; *\/ */
                   7292:        /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   7293:        /*       if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   7294:        /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(j1,TnsdVar[Tvar[Tage[k]]])]*cov[2]; */
                   7295:        /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7296:        /*       } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   7297:        /*         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]); */
                   7298:        /*         /\* cov[2+nagesqr+Tage[k]]=meanq[k]/idq[k]*cov[2];/\\* Using the mean of quantitative variable Tvar[Tage[k]] /\\* Tqresult[nres][k]; *\\/ *\/ */
                   7299:        /*         /\* exit(1); *\/ */
                   7300:        /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   7301:        /*       } */
                   7302:        /*       /\* cov[2+Tage[k]+nagesqr]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7303:        /* } */
                   7304:        /* for (k=1; k<=cptcovprod;k++){/\* For product without age *\/ */
                   7305:        /*       if(Dummy[Tvard[k][1]]==0){ */
                   7306:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7307:        /*           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]])]; */
                   7308:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7309:        /*         }else{ /\* Should we use the mean of the quantitative variables? *\/ */
                   7310:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,TnsdVar[Tvard[k][1]])] * Tqresult[nres][resultmodel[nres][k]]; */
                   7311:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   7312:        /*         } */
                   7313:        /*       }else{ */
                   7314:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7315:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(j1,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][TnsdVar[Tvard[k][1]]]; */
                   7316:        /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   7317:        /*         }else{ */
                   7318:        /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][TnsdVar[Tvard[k][1]]]*  Tqinvresult[nres][TnsdVar[Tvard[k][2]]]; */
                   7319:        /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   7320:        /*         } */
                   7321:        /*       } */
                   7322:        /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7323:        /* } */                 
1.326     brouard  7324: /* For each age and combination of dummy covariates we slightly move the parameters of delti in order to get the gradient*/                    
1.222     brouard  7325:        for(theta=1; theta <=npar; theta++){
                   7326:         for(i=1; i<=npar; i++)
                   7327:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  7328:                                
1.222     brouard  7329:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  7330:                                
1.222     brouard  7331:         k=0;
                   7332:         for(i=1; i<= (nlstate); i++){
                   7333:           for(j=1; j<=(nlstate+ndeath);j++){
                   7334:             k=k+1;
                   7335:             gp[k]=pmmij[i][j];
                   7336:           }
                   7337:         }
1.220     brouard  7338:                                
1.222     brouard  7339:         for(i=1; i<=npar; i++)
                   7340:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  7341:                                
1.222     brouard  7342:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   7343:         k=0;
                   7344:         for(i=1; i<=(nlstate); i++){
                   7345:           for(j=1; j<=(nlstate+ndeath);j++){
                   7346:             k=k+1;
                   7347:             gm[k]=pmmij[i][j];
                   7348:           }
                   7349:         }
1.220     brouard  7350:                                
1.222     brouard  7351:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   7352:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   7353:        }
1.126     brouard  7354: 
1.222     brouard  7355:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   7356:         for(theta=1; theta <=npar; theta++)
                   7357:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  7358:                        
1.222     brouard  7359:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   7360:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  7361:                        
1.222     brouard  7362:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  7363:                        
1.222     brouard  7364:        k=0;
                   7365:        for(i=1; i<=(nlstate); i++){
                   7366:         for(j=1; j<=(nlstate+ndeath);j++){
                   7367:           k=k+1;
                   7368:           mu[k][(int) age]=pmmij[i][j];
                   7369:         }
                   7370:        }
                   7371:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   7372:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   7373:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  7374:                        
1.222     brouard  7375:        /*printf("\n%d ",(int)age);
                   7376:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7377:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7378:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7379:         }*/
1.220     brouard  7380:                        
1.222     brouard  7381:        fprintf(ficresprob,"\n%d ",(int)age);
                   7382:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   7383:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  7384:                        
1.222     brouard  7385:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   7386:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   7387:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7388:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   7389:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   7390:        }
                   7391:        i=0;
                   7392:        for (k=1; k<=(nlstate);k++){
                   7393:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   7394:           i++;
                   7395:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   7396:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   7397:           for (j=1; j<=i;j++){
                   7398:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   7399:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   7400:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   7401:           }
                   7402:         }
                   7403:        }/* end of loop for state */
                   7404:      } /* end of loop for age */
                   7405:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7406:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7407:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7408:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7409:     
                   7410:      /* Confidence intervalle of pij  */
                   7411:      /*
                   7412:        fprintf(ficgp,"\nunset parametric;unset label");
                   7413:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   7414:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   7415:        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);
                   7416:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   7417:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   7418:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   7419:      */
                   7420:                
                   7421:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   7422:      first1=1;first2=2;
                   7423:      for (k2=1; k2<=(nlstate);k2++){
                   7424:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   7425:         if(l2==k2) continue;
                   7426:         j=(k2-1)*(nlstate+ndeath)+l2;
                   7427:         for (k1=1; k1<=(nlstate);k1++){
                   7428:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   7429:             if(l1==k1) continue;
                   7430:             i=(k1-1)*(nlstate+ndeath)+l1;
                   7431:             if(i<=j) continue;
                   7432:             for (age=bage; age<=fage; age ++){ 
                   7433:               if ((int)age %5==0){
                   7434:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   7435:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7436:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7437:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   7438:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   7439:                 c12=cv12/sqrt(v1*v2);
                   7440:                 /* Computing eigen value of matrix of covariance */
                   7441:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7442:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7443:                 if ((lc2 <0) || (lc1 <0) ){
                   7444:                   if(first2==1){
                   7445:                     first1=0;
                   7446:                     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);
                   7447:                   }
                   7448:                   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);
                   7449:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   7450:                   /* lc2=fabs(lc2); */
                   7451:                 }
1.220     brouard  7452:                                                                
1.222     brouard  7453:                 /* Eigen vectors */
1.280     brouard  7454:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   7455:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7456:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7457:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   7458:                 }else
                   7459:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  7460:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   7461:                 v21=(lc1-v1)/cv12*v11;
                   7462:                 v12=-v21;
                   7463:                 v22=v11;
                   7464:                 tnalp=v21/v11;
                   7465:                 if(first1==1){
                   7466:                   first1=0;
                   7467:                   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);
                   7468:                 }
                   7469:                 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);
                   7470:                 /*printf(fignu*/
                   7471:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   7472:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   7473:                 if(first==1){
                   7474:                   first=0;
                   7475:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   7476:                   fprintf(ficgp,"\nset parametric;unset label");
                   7477:                   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);
                   7478:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  7479:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  7480:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  7481: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  7482:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   7483:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7484:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7485:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   7486:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7487:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7488:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7489:                   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  7490:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   7491:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  7492:                 }else{
                   7493:                   first=0;
                   7494:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   7495:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7496:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7497:                   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  7498:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   7499:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  7500:                 }/* if first */
                   7501:               } /* age mod 5 */
                   7502:             } /* end loop age */
                   7503:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7504:             first=1;
                   7505:           } /*l12 */
                   7506:         } /* k12 */
                   7507:        } /*l1 */
                   7508:      }/* k1 */
1.332     brouard  7509:    }  /* loop on combination of covariates j1 */
1.326     brouard  7510:    } /* loop on nres */
1.222     brouard  7511:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   7512:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   7513:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7514:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   7515:    free_vector(xp,1,npar);
                   7516:    fclose(ficresprob);
                   7517:    fclose(ficresprobcov);
                   7518:    fclose(ficresprobcor);
                   7519:    fflush(ficgp);
                   7520:    fflush(fichtmcov);
                   7521:  }
1.126     brouard  7522: 
                   7523: 
                   7524: /******************* Printing html file ***********/
1.201     brouard  7525: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  7526:                  int lastpass, int stepm, int weightopt, char model[],\
                   7527:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  7528:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   7529:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   7530:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.237     brouard  7531:   int jj1, k1, i1, cpt, k4, nres;
1.319     brouard  7532:   /* In fact some results are already printed in fichtm which is open */
1.126     brouard  7533:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   7534:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   7535: </ul>");
1.319     brouard  7536: /*    fprintf(fichtm,"<ul><li> model=1+age+%s\n \ */
                   7537: /* </ul>", model); */
1.214     brouard  7538:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   7539:    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",
                   7540:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
1.332     brouard  7541:    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  7542:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   7543:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  7544:    fprintf(fichtm,"\
                   7545:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  7546:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  7547:    fprintf(fichtm,"\
1.217     brouard  7548:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   7549:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   7550:    fprintf(fichtm,"\
1.288     brouard  7551:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7552:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  7553:    fprintf(fichtm,"\
1.288     brouard  7554:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  7555:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   7556:    fprintf(fichtm,"\
1.211     brouard  7557:  - (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  7558:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7559:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  7560:    if(prevfcast==1){
                   7561:      fprintf(fichtm,"\
                   7562:  - Prevalence projections by age and states:                           \
1.201     brouard  7563:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  7564:    }
1.126     brouard  7565: 
                   7566: 
1.225     brouard  7567:    m=pow(2,cptcoveff);
1.222     brouard  7568:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7569: 
1.317     brouard  7570:    fprintf(fichtm," \n<ul><li><b>Graphs (first order)</b></li><p>");
1.264     brouard  7571: 
                   7572:    jj1=0;
                   7573: 
                   7574:    fprintf(fichtm," \n<ul>");
1.337   ! brouard  7575:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
        !          7576:      /* k1=nres; */
        !          7577:      k1= TKresult[nres];
        !          7578:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
        !          7579:    /*   if(m != 1 && TKresult[nres]!= k1) */
        !          7580:    /*     continue; */
1.264     brouard  7581:      jj1++;
                   7582:      if (cptcovn > 0) {
                   7583:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
1.337   ! brouard  7584:        for (cpt=1; cpt<=cptcovs;cpt++){ /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
        !          7585:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  7586:        }
1.337   ! brouard  7587:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
        !          7588:        /*       fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
        !          7589:        /* } */
        !          7590:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
        !          7591:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
        !          7592:        /* } */
1.264     brouard  7593:        fprintf(fichtm,"\">");
                   7594:        
                   7595:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   7596:        fprintf(fichtm,"************ Results for covariates");
1.337   ! brouard  7597:        for (cpt=1; cpt<=cptcovs;cpt++){ 
        !          7598:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  7599:        }
1.337   ! brouard  7600:        /* fprintf(fichtm,"************ Results for covariates"); */
        !          7601:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
        !          7602:        /*       fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
        !          7603:        /* } */
        !          7604:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
        !          7605:        /*       fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
        !          7606:        /* } */
1.264     brouard  7607:        if(invalidvarcomb[k1]){
                   7608:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   7609:         continue;
                   7610:        }
                   7611:        fprintf(fichtm,"</a></li>");
                   7612:      } /* cptcovn >0 */
                   7613:    }
1.317     brouard  7614:    fprintf(fichtm," \n</ul>");
1.264     brouard  7615: 
1.222     brouard  7616:    jj1=0;
1.237     brouard  7617: 
1.337   ! brouard  7618:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
        !          7619:      /* k1=nres; */
        !          7620:      k1= TKresult[nres];
        !          7621:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
        !          7622:    /*   if(m != 1 && TKresult[nres]!= k1) */
        !          7623:    /*     continue; */
1.220     brouard  7624: 
1.222     brouard  7625:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7626:      jj1++;
                   7627:      if (cptcovn > 0) {
1.264     brouard  7628:        fprintf(fichtm,"\n<p><a name=\"rescov");
1.337   ! brouard  7629:        for (cpt=1; cpt<=cptcovs;cpt++){ 
        !          7630:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  7631:        }
1.337   ! brouard  7632:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
        !          7633:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
        !          7634:        /* } */
1.264     brouard  7635:        fprintf(fichtm,"\"</a>");
                   7636:  
1.222     brouard  7637:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337   ! brouard  7638:        for (cpt=1; cpt<=cptcovs;cpt++){ 
        !          7639:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
        !          7640:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  7641:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   7642:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  7643:        }
1.230     brouard  7644:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.321     brouard  7645:        fprintf(fichtm," (model=%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.222     brouard  7646:        if(invalidvarcomb[k1]){
                   7647:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   7648:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   7649:         continue;
                   7650:        }
                   7651:      }
                   7652:      /* aij, bij */
1.259     brouard  7653:      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  7654: <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  7655:      /* Pij */
1.241     brouard  7656:      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> \
                   7657: <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  7658:      /* Quasi-incidences */
                   7659:      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  7660:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  7661:  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  7662: 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> \
                   7663: <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  7664:      /* Survival functions (period) in state j */
                   7665:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  7666:        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);
                   7667:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   7668:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.222     brouard  7669:      }
                   7670:      /* State specific survival functions (period) */
                   7671:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  7672:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
                   7673:  And probability to be observed in various states (up to %d) being in state %d at different ages.      \
1.329     brouard  7674:  <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);
                   7675:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   7676:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.222     brouard  7677:      }
1.288     brouard  7678:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  7679:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  7680:        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);
                   7681:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"P_"),subdirf2(optionfilefiname,"P_"));
                   7682:       fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.222     brouard  7683:      }
1.296     brouard  7684:      if(prevbcast==1){
1.288     brouard  7685:        /* Backward prevalence in each health state */
1.222     brouard  7686:        for(cpt=1; cpt<=nlstate;cpt++){
1.264     brouard  7687:         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> \
1.241     brouard  7688: <img src=\"%s_%d-%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"PB_"),cpt,k1,nres,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.222     brouard  7689:        }
1.217     brouard  7690:      }
1.222     brouard  7691:      if(prevfcast==1){
1.288     brouard  7692:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  7693:        for(cpt=1; cpt<=nlstate;cpt++){
1.314     brouard  7694:         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);
                   7695:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
                   7696:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
                   7697:                 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  7698:        }
                   7699:      }
1.296     brouard  7700:      if(prevbcast==1){
1.268     brouard  7701:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   7702:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  7703:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
                   7704:  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 \
                   7705:  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  7706: 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);
                   7707:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
                   7708:         fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
1.268     brouard  7709:        }
                   7710:      }
1.220     brouard  7711:         
1.222     brouard  7712:      for(cpt=1; cpt<=nlstate;cpt++) {
1.314     brouard  7713:        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);
                   7714:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
                   7715:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
1.222     brouard  7716:      }
                   7717:      /* } /\* end i1 *\/ */
1.337   ! brouard  7718:    }/* End k1=nres */
1.222     brouard  7719:    fprintf(fichtm,"</ul>");
1.126     brouard  7720: 
1.222     brouard  7721:    fprintf(fichtm,"\
1.126     brouard  7722: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  7723:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  7724:  - 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  7725: But because parameters are usually highly correlated (a higher incidence of disability \
                   7726: and a higher incidence of recovery can give very close observed transition) it might \
                   7727: be very useful to look not only at linear confidence intervals estimated from the \
                   7728: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   7729: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   7730: covariance matrix of the one-step probabilities. \
                   7731: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  7732: 
1.222     brouard  7733:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   7734:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   7735:    fprintf(fichtm,"\
1.126     brouard  7736:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7737:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  7738: 
1.222     brouard  7739:    fprintf(fichtm,"\
1.126     brouard  7740:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7741:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   7742:    fprintf(fichtm,"\
1.126     brouard  7743:  - 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): \
                   7744:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7745:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  7746:    fprintf(fichtm,"\
1.126     brouard  7747:  - (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): \
                   7748:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7749:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  7750:    fprintf(fichtm,"\
1.288     brouard  7751:  - 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  7752:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   7753:    fprintf(fichtm,"\
1.128     brouard  7754:  - 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  7755:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   7756:    fprintf(fichtm,"\
1.288     brouard  7757:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  7758:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  7759: 
                   7760: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   7761: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   7762: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   7763: /*     <br>",fileres,fileres,fileres,fileres); */
                   7764: /*  else  */
                   7765: /*    fprintf(fichtm,"\n No population forecast: popforecast = %d (instead of 1) or stepm = %d (instead of 1) or model=%s (instead of .)<br><br></li>\n",popforecast, stepm, model); */
1.222     brouard  7766:    fflush(fichtm);
1.126     brouard  7767: 
1.225     brouard  7768:    m=pow(2,cptcoveff);
1.222     brouard  7769:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7770: 
1.317     brouard  7771:    fprintf(fichtm," <ul><li><b>Graphs (second order)</b></li><p>");
                   7772: 
                   7773:   jj1=0;
                   7774: 
                   7775:    fprintf(fichtm," \n<ul>");
1.337   ! brouard  7776:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
        !          7777:      /* k1=nres; */
        !          7778:      k1= TKresult[nres];
        !          7779:      /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
        !          7780:      /* if(m != 1 && TKresult[nres]!= k1) */
        !          7781:      /*   continue; */
1.317     brouard  7782:      jj1++;
                   7783:      if (cptcovn > 0) {
                   7784:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescovsecond");
1.337   ! brouard  7785:        for (cpt=1; cpt<=cptcovs;cpt++){ 
        !          7786:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  7787:        }
                   7788:        fprintf(fichtm,"\">");
                   7789:        
                   7790:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   7791:        fprintf(fichtm,"************ Results for covariates");
1.337   ! brouard  7792:        for (cpt=1; cpt<=cptcovs;cpt++){ 
        !          7793:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  7794:        }
                   7795:        if(invalidvarcomb[k1]){
                   7796:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   7797:         continue;
                   7798:        }
                   7799:        fprintf(fichtm,"</a></li>");
                   7800:      } /* cptcovn >0 */
1.337   ! brouard  7801:    } /* End nres */
1.317     brouard  7802:    fprintf(fichtm," \n</ul>");
                   7803: 
1.222     brouard  7804:    jj1=0;
1.237     brouard  7805: 
1.241     brouard  7806:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337   ! brouard  7807:      /* k1=nres; */
        !          7808:      k1= TKresult[nres];
        !          7809:      /* for(k1=1; k1<=m;k1++){ */
        !          7810:      /* if(m != 1 && TKresult[nres]!= k1) */
        !          7811:      /*   continue; */
1.222     brouard  7812:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7813:      jj1++;
1.126     brouard  7814:      if (cptcovn > 0) {
1.317     brouard  7815:        fprintf(fichtm,"\n<p><a name=\"rescovsecond");
1.337   ! brouard  7816:        for (cpt=1; cpt<=cptcovs;cpt++){ 
        !          7817:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  7818:        }
                   7819:        fprintf(fichtm,"\"</a>");
                   7820:        
1.126     brouard  7821:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337   ! brouard  7822:        for (cpt=1; cpt<=cptcovs;cpt++){  /**< cptcoveff number of variables */
        !          7823:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
        !          7824:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  7825:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
1.317     brouard  7826:        }
1.237     brouard  7827: 
1.321     brouard  7828:        fprintf(fichtm," (model=%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.220     brouard  7829: 
1.222     brouard  7830:        if(invalidvarcomb[k1]){
                   7831:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   7832:         continue;
                   7833:        }
1.337   ! brouard  7834:      } /* If cptcovn >0 */
1.126     brouard  7835:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  7836:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.314     brouard  7837: 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);
                   7838:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   7839:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
1.126     brouard  7840:      }
                   7841:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.314     brouard  7842: health expectancies in each live states (1 to %d). If popbased=1 the smooth (due to the model) \
1.128     brouard  7843: true period expectancies (those weighted with period prevalences are also\
                   7844:  drawn in addition to the population based expectancies computed using\
1.314     brouard  7845:  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);
                   7846:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
                   7847:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  7848:      /* } /\* end i1 *\/ */
1.241     brouard  7849:   }/* End nres */
1.222     brouard  7850:    fprintf(fichtm,"</ul>");
                   7851:    fflush(fichtm);
1.126     brouard  7852: }
                   7853: 
                   7854: /******************* Gnuplot file **************/
1.296     brouard  7855: 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  7856: 
                   7857:   char dirfileres[132],optfileres[132];
1.264     brouard  7858:   char gplotcondition[132], gplotlabel[132];
1.237     brouard  7859:   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  7860:   int lv=0, vlv=0, kl=0;
1.130     brouard  7861:   int ng=0;
1.201     brouard  7862:   int vpopbased;
1.223     brouard  7863:   int ioffset; /* variable offset for columns */
1.270     brouard  7864:   int iyearc=1; /* variable column for year of projection  */
                   7865:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  7866:   int nres=0; /* Index of resultline */
1.266     brouard  7867:   int istart=1; /* For starting graphs in projections */
1.219     brouard  7868: 
1.126     brouard  7869: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   7870: /*     printf("Problem with file %s",optionfilegnuplot); */
                   7871: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   7872: /*   } */
                   7873: 
                   7874:   /*#ifdef windows */
                   7875:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  7876:   /*#endif */
1.225     brouard  7877:   m=pow(2,cptcoveff);
1.126     brouard  7878: 
1.274     brouard  7879:   /* diagram of the model */
                   7880:   fprintf(ficgp,"\n#Diagram of the model \n");
                   7881:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   7882:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   7883:   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);
                   7884: 
                   7885:   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);
                   7886:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   7887:   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);
                   7888:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   7889:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   7890:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   7891:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   7892: 
1.202     brouard  7893:   /* Contribution to likelihood */
                   7894:   /* Plot the probability implied in the likelihood */
1.223     brouard  7895:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   7896:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   7897:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   7898:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  7899: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  7900:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   7901: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  7902:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   7903:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   7904:   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));
                   7905:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   7906:   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));
                   7907:   for (i=1; i<= nlstate ; i ++) {
                   7908:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   7909:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   7910:     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);
                   7911:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   7912:       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);
                   7913:     }
                   7914:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   7915:   }
                   7916:   /* 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 */               
                   7917:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   7918:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   7919:   fprintf(ficgp,"\nset out;unset log\n");
                   7920:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  7921: 
1.126     brouard  7922:   strcpy(dirfileres,optionfilefiname);
                   7923:   strcpy(optfileres,"vpl");
1.223     brouard  7924:   /* 1eme*/
1.238     brouard  7925:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
1.337   ! brouard  7926:     /* for (k1=1; k1<= m ; k1 ++){ /\* For each valid combination of covariate *\/ */
1.236     brouard  7927:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337   ! brouard  7928:        k1=TKresult[nres];
1.238     brouard  7929:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.337   ! brouard  7930:        /* if(m != 1 && TKresult[nres]!= k1) */
        !          7931:        /*   continue; */
1.238     brouard  7932:        /* We are interested in selected combination by the resultline */
1.246     brouard  7933:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  7934:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  7935:        strcpy(gplotlabel,"(");
1.337   ! brouard  7936:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
        !          7937:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
        !          7938:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
        !          7939: 
        !          7940:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate k get corresponding value lv for combination k1 *\/ */
        !          7941:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the value of the covariate corresponding to k1 combination *\\/ *\/ */
        !          7942:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
        !          7943:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
        !          7944:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
        !          7945:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
        !          7946:        /*   vlv= nbcode[Tvaraff[k]][lv]; /\* vlv is the value of the covariate lv, 0 or 1 *\/ */
        !          7947:        /*   /\* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv *\/ */
        !          7948:        /*   /\* printf(" V%d=%d ",Tvaraff[k],vlv); *\/ */
        !          7949:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
        !          7950:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
        !          7951:        /* } */
        !          7952:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
        !          7953:        /*   /\* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); *\/ */
        !          7954:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
        !          7955:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.264     brouard  7956:        }
                   7957:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  7958:        /* printf("\n#\n"); */
1.238     brouard  7959:        fprintf(ficgp,"\n#\n");
                   7960:        if(invalidvarcomb[k1]){
1.260     brouard  7961:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  7962:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7963:          continue;
                   7964:        }
1.235     brouard  7965:       
1.241     brouard  7966:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   7967:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  7968:        /* fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel); */
1.321     brouard  7969:        fprintf(ficgp,"set title \"Alive state %d %s model=%s\" font \"Helvetica,12\"\n",cpt,gplotlabel,model);
1.260     brouard  7970:        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);
                   7971:        /* 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); */
                   7972:       /* k1-1 error should be nres-1*/
1.238     brouard  7973:        for (i=1; i<= nlstate ; i ++) {
                   7974:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7975:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   7976:        }
1.288     brouard  7977:        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  7978:        for (i=1; i<= nlstate ; i ++) {
                   7979:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7980:          else fprintf(ficgp," %%*lf (%%*lf)");
                   7981:        } 
1.260     brouard  7982:        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  7983:        for (i=1; i<= nlstate ; i ++) {
                   7984:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7985:          else fprintf(ficgp," %%*lf (%%*lf)");
                   7986:        }  
1.265     brouard  7987:        /* 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)); */
                   7988:        
                   7989:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   7990:         if(cptcoveff ==0){
1.271     brouard  7991:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  7992:        }else{
                   7993:          kl=0;
                   7994:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  7995:            /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   7996:            lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.265     brouard  7997:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7998:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7999:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8000:            vlv= nbcode[Tvaraff[k]][lv];
                   8001:            kl++;
                   8002:            /* 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 *\/ */
                   8003:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8004:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8005:            /* ''  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*/
                   8006:            if(k==cptcoveff){
                   8007:              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], \
                   8008:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   8009:            }else{
                   8010:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   8011:              kl++;
                   8012:            }
                   8013:          } /* end covariate */
                   8014:        } /* end if no covariate */
                   8015: 
1.296     brouard  8016:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  8017:          /* 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  8018:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  8019:          if(cptcoveff ==0){
1.245     brouard  8020:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  8021:          }else{
                   8022:            kl=0;
                   8023:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  8024:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8025:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.238     brouard  8026:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8027:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8028:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8029:              /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8030:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.223     brouard  8031:              kl++;
1.238     brouard  8032:              /* 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 *\/ */
                   8033:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8034:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8035:              /* ''  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*/
                   8036:              if(k==cptcoveff){
1.245     brouard  8037:                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  8038:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  8039:              }else{
1.332     brouard  8040:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]);
1.238     brouard  8041:                kl++;
                   8042:              }
                   8043:            } /* end covariate */
                   8044:          } /* end if no covariate */
1.296     brouard  8045:          if(prevbcast == 1){
1.268     brouard  8046:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   8047:            /* k1-1 error should be nres-1*/
                   8048:            for (i=1; i<= nlstate ; i ++) {
                   8049:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8050:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   8051:            }
1.271     brouard  8052:            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  8053:            for (i=1; i<= nlstate ; i ++) {
                   8054:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8055:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8056:            } 
1.276     brouard  8057:            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  8058:            for (i=1; i<= nlstate ; i ++) {
                   8059:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8060:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8061:            } 
1.274     brouard  8062:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  8063:          } /* end if backprojcast */
1.296     brouard  8064:        } /* end if prevbcast */
1.276     brouard  8065:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   8066:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  8067:       } /* nres */
1.337   ! brouard  8068:     /* } /\* k1 *\/ */
1.201     brouard  8069:   } /* cpt */
1.235     brouard  8070: 
                   8071:   
1.126     brouard  8072:   /*2 eme*/
1.337   ! brouard  8073:   /* for (k1=1; k1<= m ; k1 ++){   */
1.238     brouard  8074:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337   ! brouard  8075:       k1=TKresult[nres];
        !          8076:       /* if(m != 1 && TKresult[nres]!= k1) */
        !          8077:       /*       continue; */
1.238     brouard  8078:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  8079:       strcpy(gplotlabel,"(");
1.337   ! brouard  8080:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
        !          8081:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
        !          8082:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
        !          8083:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
        !          8084:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
        !          8085:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
        !          8086:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
        !          8087:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
        !          8088:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
        !          8089:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
        !          8090:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
        !          8091:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
        !          8092:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
        !          8093:       /* } */
        !          8094:       /* /\* for(k=1; k <= ncovds; k++){ *\/ */
        !          8095:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
        !          8096:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
        !          8097:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
        !          8098:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  8099:       }
1.264     brouard  8100:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8101:       fprintf(ficgp,"\n#\n");
1.223     brouard  8102:       if(invalidvarcomb[k1]){
                   8103:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8104:        continue;
                   8105:       }
1.219     brouard  8106:                        
1.241     brouard  8107:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  8108:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  8109:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   8110:        if(vpopbased==0){
1.238     brouard  8111:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  8112:        }else
1.238     brouard  8113:          fprintf(ficgp,"\nreplot ");
                   8114:        for (i=1; i<= nlstate+1 ; i ++) {
                   8115:          k=2*i;
1.261     brouard  8116:          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  8117:          for (j=1; j<= nlstate+1 ; j ++) {
                   8118:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8119:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8120:          }   
                   8121:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   8122:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
1.261     brouard  8123:          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  8124:          for (j=1; j<= nlstate+1 ; j ++) {
                   8125:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8126:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8127:          }   
                   8128:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  8129:          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  8130:          for (j=1; j<= nlstate+1 ; j ++) {
                   8131:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8132:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8133:          }   
                   8134:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   8135:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   8136:        } /* state */
                   8137:       } /* vpopbased */
1.264     brouard  8138:       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  8139:     } /* end nres */
1.337   ! brouard  8140:   /* } /\* k1 end 2 eme*\/ */
1.238     brouard  8141:        
                   8142:        
                   8143:   /*3eme*/
1.337   ! brouard  8144:   /* for (k1=1; k1<= m ; k1 ++){ */
1.238     brouard  8145:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337   ! brouard  8146:       k1=TKresult[nres];
        !          8147:       /* if(m != 1 && TKresult[nres]!= k1) */
        !          8148:       /*       continue; */
1.238     brouard  8149: 
1.332     brouard  8150:       for (cpt=1; cpt<= nlstate ; cpt ++) { /* Fragile no verification of covariate values */
1.261     brouard  8151:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  8152:        strcpy(gplotlabel,"(");
1.337   ! brouard  8153:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
        !          8154:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
        !          8155:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
        !          8156:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
        !          8157:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
        !          8158:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
        !          8159:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
        !          8160:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
        !          8161:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
        !          8162:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
        !          8163:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
        !          8164:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
        !          8165:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
        !          8166:        /* } */
        !          8167:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
        !          8168:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
        !          8169:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
        !          8170:        }
1.264     brouard  8171:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8172:        fprintf(ficgp,"\n#\n");
                   8173:        if(invalidvarcomb[k1]){
                   8174:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8175:          continue;
                   8176:        }
                   8177:                        
                   8178:        /*       k=2+nlstate*(2*cpt-2); */
                   8179:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  8180:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  8181:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  8182:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  8183: 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  8184:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8185:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8186:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   8187:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8188:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8189:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  8190:                                
1.238     brouard  8191:        */
                   8192:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  8193:          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  8194:          /*    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  8195:                                
1.238     brouard  8196:        } 
1.261     brouard  8197:        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  8198:       }
1.264     brouard  8199:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  8200:     } /* end nres */
1.337   ! brouard  8201:   /* } /\* end kl 3eme *\/ */
1.126     brouard  8202:   
1.223     brouard  8203:   /* 4eme */
1.201     brouard  8204:   /* Survival functions (period) from state i in state j by initial state i */
1.337   ! brouard  8205:   /* for (k1=1; k1<=m; k1++){    /\* For each covariate and each value *\/ */
1.238     brouard  8206:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337   ! brouard  8207:       k1=TKresult[nres];
        !          8208:       /* if(m != 1 && TKresult[nres]!= k1) */
        !          8209:       /*       continue; */
1.238     brouard  8210:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  8211:        strcpy(gplotlabel,"(");
1.337   ! brouard  8212:        fprintf(ficgp,"\n#\n#\n# Survival functions in state %d : 'LIJ_' files, cov=%d state=%d", cpt, k1, cpt);
        !          8213:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
        !          8214:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
        !          8215:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
        !          8216:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
        !          8217:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
        !          8218:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
        !          8219:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
        !          8220:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
        !          8221:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
        !          8222:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
        !          8223:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
        !          8224:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
        !          8225:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
        !          8226:        /* } */
        !          8227:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
        !          8228:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
        !          8229:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  8230:        }       
1.264     brouard  8231:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8232:        fprintf(ficgp,"\n#\n");
                   8233:        if(invalidvarcomb[k1]){
                   8234:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8235:          continue;
1.223     brouard  8236:        }
1.238     brouard  8237:       
1.241     brouard  8238:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  8239:        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  8240:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8241: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8242:        k=3;
                   8243:        for (i=1; i<= nlstate ; i ++){
                   8244:          if(i==1){
                   8245:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8246:          }else{
                   8247:            fprintf(ficgp,", '' ");
                   8248:          }
                   8249:          l=(nlstate+ndeath)*(i-1)+1;
                   8250:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8251:          for (j=2; j<= nlstate+ndeath ; j ++)
                   8252:            fprintf(ficgp,"+$%d",k+l+j-1);
                   8253:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   8254:        } /* nlstate */
1.264     brouard  8255:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8256:       } /* end cpt state*/ 
                   8257:     } /* end nres */
1.337   ! brouard  8258:   /* } /\* end covariate k1 *\/   */
1.238     brouard  8259: 
1.220     brouard  8260: /* 5eme */
1.201     brouard  8261:   /* Survival functions (period) from state i in state j by final state j */
1.337   ! brouard  8262:   /* for (k1=1; k1<= m ; k1++){ /\* For each covariate combination if any *\/ */
1.238     brouard  8263:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337   ! brouard  8264:       k1=TKresult[nres];
        !          8265:       /* if(m != 1 && TKresult[nres]!= k1) */
        !          8266:       /*       continue; */
1.238     brouard  8267:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  8268:        strcpy(gplotlabel,"(");
1.238     brouard  8269:        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  8270:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
        !          8271:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
        !          8272:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
        !          8273:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
        !          8274:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
        !          8275:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
        !          8276:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
        !          8277:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
        !          8278:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
        !          8279:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
        !          8280:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
        !          8281:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
        !          8282:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
        !          8283:        /* } */
        !          8284:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
        !          8285:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
        !          8286:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  8287:        }       
1.264     brouard  8288:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8289:        fprintf(ficgp,"\n#\n");
                   8290:        if(invalidvarcomb[k1]){
                   8291:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8292:          continue;
                   8293:        }
1.227     brouard  8294:       
1.241     brouard  8295:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  8296:        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  8297:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8298: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8299:        k=3;
                   8300:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8301:          if(j==1)
                   8302:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8303:          else
                   8304:            fprintf(ficgp,", '' ");
                   8305:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8306:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   8307:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   8308:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   8309:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   8310:        } /* nlstate */
                   8311:        fprintf(ficgp,", '' ");
                   8312:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   8313:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8314:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8315:          if(j < nlstate)
                   8316:            fprintf(ficgp,"$%d +",k+l);
                   8317:          else
                   8318:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   8319:        }
1.264     brouard  8320:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8321:       } /* end cpt state*/ 
1.337   ! brouard  8322:     /* } /\* end covariate *\/   */
1.238     brouard  8323:   } /* end nres */
1.227     brouard  8324:   
1.220     brouard  8325: /* 6eme */
1.202     brouard  8326:   /* CV preval stable (period) for each covariate */
1.337   ! brouard  8327:   /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8328:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337   ! brouard  8329:      k1=TKresult[nres];
        !          8330:      /* if(m != 1 && TKresult[nres]!= k1) */
        !          8331:      /*  continue; */
1.255     brouard  8332:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  8333:       strcpy(gplotlabel,"(");      
1.288     brouard  8334:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.337   ! brouard  8335:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
        !          8336:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
        !          8337:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
        !          8338:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
        !          8339:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
        !          8340:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
        !          8341:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
        !          8342:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
        !          8343:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
        !          8344:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
        !          8345:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
        !          8346:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
        !          8347:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
        !          8348:       /* } */
        !          8349:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
        !          8350:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
        !          8351:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8352:       }        
1.264     brouard  8353:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8354:       fprintf(ficgp,"\n#\n");
1.223     brouard  8355:       if(invalidvarcomb[k1]){
1.227     brouard  8356:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8357:        continue;
1.223     brouard  8358:       }
1.227     brouard  8359:       
1.241     brouard  8360:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  8361:       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  8362:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8363: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  8364:       k=3; /* Offset */
1.255     brouard  8365:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  8366:        if(i==1)
                   8367:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8368:        else
                   8369:          fprintf(ficgp,", '' ");
1.255     brouard  8370:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  8371:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8372:        for (j=2; j<= nlstate ; j ++)
                   8373:          fprintf(ficgp,"+$%d",k+l+j-1);
                   8374:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  8375:       } /* nlstate */
1.264     brouard  8376:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  8377:     } /* end cpt state*/ 
                   8378:   } /* end covariate */  
1.227     brouard  8379:   
                   8380:   
1.220     brouard  8381: /* 7eme */
1.296     brouard  8382:   if(prevbcast == 1){
1.288     brouard  8383:     /* CV backward prevalence  for each covariate */
1.337   ! brouard  8384:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8385:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337   ! brouard  8386:       k1=TKresult[nres];
        !          8387:       /* if(m != 1 && TKresult[nres]!= k1) */
        !          8388:       /*       continue; */
1.268     brouard  8389:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  8390:        strcpy(gplotlabel,"(");      
1.288     brouard  8391:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.337   ! brouard  8392:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
        !          8393:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
        !          8394:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
        !          8395:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
        !          8396:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
        !          8397:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
        !          8398:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
        !          8399:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
        !          8400:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
        !          8401:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
        !          8402:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
        !          8403:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
        !          8404:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
        !          8405:        /* } */
        !          8406:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
        !          8407:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
        !          8408:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8409:        }       
1.264     brouard  8410:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8411:        fprintf(ficgp,"\n#\n");
                   8412:        if(invalidvarcomb[k1]){
                   8413:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8414:          continue;
                   8415:        }
                   8416:        
1.241     brouard  8417:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  8418:        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  8419:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8420: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  8421:        k=3; /* Offset */
1.268     brouard  8422:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  8423:          if(i==1)
                   8424:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   8425:          else
                   8426:            fprintf(ficgp,", '' ");
                   8427:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  8428:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.324     brouard  8429:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   8430:          /* 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  8431:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  8432:          /* for (j=2; j<= nlstate ; j ++) */
                   8433:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   8434:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  8435:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  8436:        } /* nlstate */
1.264     brouard  8437:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  8438:       } /* end cpt state*/ 
                   8439:     } /* end covariate */  
1.296     brouard  8440:   } /* End if prevbcast */
1.218     brouard  8441:   
1.223     brouard  8442:   /* 8eme */
1.218     brouard  8443:   if(prevfcast==1){
1.288     brouard  8444:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  8445:     
1.337   ! brouard  8446:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8447:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337   ! brouard  8448:       k1=TKresult[nres];
        !          8449:       /* if(m != 1 && TKresult[nres]!= k1) */
        !          8450:       /*       continue; */
1.211     brouard  8451:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  8452:        strcpy(gplotlabel,"(");      
1.288     brouard  8453:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.337   ! brouard  8454:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
        !          8455:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
        !          8456:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
        !          8457:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
        !          8458:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
        !          8459:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
        !          8460:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
        !          8461:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
        !          8462:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
        !          8463:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
        !          8464:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
        !          8465:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
        !          8466:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
        !          8467:        /* } */
        !          8468:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
        !          8469:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
        !          8470:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8471:        }       
1.264     brouard  8472:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8473:        fprintf(ficgp,"\n#\n");
                   8474:        if(invalidvarcomb[k1]){
                   8475:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8476:          continue;
                   8477:        }
                   8478:        
                   8479:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  8480:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  8481:        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  8482:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  8483: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  8484: 
                   8485:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   8486:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8487:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8488:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  8489:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8490:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8491:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8492:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  8493:          if(i==istart){
1.227     brouard  8494:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   8495:          }else{
                   8496:            fprintf(ficgp,",\\\n '' ");
                   8497:          }
                   8498:          if(cptcoveff ==0){ /* No covariate */
                   8499:            ioffset=2; /* Age is in 2 */
                   8500:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8501:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8502:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8503:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8504:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  8505:            if(i==nlstate+1){
1.270     brouard  8506:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  8507:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   8508:              fprintf(ficgp,",\\\n '' ");
                   8509:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  8510:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  8511:                     offyear,                           \
1.268     brouard  8512:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  8513:            }else
1.227     brouard  8514:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   8515:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8516:          }else{ /* more than 2 covariates */
1.270     brouard  8517:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   8518:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8519:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   8520:            iyearc=ioffset-1;
                   8521:            iagec=ioffset;
1.227     brouard  8522:            fprintf(ficgp," u %d:(",ioffset); 
                   8523:            kl=0;
                   8524:            strcpy(gplotcondition,"(");
                   8525:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
1.332     brouard  8526:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8527:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.227     brouard  8528:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8529:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8530:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8531:              /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   8532:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.227     brouard  8533:              kl++;
                   8534:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   8535:              kl++;
                   8536:              if(k <cptcoveff && cptcoveff>1)
                   8537:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   8538:            }
                   8539:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   8540:            /* 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 *\/ */
                   8541:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8542:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8543:            /* ''  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*/
                   8544:            if(i==nlstate+1){
1.270     brouard  8545:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   8546:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  8547:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  8548:              fprintf(ficgp," u %d:(",iagec); 
                   8549:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   8550:                      iyearc, iagec, offyear,                           \
                   8551:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  8552: /*  '' 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  8553:            }else{
                   8554:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   8555:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8556:            }
                   8557:          } /* end if covariate */
                   8558:        } /* nlstate */
1.264     brouard  8559:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  8560:       } /* end cpt state*/
                   8561:     } /* end covariate */
                   8562:   } /* End if prevfcast */
1.227     brouard  8563:   
1.296     brouard  8564:   if(prevbcast==1){
1.268     brouard  8565:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   8566:     
1.337   ! brouard  8567:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.268     brouard  8568:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337   ! brouard  8569:      k1=TKresult[nres];
        !          8570:        /* if(m != 1 && TKresult[nres]!= k1) */
        !          8571:        /*      continue; */
1.268     brouard  8572:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   8573:        strcpy(gplotlabel,"(");      
                   8574:        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  8575:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
        !          8576:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
        !          8577:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
        !          8578:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
        !          8579:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
        !          8580:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
        !          8581:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
        !          8582:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
        !          8583:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
        !          8584:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
        !          8585:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
        !          8586:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
        !          8587:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
        !          8588:        /* } */
        !          8589:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
        !          8590:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
        !          8591:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.268     brouard  8592:        }       
                   8593:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   8594:        fprintf(ficgp,"\n#\n");
                   8595:        if(invalidvarcomb[k1]){
                   8596:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8597:          continue;
                   8598:        }
                   8599:        
                   8600:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   8601:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   8602:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   8603:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   8604: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8605: 
                   8606:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   8607:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8608:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8609:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   8610:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8611:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8612:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8613:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8614:          if(i==istart){
                   8615:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   8616:          }else{
                   8617:            fprintf(ficgp,",\\\n '' ");
                   8618:          }
                   8619:          if(cptcoveff ==0){ /* No covariate */
                   8620:            ioffset=2; /* Age is in 2 */
                   8621:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8622:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8623:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8624:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8625:            fprintf(ficgp," u %d:(", ioffset); 
                   8626:            if(i==nlstate+1){
1.270     brouard  8627:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  8628:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   8629:              fprintf(ficgp,",\\\n '' ");
                   8630:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  8631:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  8632:                     offbyear,                          \
                   8633:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   8634:            }else
                   8635:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   8636:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   8637:          }else{ /* more than 2 covariates */
1.270     brouard  8638:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   8639:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8640:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   8641:            iyearc=ioffset-1;
                   8642:            iagec=ioffset;
1.268     brouard  8643:            fprintf(ficgp," u %d:(",ioffset); 
                   8644:            kl=0;
                   8645:            strcpy(gplotcondition,"(");
1.337   ! brouard  8646:            for (k=1; k<=cptcovs; k++){    /* For each covariate k of the resultline, get corresponding value lv for combination k1 */
        !          8647:              if(Dummy[Tvresult[nres][k]]==0){  /* To be verified */
        !          8648:                /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
        !          8649:                /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
        !          8650:                /* lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
        !          8651:                lv=Tvresult[nres][k];
        !          8652:                vlv=TinvDoQresult[nres][Tvresult[nres][k]];
        !          8653:                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
        !          8654:                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
        !          8655:                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
        !          8656:                /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
        !          8657:                /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
        !          8658:                kl++;
        !          8659:                /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
        !          8660:                sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%lg " ,kl,Tvresult[nres][k], kl+1,TinvDoQresult[nres][Tvresult[nres][k]]);
        !          8661:                kl++;
        !          8662:                if(k <cptcoveff && cptcoveff>1)
        !          8663:                  sprintf(gplotcondition+strlen(gplotcondition)," && ");
        !          8664:              }
1.268     brouard  8665:            }
                   8666:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   8667:            /* 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 *\/ */
                   8668:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8669:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8670:            /* ''  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*/
                   8671:            if(i==nlstate+1){
1.270     brouard  8672:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   8673:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  8674:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  8675:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  8676:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  8677:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   8678:                      iyearc,iagec,offbyear,                            \
                   8679:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  8680: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   8681:            }else{
                   8682:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   8683:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   8684:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   8685:            }
                   8686:          } /* end if covariate */
                   8687:        } /* nlstate */
                   8688:        fprintf(ficgp,"\nset out; unset label;\n");
                   8689:       } /* end cpt state*/
                   8690:     } /* end covariate */
1.296     brouard  8691:   } /* End if prevbcast */
1.268     brouard  8692:   
1.227     brouard  8693:   
1.238     brouard  8694:   /* 9eme writing MLE parameters */
                   8695:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  8696:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  8697:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  8698:     for(k=1; k <=(nlstate+ndeath); k++){
                   8699:       if (k != i) {
1.227     brouard  8700:        fprintf(ficgp,"#   current state %d\n",k);
                   8701:        for(j=1; j <=ncovmodel; j++){
                   8702:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   8703:          jk++; 
                   8704:        }
                   8705:        fprintf(ficgp,"\n");
1.126     brouard  8706:       }
                   8707:     }
1.223     brouard  8708:   }
1.187     brouard  8709:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  8710:   
1.145     brouard  8711:   /*goto avoid;*/
1.238     brouard  8712:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   8713:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  8714:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   8715:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   8716:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   8717:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   8718:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8719:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   8720:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8721:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   8722:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   8723:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8724:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   8725:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   8726:   fprintf(ficgp,"#\n");
1.223     brouard  8727:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  8728:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.237     brouard  8729:     fprintf(ficgp,"#model=%s \n",model);
1.238     brouard  8730:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.264     brouard  8731:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
1.337   ! brouard  8732:     /* for(k1=1; k1 <=m; k1++)  /\* For each combination of covariate *\/ */
1.237     brouard  8733:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337   ! brouard  8734:      /* k1=nres; */
        !          8735:       k1= TKresult[nres];
        !          8736:       fprintf(ficgp,"\n\n# Resultline k1=%d ",k1);
1.264     brouard  8737:       strcpy(gplotlabel,"(");
1.276     brouard  8738:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.337   ! brouard  8739:       for (k=1; k<=cptcovs; k++){  /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
        !          8740:        /* for each resultline nres, and position k, Tvresult[nres][k] gives the name of the variable and
        !          8741:           TinvDoQresult[nres][Tvresult[nres][k]] gives its value double or integer) */
        !          8742:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
        !          8743:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
        !          8744:       }
        !          8745:       /* if(m != 1 && TKresult[nres]!= k1) */
        !          8746:       /*       continue; */
        !          8747:       /* fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1); */
        !          8748:       /* strcpy(gplotlabel,"("); */
        !          8749:       /* /\*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*\/ */
        !          8750:       /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
        !          8751:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
        !          8752:       /*       lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
        !          8753:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
        !          8754:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
        !          8755:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
        !          8756:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
        !          8757:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
        !          8758:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
        !          8759:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
        !          8760:       /* } */
        !          8761:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
        !          8762:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
        !          8763:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
        !          8764:       /* }      */
1.264     brouard  8765:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  8766:       fprintf(ficgp,"\n#\n");
1.264     brouard  8767:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  8768:       fprintf(ficgp,"\nset key outside ");
                   8769:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   8770:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  8771:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   8772:       if (ng==1){
                   8773:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   8774:        fprintf(ficgp,"\nunset log y");
                   8775:       }else if (ng==2){
                   8776:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   8777:        fprintf(ficgp,"\nset log y");
                   8778:       }else if (ng==3){
                   8779:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   8780:        fprintf(ficgp,"\nset log y");
                   8781:       }else
                   8782:        fprintf(ficgp,"\nunset title ");
                   8783:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   8784:       i=1;
                   8785:       for(k2=1; k2<=nlstate; k2++) {
                   8786:        k3=i;
                   8787:        for(k=1; k<=(nlstate+ndeath); k++) {
                   8788:          if (k != k2){
                   8789:            switch( ng) {
                   8790:            case 1:
                   8791:              if(nagesqr==0)
                   8792:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   8793:              else /* nagesqr =1 */
                   8794:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   8795:              break;
                   8796:            case 2: /* ng=2 */
                   8797:              if(nagesqr==0)
                   8798:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   8799:              else /* nagesqr =1 */
                   8800:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   8801:              break;
                   8802:            case 3:
                   8803:              if(nagesqr==0)
                   8804:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   8805:              else /* nagesqr =1 */
                   8806:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   8807:              break;
                   8808:            }
                   8809:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  8810:            ijp=1; /* product no age */
                   8811:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   8812:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  8813:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.329     brouard  8814:              switch(Typevar[j]){
                   8815:              case 1:
                   8816:                if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   8817:                  if(j==Tage[ij]) { /* Product by age  To be looked at!!*//* Bug valgrind */
                   8818:                    if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   8819:                      if(DummyV[j]==0){/* Bug valgrind */
                   8820:                        fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   8821:                      }else{ /* quantitative */
                   8822:                        fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   8823:                        /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8824:                      }
                   8825:                      ij++;
1.268     brouard  8826:                    }
1.237     brouard  8827:                  }
1.329     brouard  8828:                }
                   8829:                break;
                   8830:              case 2:
                   8831:                if(cptcovprod >0){
                   8832:                  if(j==Tprod[ijp]) { /* */ 
                   8833:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   8834:                    if(ijp <=cptcovprod) { /* Product */
                   8835:                      if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   8836:                        if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   8837:                          /* 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)]); */
                   8838:                          fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   8839:                        }else{ /* Vn is dummy and Vm is quanti */
                   8840:                          /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8841:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8842:                        }
                   8843:                      }else{ /* Vn*Vm Vn is quanti */
                   8844:                        if(DummyV[Tvard[ijp][2]]==0){
                   8845:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   8846:                        }else{ /* Both quanti */
                   8847:                          fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8848:                        }
1.268     brouard  8849:                      }
1.329     brouard  8850:                      ijp++;
1.237     brouard  8851:                    }
1.329     brouard  8852:                  } /* end Tprod */
                   8853:                }
                   8854:                break;
                   8855:              case 0:
                   8856:                /* simple covariate */
1.264     brouard  8857:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  8858:                if(Dummy[j]==0){
                   8859:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   8860:                }else{ /* quantitative */
                   8861:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  8862:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  8863:                }
1.329     brouard  8864:               /* end simple */
                   8865:                break;
                   8866:              default:
                   8867:                break;
                   8868:              } /* end switch */
1.237     brouard  8869:            } /* end j */
1.329     brouard  8870:          }else{ /* k=k2 */
                   8871:            if(ng !=1 ){ /* For logit formula of log p11 is more difficult to get */
                   8872:              fprintf(ficgp," (1.");i=i-ncovmodel;
                   8873:            }else
                   8874:              i=i-ncovmodel;
1.223     brouard  8875:          }
1.227     brouard  8876:          
1.223     brouard  8877:          if(ng != 1){
                   8878:            fprintf(ficgp,")/(1");
1.227     brouard  8879:            
1.264     brouard  8880:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  8881:              if(nagesqr==0)
1.264     brouard  8882:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  8883:              else /* nagesqr =1 */
1.264     brouard  8884:                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  8885:               
1.223     brouard  8886:              ij=1;
1.329     brouard  8887:              ijp=1;
                   8888:              /* for(j=3; j <=ncovmodel-nagesqr; j++){ */
                   8889:              for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
                   8890:                switch(Typevar[j]){
                   8891:                case 1:
                   8892:                  if(cptcovage >0){ 
                   8893:                    if(j==Tage[ij]) { /* Bug valgrind */
                   8894:                      if(ij <=cptcovage) { /* Bug valgrind */
                   8895:                        if(DummyV[j]==0){/* Bug valgrind */
                   8896:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]); */
                   8897:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,nbcode[Tvar[j]][codtabm(k1,j)]); */
                   8898:                          fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]);
                   8899:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);; */
                   8900:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8901:                        }else{ /* quantitative */
                   8902:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   8903:                          fprintf(ficgp,"+p%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   8904:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   8905:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8906:                        }
                   8907:                        ij++;
                   8908:                      }
                   8909:                    }
                   8910:                  }
                   8911:                  break;
                   8912:                case 2:
                   8913:                  if(cptcovprod >0){
                   8914:                    if(j==Tprod[ijp]) { /* */ 
                   8915:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   8916:                      if(ijp <=cptcovprod) { /* Product */
                   8917:                        if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   8918:                          if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   8919:                            /* 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)]); */
                   8920:                            fprintf(ficgp,"+p%d*%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   8921:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   8922:                          }else{ /* Vn is dummy and Vm is quanti */
                   8923:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8924:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8925:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8926:                          }
                   8927:                        }else{ /* Vn*Vm Vn is quanti */
                   8928:                          if(DummyV[Tvard[ijp][2]]==0){
                   8929:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   8930:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   8931:                          }else{ /* Both quanti */
                   8932:                            fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8933:                            /* fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8934:                          } 
                   8935:                        }
                   8936:                        ijp++;
                   8937:                      }
                   8938:                    } /* end Tprod */
                   8939:                  } /* end if */
                   8940:                  break;
                   8941:                case 0: 
                   8942:                  /* simple covariate */
                   8943:                  /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
                   8944:                  if(Dummy[j]==0){
                   8945:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   8946:                    fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]); /*  */
                   8947:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   8948:                  }else{ /* quantitative */
                   8949:                    fprintf(ficgp,"+p%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* */
                   8950:                    /* fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* *\/ */
                   8951:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8952:                  }
                   8953:                  /* end simple */
                   8954:                  /* fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);/\* Valgrind bug nbcode *\/ */
                   8955:                  break;
                   8956:                default:
                   8957:                  break;
                   8958:                } /* end switch */
1.223     brouard  8959:              }
                   8960:              fprintf(ficgp,")");
                   8961:            }
                   8962:            fprintf(ficgp,")");
                   8963:            if(ng ==2)
1.276     brouard  8964:              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  8965:            else /* ng= 3 */
1.276     brouard  8966:              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  8967:           }else{ /* end ng <> 1 */
1.223     brouard  8968:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  8969:              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  8970:          }
                   8971:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   8972:            fprintf(ficgp,",");
                   8973:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   8974:            fprintf(ficgp,",");
                   8975:          i=i+ncovmodel;
                   8976:        } /* end k */
                   8977:       } /* end k2 */
1.276     brouard  8978:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   8979:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.337   ! brouard  8980:     } /* end resultline */
1.223     brouard  8981:   } /* end ng */
                   8982:   /* avoid: */
                   8983:   fflush(ficgp); 
1.126     brouard  8984: }  /* end gnuplot */
                   8985: 
                   8986: 
                   8987: /*************** Moving average **************/
1.219     brouard  8988: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  8989:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  8990:    
1.222     brouard  8991:    int i, cpt, cptcod;
                   8992:    int modcovmax =1;
                   8993:    int mobilavrange, mob;
                   8994:    int iage=0;
1.288     brouard  8995:    int firstA1=0, firstA2=0;
1.222     brouard  8996: 
1.266     brouard  8997:    double sum=0., sumr=0.;
1.222     brouard  8998:    double age;
1.266     brouard  8999:    double *sumnewp, *sumnewm, *sumnewmr;
                   9000:    double *agemingood, *agemaxgood; 
                   9001:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  9002:   
                   9003:   
1.278     brouard  9004:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   9005:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  9006: 
                   9007:    sumnewp = vector(1,ncovcombmax);
                   9008:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  9009:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  9010:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  9011:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  9012:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  9013:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  9014: 
                   9015:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  9016:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  9017:      sumnewp[cptcod]=0.;
1.266     brouard  9018:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   9019:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  9020:    }
                   9021:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   9022:   
1.266     brouard  9023:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   9024:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  9025:      else mobilavrange=mobilav;
                   9026:      for (age=bage; age<=fage; age++)
                   9027:        for (i=1; i<=nlstate;i++)
                   9028:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   9029:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9030:      /* We keep the original values on the extreme ages bage, fage and for 
                   9031:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   9032:        we use a 5 terms etc. until the borders are no more concerned. 
                   9033:      */ 
                   9034:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   9035:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  9036:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   9037:           sumnewm[cptcod]=0.;
                   9038:           for (i=1; i<=nlstate;i++){
1.222     brouard  9039:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   9040:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   9041:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   9042:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   9043:             }
                   9044:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  9045:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9046:           } /* end i */
                   9047:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   9048:         } /* end cptcod */
1.222     brouard  9049:        }/* end age */
                   9050:      }/* end mob */
1.266     brouard  9051:    }else{
                   9052:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  9053:      return -1;
1.266     brouard  9054:    }
                   9055: 
                   9056:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  9057:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   9058:      if(invalidvarcomb[cptcod]){
                   9059:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   9060:        continue;
                   9061:      }
1.219     brouard  9062: 
1.266     brouard  9063:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   9064:        sumnewm[cptcod]=0.;
                   9065:        sumnewmr[cptcod]=0.;
                   9066:        for (i=1; i<=nlstate;i++){
                   9067:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9068:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9069:        }
                   9070:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9071:         agemingoodr[cptcod]=age;
                   9072:        }
                   9073:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9074:           agemingood[cptcod]=age;
                   9075:        }
                   9076:      } /* age */
                   9077:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  9078:        sumnewm[cptcod]=0.;
1.266     brouard  9079:        sumnewmr[cptcod]=0.;
1.222     brouard  9080:        for (i=1; i<=nlstate;i++){
                   9081:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9082:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9083:        }
                   9084:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9085:         agemaxgoodr[cptcod]=age;
1.222     brouard  9086:        }
                   9087:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  9088:         agemaxgood[cptcod]=age;
                   9089:        }
                   9090:      } /* age */
                   9091:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   9092:      /* but they will change */
1.288     brouard  9093:      firstA1=0;firstA2=0;
1.266     brouard  9094:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   9095:        sumnewm[cptcod]=0.;
                   9096:        sumnewmr[cptcod]=0.;
                   9097:        for (i=1; i<=nlstate;i++){
                   9098:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9099:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9100:        }
                   9101:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9102:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9103:           agemaxgoodr[cptcod]=age;  /* age min */
                   9104:           for (i=1; i<=nlstate;i++)
                   9105:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9106:         }else{ /* bad we change the value with the values of good ages */
                   9107:           for (i=1; i<=nlstate;i++){
                   9108:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   9109:           } /* i */
                   9110:         } /* end bad */
                   9111:        }else{
                   9112:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9113:           agemaxgood[cptcod]=age;
                   9114:         }else{ /* bad we change the value with the values of good ages */
                   9115:           for (i=1; i<=nlstate;i++){
                   9116:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   9117:           } /* i */
                   9118:         } /* end bad */
                   9119:        }/* end else */
                   9120:        sum=0.;sumr=0.;
                   9121:        for (i=1; i<=nlstate;i++){
                   9122:         sum+=mobaverage[(int)age][i][cptcod];
                   9123:         sumr+=probs[(int)age][i][cptcod];
                   9124:        }
                   9125:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  9126:         if(!firstA1){
                   9127:           firstA1=1;
                   9128:           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);
                   9129:         }
                   9130:         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  9131:        } /* end bad */
                   9132:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9133:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  9134:         if(!firstA2){
                   9135:           firstA2=1;
                   9136:           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);
                   9137:         }
                   9138:         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  9139:        } /* end bad */
                   9140:      }/* age */
1.266     brouard  9141: 
                   9142:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  9143:        sumnewm[cptcod]=0.;
1.266     brouard  9144:        sumnewmr[cptcod]=0.;
1.222     brouard  9145:        for (i=1; i<=nlstate;i++){
                   9146:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9147:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9148:        } 
                   9149:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9150:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   9151:           agemingoodr[cptcod]=age;
                   9152:           for (i=1; i<=nlstate;i++)
                   9153:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9154:         }else{ /* bad we change the value with the values of good ages */
                   9155:           for (i=1; i<=nlstate;i++){
                   9156:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   9157:           } /* i */
                   9158:         } /* end bad */
                   9159:        }else{
                   9160:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9161:           agemingood[cptcod]=age;
                   9162:         }else{ /* bad */
                   9163:           for (i=1; i<=nlstate;i++){
                   9164:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   9165:           } /* i */
                   9166:         } /* end bad */
                   9167:        }/* end else */
                   9168:        sum=0.;sumr=0.;
                   9169:        for (i=1; i<=nlstate;i++){
                   9170:         sum+=mobaverage[(int)age][i][cptcod];
                   9171:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  9172:        }
1.266     brouard  9173:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  9174:         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  9175:        } /* end bad */
                   9176:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9177:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  9178:         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  9179:        } /* end bad */
                   9180:      }/* age */
1.266     brouard  9181: 
1.222     brouard  9182:                
                   9183:      for (age=bage; age<=fage; age++){
1.235     brouard  9184:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  9185:        sumnewp[cptcod]=0.;
                   9186:        sumnewm[cptcod]=0.;
                   9187:        for (i=1; i<=nlstate;i++){
                   9188:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   9189:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9190:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   9191:        }
                   9192:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   9193:      }
                   9194:      /* printf("\n"); */
                   9195:      /* } */
1.266     brouard  9196: 
1.222     brouard  9197:      /* brutal averaging */
1.266     brouard  9198:      /* for (i=1; i<=nlstate;i++){ */
                   9199:      /*   for (age=1; age<=bage; age++){ */
                   9200:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   9201:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9202:      /*   }     */
                   9203:      /*   for (age=fage; age<=AGESUP; age++){ */
                   9204:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   9205:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9206:      /*   } */
                   9207:      /* } /\* end i status *\/ */
                   9208:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   9209:      /*   for (age=1; age<=AGESUP; age++){ */
                   9210:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   9211:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   9212:      /*   } */
                   9213:      /* } */
1.222     brouard  9214:    }/* end cptcod */
1.266     brouard  9215:    free_vector(agemaxgoodr,1, ncovcombmax);
                   9216:    free_vector(agemaxgood,1, ncovcombmax);
                   9217:    free_vector(agemingood,1, ncovcombmax);
                   9218:    free_vector(agemingoodr,1, ncovcombmax);
                   9219:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  9220:    free_vector(sumnewm,1, ncovcombmax);
                   9221:    free_vector(sumnewp,1, ncovcombmax);
                   9222:    return 0;
                   9223:  }/* End movingaverage */
1.218     brouard  9224:  
1.126     brouard  9225: 
1.296     brouard  9226:  
1.126     brouard  9227: /************** Forecasting ******************/
1.296     brouard  9228: /* 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)*/
                   9229: 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){
                   9230:   /* dateintemean, mean date of interviews
                   9231:      dateprojd, year, month, day of starting projection 
                   9232:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  9233:      agemin, agemax range of age
                   9234:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   9235:   */
1.296     brouard  9236:   /* double anprojd, mprojd, jprojd; */
                   9237:   /* double anprojf, mprojf, jprojf; */
1.267     brouard  9238:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  9239:   double agec; /* generic age */
1.296     brouard  9240:   double agelim, ppij, yp,yp1,yp2;
1.126     brouard  9241:   double *popeffectif,*popcount;
                   9242:   double ***p3mat;
1.218     brouard  9243:   /* double ***mobaverage; */
1.126     brouard  9244:   char fileresf[FILENAMELENGTH];
                   9245: 
                   9246:   agelim=AGESUP;
1.211     brouard  9247:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9248:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9249:      We still use firstpass and lastpass as another selection.
                   9250:   */
1.214     brouard  9251:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9252:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  9253:  
1.201     brouard  9254:   strcpy(fileresf,"F_"); 
                   9255:   strcat(fileresf,fileresu);
1.126     brouard  9256:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   9257:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   9258:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   9259:   }
1.235     brouard  9260:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   9261:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  9262: 
1.225     brouard  9263:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  9264: 
                   9265: 
                   9266:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9267:   if (stepm<=12) stepsize=1;
                   9268:   if(estepm < stepm){
                   9269:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9270:   }
1.270     brouard  9271:   else{
                   9272:     hstepm=estepm;   
                   9273:   }
                   9274:   if(estepm > stepm){ /* Yes every two year */
                   9275:     stepsize=2;
                   9276:   }
1.296     brouard  9277:   hstepm=hstepm/stepm;
1.126     brouard  9278: 
1.296     brouard  9279:   
                   9280:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9281:   /*                              fractional in yp1 *\/ */
                   9282:   /* aintmean=yp; */
                   9283:   /* yp2=modf((yp1*12),&yp); */
                   9284:   /* mintmean=yp; */
                   9285:   /* yp1=modf((yp2*30.5),&yp); */
                   9286:   /* jintmean=yp; */
                   9287:   /* if(jintmean==0) jintmean=1; */
                   9288:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  9289: 
1.296     brouard  9290: 
                   9291:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   9292:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   9293:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.227     brouard  9294:   i1=pow(2,cptcoveff);
1.126     brouard  9295:   if (cptcovn < 1){i1=1;}
                   9296:   
1.296     brouard  9297:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  9298:   
                   9299:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  9300:   
1.126     brouard  9301: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  9302:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.332     brouard  9303:     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  9304:     if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  9305:       continue;
1.227     brouard  9306:     if(invalidvarcomb[k]){
                   9307:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   9308:       continue;
                   9309:     }
                   9310:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   9311:     for(j=1;j<=cptcoveff;j++) {
1.332     brouard  9312:       /* fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); */
                   9313:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.227     brouard  9314:     }
1.235     brouard  9315:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  9316:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.235     brouard  9317:     }
1.227     brouard  9318:     fprintf(ficresf," yearproj age");
                   9319:     for(j=1; j<=nlstate+ndeath;j++){ 
                   9320:       for(i=1; i<=nlstate;i++)               
                   9321:        fprintf(ficresf," p%d%d",i,j);
                   9322:       fprintf(ficresf," wp.%d",j);
                   9323:     }
1.296     brouard  9324:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  9325:       fprintf(ficresf,"\n");
1.296     brouard  9326:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  9327:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   9328:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  9329:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   9330:        nhstepm = nhstepm/hstepm; 
                   9331:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9332:        oldm=oldms;savm=savms;
1.268     brouard  9333:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  9334:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  9335:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  9336:        for (h=0; h<=nhstepm; h++){
                   9337:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  9338:            break;
                   9339:          }
                   9340:        }
                   9341:        fprintf(ficresf,"\n");
                   9342:        for(j=1;j<=cptcoveff;j++) 
1.332     brouard  9343:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Tvaraff not correct *\/ */
                   9344:          fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /* TnsdVar[Tvaraff]  correct */
1.296     brouard  9345:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  9346:        
                   9347:        for(j=1; j<=nlstate+ndeath;j++) {
                   9348:          ppij=0.;
                   9349:          for(i=1; i<=nlstate;i++) {
1.278     brouard  9350:            if (mobilav>=1)
                   9351:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   9352:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   9353:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   9354:            }
1.268     brouard  9355:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   9356:          } /* end i */
                   9357:          fprintf(ficresf," %.3f", ppij);
                   9358:        }/* end j */
1.227     brouard  9359:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9360:       } /* end agec */
1.266     brouard  9361:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   9362:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  9363:     } /* end yearp */
                   9364:   } /* end  k */
1.219     brouard  9365:        
1.126     brouard  9366:   fclose(ficresf);
1.215     brouard  9367:   printf("End of Computing forecasting \n");
                   9368:   fprintf(ficlog,"End of Computing forecasting\n");
                   9369: 
1.126     brouard  9370: }
                   9371: 
1.269     brouard  9372: /************** Back Forecasting ******************/
1.296     brouard  9373:  /* 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){ */
                   9374:  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){
                   9375:   /* back1, year, month, day of starting backprojection
1.267     brouard  9376:      agemin, agemax range of age
                   9377:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  9378:      anback2 year of end of backprojection (same day and month as back1).
                   9379:      prevacurrent and prev are prevalences.
1.267     brouard  9380:   */
                   9381:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   9382:   double agec; /* generic age */
1.302     brouard  9383:   double agelim, ppij, ppi, yp,yp1,yp2; /* ,jintmean,mintmean,aintmean;*/
1.267     brouard  9384:   double *popeffectif,*popcount;
                   9385:   double ***p3mat;
                   9386:   /* double ***mobaverage; */
                   9387:   char fileresfb[FILENAMELENGTH];
                   9388:  
1.268     brouard  9389:   agelim=AGEINF;
1.267     brouard  9390:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9391:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9392:      We still use firstpass and lastpass as another selection.
                   9393:   */
                   9394:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9395:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   9396: 
                   9397:   /*Do we need to compute prevalence again?*/
                   9398: 
                   9399:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   9400:   
                   9401:   strcpy(fileresfb,"FB_");
                   9402:   strcat(fileresfb,fileresu);
                   9403:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   9404:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   9405:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   9406:   }
                   9407:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   9408:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   9409:   
                   9410:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   9411:   
                   9412:    
                   9413:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9414:   if (stepm<=12) stepsize=1;
                   9415:   if(estepm < stepm){
                   9416:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9417:   }
1.270     brouard  9418:   else{
                   9419:     hstepm=estepm;   
                   9420:   }
                   9421:   if(estepm >= stepm){ /* Yes every two year */
                   9422:     stepsize=2;
                   9423:   }
1.267     brouard  9424:   
                   9425:   hstepm=hstepm/stepm;
1.296     brouard  9426:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9427:   /*                              fractional in yp1 *\/ */
                   9428:   /* aintmean=yp; */
                   9429:   /* yp2=modf((yp1*12),&yp); */
                   9430:   /* mintmean=yp; */
                   9431:   /* yp1=modf((yp2*30.5),&yp); */
                   9432:   /* jintmean=yp; */
                   9433:   /* if(jintmean==0) jintmean=1; */
                   9434:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  9435:   
                   9436:   i1=pow(2,cptcoveff);
                   9437:   if (cptcovn < 1){i1=1;}
                   9438:   
1.296     brouard  9439:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   9440:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  9441:   
                   9442:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   9443:   
                   9444:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9445:   for(k=1; k<=i1;k++){
                   9446:     if(i1 != 1 && TKresult[nres]!= k)
                   9447:       continue;
                   9448:     if(invalidvarcomb[k]){
                   9449:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   9450:       continue;
                   9451:     }
1.268     brouard  9452:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.267     brouard  9453:     for(j=1;j<=cptcoveff;j++) {
1.332     brouard  9454:       fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.267     brouard  9455:     }
                   9456:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   9457:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9458:     }
                   9459:     fprintf(ficresfb," yearbproj age");
                   9460:     for(j=1; j<=nlstate+ndeath;j++){
                   9461:       for(i=1; i<=nlstate;i++)
1.268     brouard  9462:        fprintf(ficresfb," b%d%d",i,j);
                   9463:       fprintf(ficresfb," b.%d",j);
1.267     brouard  9464:     }
1.296     brouard  9465:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  9466:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   9467:       fprintf(ficresfb,"\n");
1.296     brouard  9468:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  9469:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  9470:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   9471:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  9472:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  9473:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  9474:        nhstepm = nhstepm/hstepm;
                   9475:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9476:        oldm=oldms;savm=savms;
1.268     brouard  9477:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  9478:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  9479:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  9480:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   9481:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   9482:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  9483:        for (h=0; h<=nhstepm; h++){
1.268     brouard  9484:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   9485:            break;
                   9486:          }
                   9487:        }
                   9488:        fprintf(ficresfb,"\n");
                   9489:        for(j=1;j<=cptcoveff;j++)
1.332     brouard  9490:          fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.296     brouard  9491:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  9492:        for(i=1; i<=nlstate+ndeath;i++) {
                   9493:          ppij=0.;ppi=0.;
                   9494:          for(j=1; j<=nlstate;j++) {
                   9495:            /* if (mobilav==1) */
1.269     brouard  9496:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   9497:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   9498:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   9499:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  9500:              /* else { */
                   9501:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   9502:              /* } */
1.268     brouard  9503:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   9504:          } /* end j */
                   9505:          if(ppi <0.99){
                   9506:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   9507:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   9508:          }
                   9509:          fprintf(ficresfb," %.3f", ppij);
                   9510:        }/* end j */
1.267     brouard  9511:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9512:       } /* end agec */
                   9513:     } /* end yearp */
                   9514:   } /* end k */
1.217     brouard  9515:   
1.267     brouard  9516:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  9517:   
1.267     brouard  9518:   fclose(ficresfb);
                   9519:   printf("End of Computing Back forecasting \n");
                   9520:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  9521:        
1.267     brouard  9522: }
1.217     brouard  9523: 
1.269     brouard  9524: /* Variance of prevalence limit: varprlim */
                   9525:  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  9526:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  9527:  
                   9528:    char fileresvpl[FILENAMELENGTH];  
                   9529:    FILE *ficresvpl;
                   9530:    double **oldm, **savm;
                   9531:    double **varpl; /* Variances of prevalence limits by age */   
                   9532:    int i1, k, nres, j ;
                   9533:    
                   9534:     strcpy(fileresvpl,"VPL_");
                   9535:     strcat(fileresvpl,fileresu);
                   9536:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  9537:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  9538:       exit(0);
                   9539:     }
1.288     brouard  9540:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   9541:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  9542:     
                   9543:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   9544:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   9545:     
                   9546:     i1=pow(2,cptcoveff);
                   9547:     if (cptcovn < 1){i1=1;}
                   9548: 
1.337   ! brouard  9549:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
        !          9550:        k=TKresult[nres];
        !          9551:      /* for(k=1; k<=i1;k++){ /\* We find the combination equivalent to result line values of dummies *\/ */
1.269     brouard  9552:       if(i1 != 1 && TKresult[nres]!= k)
                   9553:        continue;
                   9554:       fprintf(ficresvpl,"\n#****** ");
                   9555:       printf("\n#****** ");
                   9556:       fprintf(ficlog,"\n#****** ");
1.337   ! brouard  9557:       for(j=1;j<=cptcovs;j++) {
        !          9558:        fprintf(ficresvpl,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
        !          9559:        fprintf(ficlog,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
        !          9560:        printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
        !          9561:        /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
        !          9562:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.269     brouard  9563:       }
1.337   ! brouard  9564:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
        !          9565:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
        !          9566:       /*       fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
        !          9567:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
        !          9568:       /* }      */
1.269     brouard  9569:       fprintf(ficresvpl,"******\n");
                   9570:       printf("******\n");
                   9571:       fprintf(ficlog,"******\n");
                   9572:       
                   9573:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9574:       oldm=oldms;savm=savms;
                   9575:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   9576:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   9577:       /*}*/
                   9578:     }
                   9579:     
                   9580:     fclose(ficresvpl);
1.288     brouard  9581:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   9582:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  9583: 
                   9584:  }
                   9585: /* Variance of back prevalence: varbprlim */
                   9586:  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){
                   9587:       /*------- Variance of back (stable) prevalence------*/
                   9588: 
                   9589:    char fileresvbl[FILENAMELENGTH];  
                   9590:    FILE  *ficresvbl;
                   9591: 
                   9592:    double **oldm, **savm;
                   9593:    double **varbpl; /* Variances of back prevalence limits by age */   
                   9594:    int i1, k, nres, j ;
                   9595: 
                   9596:    strcpy(fileresvbl,"VBL_");
                   9597:    strcat(fileresvbl,fileresu);
                   9598:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   9599:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   9600:      exit(0);
                   9601:    }
                   9602:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   9603:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   9604:    
                   9605:    
                   9606:    i1=pow(2,cptcoveff);
                   9607:    if (cptcovn < 1){i1=1;}
                   9608:    
1.337   ! brouard  9609:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
        !          9610:      k=TKresult[nres];
        !          9611:     /* for(k=1; k<=i1;k++){ */
        !          9612:     /*    if(i1 != 1 && TKresult[nres]!= k) */
        !          9613:     /*          continue; */
1.269     brouard  9614:        fprintf(ficresvbl,"\n#****** ");
                   9615:        printf("\n#****** ");
                   9616:        fprintf(ficlog,"\n#****** ");
1.337   ! brouard  9617:        for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */
        !          9618:         printf(" V%d=%lg ",Tvqresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
        !          9619:         fprintf(ficresvbl," V%d=%lg ",Tvqresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
        !          9620:         fprintf(ficlog," V%d=%lg ",Tvqresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
        !          9621:        /* for(j=1;j<=cptcoveff;j++) { */
        !          9622:        /*       fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
        !          9623:        /*       fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
        !          9624:        /*       printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
        !          9625:        /* } */
        !          9626:        /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
        !          9627:        /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
        !          9628:        /*       fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
        !          9629:        /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
1.269     brouard  9630:        }
                   9631:        fprintf(ficresvbl,"******\n");
                   9632:        printf("******\n");
                   9633:        fprintf(ficlog,"******\n");
                   9634:        
                   9635:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9636:        oldm=oldms;savm=savms;
                   9637:        
                   9638:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   9639:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   9640:        /*}*/
                   9641:      }
                   9642:    
                   9643:    fclose(ficresvbl);
                   9644:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   9645:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   9646: 
                   9647:  } /* End of varbprlim */
                   9648: 
1.126     brouard  9649: /************** Forecasting *****not tested NB*************/
1.227     brouard  9650: /* 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  9651:   
1.227     brouard  9652: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   9653: /*   int *popage; */
                   9654: /*   double calagedatem, agelim, kk1, kk2; */
                   9655: /*   double *popeffectif,*popcount; */
                   9656: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   9657: /*   /\* double ***mobaverage; *\/ */
                   9658: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  9659: 
1.227     brouard  9660: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9661: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9662: /*   agelim=AGESUP; */
                   9663: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  9664:   
1.227     brouard  9665: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  9666:   
                   9667:   
1.227     brouard  9668: /*   strcpy(filerespop,"POP_");  */
                   9669: /*   strcat(filerespop,fileresu); */
                   9670: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   9671: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   9672: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   9673: /*   } */
                   9674: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   9675: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  9676: 
1.227     brouard  9677: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  9678: 
1.227     brouard  9679: /*   /\* if (mobilav!=0) { *\/ */
                   9680: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   9681: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   9682: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   9683: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   9684: /*   /\*   } *\/ */
                   9685: /*   /\* } *\/ */
1.126     brouard  9686: 
1.227     brouard  9687: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   9688: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  9689:   
1.227     brouard  9690: /*   agelim=AGESUP; */
1.126     brouard  9691:   
1.227     brouard  9692: /*   hstepm=1; */
                   9693: /*   hstepm=hstepm/stepm;  */
1.218     brouard  9694:        
1.227     brouard  9695: /*   if (popforecast==1) { */
                   9696: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   9697: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   9698: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   9699: /*     }  */
                   9700: /*     popage=ivector(0,AGESUP); */
                   9701: /*     popeffectif=vector(0,AGESUP); */
                   9702: /*     popcount=vector(0,AGESUP); */
1.126     brouard  9703:     
1.227     brouard  9704: /*     i=1;    */
                   9705: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  9706:     
1.227     brouard  9707: /*     imx=i; */
                   9708: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   9709: /*   } */
1.218     brouard  9710:   
1.227     brouard  9711: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   9712: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   9713: /*       k=k+1; */
                   9714: /*       fprintf(ficrespop,"\n#******"); */
                   9715: /*       for(j=1;j<=cptcoveff;j++) { */
                   9716: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   9717: /*       } */
                   9718: /*       fprintf(ficrespop,"******\n"); */
                   9719: /*       fprintf(ficrespop,"# Age"); */
                   9720: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   9721: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  9722:       
1.227     brouard  9723: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   9724: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  9725:        
1.227     brouard  9726: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   9727: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   9728: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  9729:          
1.227     brouard  9730: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9731: /*       oldm=oldms;savm=savms; */
                   9732: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  9733:          
1.227     brouard  9734: /*       for (h=0; h<=nhstepm; h++){ */
                   9735: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   9736: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   9737: /*         }  */
                   9738: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   9739: /*           kk1=0.;kk2=0; */
                   9740: /*           for(i=1; i<=nlstate;i++) {               */
                   9741: /*             if (mobilav==1)  */
                   9742: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   9743: /*             else { */
                   9744: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   9745: /*             } */
                   9746: /*           } */
                   9747: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   9748: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   9749: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   9750: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   9751: /*           } */
                   9752: /*         } */
                   9753: /*         for(i=1; i<=nlstate;i++){ */
                   9754: /*           kk1=0.; */
                   9755: /*           for(j=1; j<=nlstate;j++){ */
                   9756: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   9757: /*           } */
                   9758: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   9759: /*         } */
1.218     brouard  9760:            
1.227     brouard  9761: /*         if (h==(int)(calagedatem+12*cpt)) */
                   9762: /*           for(j=1; j<=nlstate;j++)  */
                   9763: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   9764: /*       } */
                   9765: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9766: /*     } */
                   9767: /*       } */
1.218     brouard  9768:       
1.227     brouard  9769: /*       /\******\/ */
1.218     brouard  9770:       
1.227     brouard  9771: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   9772: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   9773: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   9774: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   9775: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  9776:          
1.227     brouard  9777: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9778: /*       oldm=oldms;savm=savms; */
                   9779: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   9780: /*       for (h=0; h<=nhstepm; h++){ */
                   9781: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   9782: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   9783: /*         }  */
                   9784: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   9785: /*           kk1=0.;kk2=0; */
                   9786: /*           for(i=1; i<=nlstate;i++) {               */
                   9787: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   9788: /*           } */
                   9789: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   9790: /*         } */
                   9791: /*       } */
                   9792: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9793: /*     } */
                   9794: /*       } */
                   9795: /*     }  */
                   9796: /*   } */
1.218     brouard  9797:   
1.227     brouard  9798: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  9799:   
1.227     brouard  9800: /*   if (popforecast==1) { */
                   9801: /*     free_ivector(popage,0,AGESUP); */
                   9802: /*     free_vector(popeffectif,0,AGESUP); */
                   9803: /*     free_vector(popcount,0,AGESUP); */
                   9804: /*   } */
                   9805: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9806: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9807: /*   fclose(ficrespop); */
                   9808: /* } /\* End of popforecast *\/ */
1.218     brouard  9809:  
1.126     brouard  9810: int fileappend(FILE *fichier, char *optionfich)
                   9811: {
                   9812:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   9813:     printf("Problem with file: %s\n", optionfich);
                   9814:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   9815:     return (0);
                   9816:   }
                   9817:   fflush(fichier);
                   9818:   return (1);
                   9819: }
                   9820: 
                   9821: 
                   9822: /**************** function prwizard **********************/
                   9823: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   9824: {
                   9825: 
                   9826:   /* Wizard to print covariance matrix template */
                   9827: 
1.164     brouard  9828:   char ca[32], cb[32];
                   9829:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  9830:   int numlinepar;
                   9831: 
                   9832:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9833:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9834:   for(i=1; i <=nlstate; i++){
                   9835:     jj=0;
                   9836:     for(j=1; j <=nlstate+ndeath; j++){
                   9837:       if(j==i) continue;
                   9838:       jj++;
                   9839:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   9840:       printf("%1d%1d",i,j);
                   9841:       fprintf(ficparo,"%1d%1d",i,j);
                   9842:       for(k=1; k<=ncovmodel;k++){
                   9843:        /*        printf(" %lf",param[i][j][k]); */
                   9844:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   9845:        printf(" 0.");
                   9846:        fprintf(ficparo," 0.");
                   9847:       }
                   9848:       printf("\n");
                   9849:       fprintf(ficparo,"\n");
                   9850:     }
                   9851:   }
                   9852:   printf("# Scales (for hessian or gradient estimation)\n");
                   9853:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   9854:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   9855:   for(i=1; i <=nlstate; i++){
                   9856:     jj=0;
                   9857:     for(j=1; j <=nlstate+ndeath; j++){
                   9858:       if(j==i) continue;
                   9859:       jj++;
                   9860:       fprintf(ficparo,"%1d%1d",i,j);
                   9861:       printf("%1d%1d",i,j);
                   9862:       fflush(stdout);
                   9863:       for(k=1; k<=ncovmodel;k++){
                   9864:        /*      printf(" %le",delti3[i][j][k]); */
                   9865:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   9866:        printf(" 0.");
                   9867:        fprintf(ficparo," 0.");
                   9868:       }
                   9869:       numlinepar++;
                   9870:       printf("\n");
                   9871:       fprintf(ficparo,"\n");
                   9872:     }
                   9873:   }
                   9874:   printf("# Covariance matrix\n");
                   9875: /* # 121 Var(a12)\n\ */
                   9876: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   9877: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   9878: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   9879: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   9880: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   9881: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   9882: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   9883:   fflush(stdout);
                   9884:   fprintf(ficparo,"# Covariance matrix\n");
                   9885:   /* # 121 Var(a12)\n\ */
                   9886:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   9887:   /* #   ...\n\ */
                   9888:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   9889:   
                   9890:   for(itimes=1;itimes<=2;itimes++){
                   9891:     jj=0;
                   9892:     for(i=1; i <=nlstate; i++){
                   9893:       for(j=1; j <=nlstate+ndeath; j++){
                   9894:        if(j==i) continue;
                   9895:        for(k=1; k<=ncovmodel;k++){
                   9896:          jj++;
                   9897:          ca[0]= k+'a'-1;ca[1]='\0';
                   9898:          if(itimes==1){
                   9899:            printf("#%1d%1d%d",i,j,k);
                   9900:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   9901:          }else{
                   9902:            printf("%1d%1d%d",i,j,k);
                   9903:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   9904:            /*  printf(" %.5le",matcov[i][j]); */
                   9905:          }
                   9906:          ll=0;
                   9907:          for(li=1;li <=nlstate; li++){
                   9908:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   9909:              if(lj==li) continue;
                   9910:              for(lk=1;lk<=ncovmodel;lk++){
                   9911:                ll++;
                   9912:                if(ll<=jj){
                   9913:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   9914:                  if(ll<jj){
                   9915:                    if(itimes==1){
                   9916:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9917:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9918:                    }else{
                   9919:                      printf(" 0.");
                   9920:                      fprintf(ficparo," 0.");
                   9921:                    }
                   9922:                  }else{
                   9923:                    if(itimes==1){
                   9924:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   9925:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   9926:                    }else{
                   9927:                      printf(" 0.");
                   9928:                      fprintf(ficparo," 0.");
                   9929:                    }
                   9930:                  }
                   9931:                }
                   9932:              } /* end lk */
                   9933:            } /* end lj */
                   9934:          } /* end li */
                   9935:          printf("\n");
                   9936:          fprintf(ficparo,"\n");
                   9937:          numlinepar++;
                   9938:        } /* end k*/
                   9939:       } /*end j */
                   9940:     } /* end i */
                   9941:   } /* end itimes */
                   9942: 
                   9943: } /* end of prwizard */
                   9944: /******************* Gompertz Likelihood ******************************/
                   9945: double gompertz(double x[])
                   9946: { 
1.302     brouard  9947:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
1.126     brouard  9948:   int i,n=0; /* n is the size of the sample */
                   9949: 
1.220     brouard  9950:   for (i=1;i<=imx ; i++) {
1.126     brouard  9951:     sump=sump+weight[i];
                   9952:     /*    sump=sump+1;*/
                   9953:     num=num+1;
                   9954:   }
1.302     brouard  9955:   L=0.0;
                   9956:   /* agegomp=AGEGOMP; */
1.126     brouard  9957:   /* for (i=0; i<=imx; i++) 
                   9958:      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]);*/
                   9959: 
1.302     brouard  9960:   for (i=1;i<=imx ; i++) {
                   9961:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   9962:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   9963:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   9964:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   9965:      * +
                   9966:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   9967:      */
                   9968:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   9969:        if (cens[i] == 1){
                   9970:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   9971:        } else if (cens[i] == 0){
1.126     brouard  9972:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
1.302     brouard  9973:          +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   9974:       } else
                   9975:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
1.126     brouard  9976:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
1.302     brouard  9977:        L=L+A*weight[i];
1.126     brouard  9978:        /*      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  9979:      }
                   9980:   }
1.126     brouard  9981: 
1.302     brouard  9982:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
1.126     brouard  9983:  
                   9984:   return -2*L*num/sump;
                   9985: }
                   9986: 
1.136     brouard  9987: #ifdef GSL
                   9988: /******************* Gompertz_f Likelihood ******************************/
                   9989: double gompertz_f(const gsl_vector *v, void *params)
                   9990: { 
1.302     brouard  9991:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
1.136     brouard  9992:   double *x= (double *) v->data;
                   9993:   int i,n=0; /* n is the size of the sample */
                   9994: 
                   9995:   for (i=0;i<=imx-1 ; i++) {
                   9996:     sump=sump+weight[i];
                   9997:     /*    sump=sump+1;*/
                   9998:     num=num+1;
                   9999:   }
                   10000:  
                   10001:  
                   10002:   /* for (i=0; i<=imx; i++) 
                   10003:      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]);*/
                   10004:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   10005:   for (i=1;i<=imx ; i++)
                   10006:     {
                   10007:       if (cens[i] == 1 && wav[i]>1)
                   10008:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   10009:       
                   10010:       if (cens[i] == 0 && wav[i]>1)
                   10011:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   10012:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   10013:       
                   10014:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   10015:       if (wav[i] > 1 ) { /* ??? */
                   10016:        LL=LL+A*weight[i];
                   10017:        /*      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]);*/
                   10018:       }
                   10019:     }
                   10020: 
                   10021:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   10022:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   10023:  
                   10024:   return -2*LL*num/sump;
                   10025: }
                   10026: #endif
                   10027: 
1.126     brouard  10028: /******************* Printing html file ***********/
1.201     brouard  10029: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  10030:                  int lastpass, int stepm, int weightopt, char model[],\
                   10031:                  int imx,  double p[],double **matcov,double agemortsup){
                   10032:   int i,k;
                   10033: 
                   10034:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   10035:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   10036:   for (i=1;i<=2;i++) 
                   10037:     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  10038:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  10039:   fprintf(fichtm,"</ul>");
                   10040: 
                   10041: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   10042: 
                   10043:  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>");
                   10044: 
                   10045:  for (k=agegomp;k<(agemortsup-2);k++) 
                   10046:    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]);
                   10047: 
                   10048:  
                   10049:   fflush(fichtm);
                   10050: }
                   10051: 
                   10052: /******************* Gnuplot file **************/
1.201     brouard  10053: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  10054: 
                   10055:   char dirfileres[132],optfileres[132];
1.164     brouard  10056: 
1.126     brouard  10057:   int ng;
                   10058: 
                   10059: 
                   10060:   /*#ifdef windows */
                   10061:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   10062:     /*#endif */
                   10063: 
                   10064: 
                   10065:   strcpy(dirfileres,optionfilefiname);
                   10066:   strcpy(optfileres,"vpl");
1.199     brouard  10067:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  10068:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  10069:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  10070:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  10071:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   10072: 
                   10073: } 
                   10074: 
1.136     brouard  10075: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   10076: {
1.126     brouard  10077: 
1.136     brouard  10078:   /*-------- data file ----------*/
                   10079:   FILE *fic;
                   10080:   char dummy[]="                         ";
1.240     brouard  10081:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  10082:   int lstra;
1.136     brouard  10083:   int linei, month, year,iout;
1.302     brouard  10084:   int noffset=0; /* This is the offset if BOM data file */
1.136     brouard  10085:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  10086:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  10087:   char *stratrunc;
1.223     brouard  10088: 
1.240     brouard  10089:   DummyV=ivector(1,NCOVMAX); /* 1 to 3 */
                   10090:   FixedV=ivector(1,NCOVMAX); /* 1 to 3 */
1.328     brouard  10091:   for(v=1;v<NCOVMAX;v++){
                   10092:     DummyV[v]=0;
                   10093:     FixedV[v]=0;
                   10094:   }
1.126     brouard  10095: 
1.240     brouard  10096:   for(v=1; v <=ncovcol;v++){
                   10097:     DummyV[v]=0;
                   10098:     FixedV[v]=0;
                   10099:   }
                   10100:   for(v=ncovcol+1; v <=ncovcol+nqv;v++){
                   10101:     DummyV[v]=1;
                   10102:     FixedV[v]=0;
                   10103:   }
                   10104:   for(v=ncovcol+nqv+1; v <=ncovcol+nqv+ntv;v++){
                   10105:     DummyV[v]=0;
                   10106:     FixedV[v]=1;
                   10107:   }
                   10108:   for(v=ncovcol+nqv+ntv+1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   10109:     DummyV[v]=1;
                   10110:     FixedV[v]=1;
                   10111:   }
                   10112:   for(v=1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   10113:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   10114:     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]);
                   10115:   }
1.126     brouard  10116: 
1.136     brouard  10117:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  10118:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10119:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  10120:   }
1.126     brouard  10121: 
1.302     brouard  10122:     /* Is it a BOM UTF-8 Windows file? */
                   10123:   /* First data line */
                   10124:   linei=0;
                   10125:   while(fgets(line, MAXLINE, fic)) {
                   10126:     noffset=0;
                   10127:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   10128:     {
                   10129:       noffset=noffset+3;
                   10130:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   10131:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   10132:       fflush(ficlog); return 1;
                   10133:     }
                   10134:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   10135:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   10136:     {
                   10137:       noffset=noffset+2;
1.304     brouard  10138:       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);
                   10139:       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  10140:       fflush(ficlog); return 1;
                   10141:     }
                   10142:     else if( line[0] == 0 && line[1] == 0)
                   10143:     {
                   10144:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   10145:        noffset=noffset+4;
1.304     brouard  10146:        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);
                   10147:        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  10148:        fflush(ficlog); return 1;
                   10149:       }
                   10150:     } else{
                   10151:       ;/*printf(" Not a BOM file\n");*/
                   10152:     }
                   10153:         /* If line starts with a # it is a comment */
                   10154:     if (line[noffset] == '#') {
                   10155:       linei=linei+1;
                   10156:       break;
                   10157:     }else{
                   10158:       break;
                   10159:     }
                   10160:   }
                   10161:   fclose(fic);
                   10162:   if((fic=fopen(datafile,"r"))==NULL)    {
                   10163:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10164:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   10165:   }
                   10166:   /* Not a Bom file */
                   10167:   
1.136     brouard  10168:   i=1;
                   10169:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   10170:     linei=linei+1;
                   10171:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   10172:       if(line[j] == '\t')
                   10173:        line[j] = ' ';
                   10174:     }
                   10175:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   10176:       ;
                   10177:     };
                   10178:     line[j+1]=0;  /* Trims blanks at end of line */
                   10179:     if(line[0]=='#'){
                   10180:       fprintf(ficlog,"Comment line\n%s\n",line);
                   10181:       printf("Comment line\n%s\n",line);
                   10182:       continue;
                   10183:     }
                   10184:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  10185:     strcpy(line, linetmp);
1.223     brouard  10186:     
                   10187:     /* Loops on waves */
                   10188:     for (j=maxwav;j>=1;j--){
                   10189:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  10190:        cutv(stra, strb, line, ' '); 
                   10191:        if(strb[0]=='.') { /* Missing value */
                   10192:          lval=-1;
                   10193:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
                   10194:          cotvar[j][ntv+iv][i]=-1; /* For performance reasons */
                   10195:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   10196:            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);
                   10197:            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);
                   10198:            return 1;
                   10199:          }
                   10200:        }else{
                   10201:          errno=0;
                   10202:          /* what_kind_of_number(strb); */
                   10203:          dval=strtod(strb,&endptr); 
                   10204:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   10205:          /* if(strb != endptr && *endptr == '\0') */
                   10206:          /*    dval=dlval; */
                   10207:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10208:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10209:            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);
                   10210:            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);
                   10211:            return 1;
                   10212:          }
                   10213:          cotqvar[j][iv][i]=dval; 
                   10214:          cotvar[j][ntv+iv][i]=dval; 
                   10215:        }
                   10216:        strcpy(line,stra);
1.223     brouard  10217:       }/* end loop ntqv */
1.225     brouard  10218:       
1.223     brouard  10219:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  10220:        cutv(stra, strb, line, ' '); 
                   10221:        if(strb[0]=='.') { /* Missing value */
                   10222:          lval=-1;
                   10223:        }else{
                   10224:          errno=0;
                   10225:          lval=strtol(strb,&endptr,10); 
                   10226:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   10227:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10228:            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);
                   10229:            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);
                   10230:            return 1;
                   10231:          }
                   10232:        }
                   10233:        if(lval <-1 || lval >1){
                   10234:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10235:  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  10236:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10237:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10238:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10239:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10240:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10241:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10242:  Exiting.\n",lval,linei, i,line,iv,j);
1.238     brouard  10243:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10244:  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  10245:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10246:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10247:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10248:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10249:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10250:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10251:  Exiting.\n",lval,linei, i,line,iv,j);fflush(ficlog);
1.238     brouard  10252:          return 1;
                   10253:        }
                   10254:        cotvar[j][iv][i]=(double)(lval);
                   10255:        strcpy(line,stra);
1.223     brouard  10256:       }/* end loop ntv */
1.225     brouard  10257:       
1.223     brouard  10258:       /* Statuses  at wave */
1.137     brouard  10259:       cutv(stra, strb, line, ' '); 
1.223     brouard  10260:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  10261:        lval=-1;
1.136     brouard  10262:       }else{
1.238     brouard  10263:        errno=0;
                   10264:        lval=strtol(strb,&endptr,10); 
                   10265:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   10266:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10267:          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);
                   10268:          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);
                   10269:          return 1;
                   10270:        }
1.136     brouard  10271:       }
1.225     brouard  10272:       
1.136     brouard  10273:       s[j][i]=lval;
1.225     brouard  10274:       
1.223     brouard  10275:       /* Date of Interview */
1.136     brouard  10276:       strcpy(line,stra);
                   10277:       cutv(stra, strb,line,' ');
1.169     brouard  10278:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10279:       }
1.169     brouard  10280:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  10281:        month=99;
                   10282:        year=9999;
1.136     brouard  10283:       }else{
1.225     brouard  10284:        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);
                   10285:        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);
                   10286:        return 1;
1.136     brouard  10287:       }
                   10288:       anint[j][i]= (double) year; 
1.302     brouard  10289:       mint[j][i]= (double)month;
                   10290:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   10291:       /*       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]); */
                   10292:       /*       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]); */
                   10293:       /* } */
1.136     brouard  10294:       strcpy(line,stra);
1.223     brouard  10295:     } /* End loop on waves */
1.225     brouard  10296:     
1.223     brouard  10297:     /* Date of death */
1.136     brouard  10298:     cutv(stra, strb,line,' '); 
1.169     brouard  10299:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10300:     }
1.169     brouard  10301:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  10302:       month=99;
                   10303:       year=9999;
                   10304:     }else{
1.141     brouard  10305:       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  10306:       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);
                   10307:       return 1;
1.136     brouard  10308:     }
                   10309:     andc[i]=(double) year; 
                   10310:     moisdc[i]=(double) month; 
                   10311:     strcpy(line,stra);
                   10312:     
1.223     brouard  10313:     /* Date of birth */
1.136     brouard  10314:     cutv(stra, strb,line,' '); 
1.169     brouard  10315:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10316:     }
1.169     brouard  10317:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  10318:       month=99;
                   10319:       year=9999;
                   10320:     }else{
1.141     brouard  10321:       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);
                   10322:       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  10323:       return 1;
1.136     brouard  10324:     }
                   10325:     if (year==9999) {
1.141     brouard  10326:       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);
                   10327:       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  10328:       return 1;
                   10329:       
1.136     brouard  10330:     }
                   10331:     annais[i]=(double)(year);
1.302     brouard  10332:     moisnais[i]=(double)(month);
                   10333:     for (j=1;j<=maxwav;j++){
                   10334:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   10335:        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]);
                   10336:        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]);
                   10337:       }
                   10338:     }
                   10339: 
1.136     brouard  10340:     strcpy(line,stra);
1.225     brouard  10341:     
1.223     brouard  10342:     /* Sample weight */
1.136     brouard  10343:     cutv(stra, strb,line,' '); 
                   10344:     errno=0;
                   10345:     dval=strtod(strb,&endptr); 
                   10346:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  10347:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   10348:       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  10349:       fflush(ficlog);
                   10350:       return 1;
                   10351:     }
                   10352:     weight[i]=dval; 
                   10353:     strcpy(line,stra);
1.225     brouard  10354:     
1.223     brouard  10355:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   10356:       cutv(stra, strb, line, ' '); 
                   10357:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  10358:        lval=-1;
1.311     brouard  10359:        coqvar[iv][i]=NAN; 
                   10360:        covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  10361:       }else{
1.225     brouard  10362:        errno=0;
                   10363:        /* what_kind_of_number(strb); */
                   10364:        dval=strtod(strb,&endptr);
                   10365:        /* if(strb != endptr && *endptr == '\0') */
                   10366:        /*   dval=dlval; */
                   10367:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10368:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10369:          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);
                   10370:          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);
                   10371:          return 1;
                   10372:        }
                   10373:        coqvar[iv][i]=dval; 
1.226     brouard  10374:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  10375:       }
                   10376:       strcpy(line,stra);
                   10377:     }/* end loop nqv */
1.136     brouard  10378:     
1.223     brouard  10379:     /* Covariate values */
1.136     brouard  10380:     for (j=ncovcol;j>=1;j--){
                   10381:       cutv(stra, strb,line,' '); 
1.223     brouard  10382:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  10383:        lval=-1;
1.136     brouard  10384:       }else{
1.225     brouard  10385:        errno=0;
                   10386:        lval=strtol(strb,&endptr,10); 
                   10387:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10388:          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);
                   10389:          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);
                   10390:          return 1;
                   10391:        }
1.136     brouard  10392:       }
                   10393:       if(lval <-1 || lval >1){
1.225     brouard  10394:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  10395:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   10396:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  10397:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10398:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10399:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  10400:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  10401:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  10402:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  10403:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  10404:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   10405:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  10406:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10407:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10408:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  10409:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  10410:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  10411:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  10412:        return 1;
1.136     brouard  10413:       }
                   10414:       covar[j][i]=(double)(lval);
                   10415:       strcpy(line,stra);
                   10416:     }  
                   10417:     lstra=strlen(stra);
1.225     brouard  10418:     
1.136     brouard  10419:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   10420:       stratrunc = &(stra[lstra-9]);
                   10421:       num[i]=atol(stratrunc);
                   10422:     }
                   10423:     else
                   10424:       num[i]=atol(stra);
                   10425:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   10426:       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;}*/
                   10427:     
                   10428:     i=i+1;
                   10429:   } /* End loop reading  data */
1.225     brouard  10430:   
1.136     brouard  10431:   *imax=i-1; /* Number of individuals */
                   10432:   fclose(fic);
1.225     brouard  10433:   
1.136     brouard  10434:   return (0);
1.164     brouard  10435:   /* endread: */
1.225     brouard  10436:   printf("Exiting readdata: ");
                   10437:   fclose(fic);
                   10438:   return (1);
1.223     brouard  10439: }
1.126     brouard  10440: 
1.234     brouard  10441: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  10442:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  10443:   while (*p2 == ' ')
1.234     brouard  10444:     p2++; 
                   10445:   /* while ((*p1++ = *p2++) !=0) */
                   10446:   /*   ; */
                   10447:   /* do */
                   10448:   /*   while (*p2 == ' ') */
                   10449:   /*     p2++; */
                   10450:   /* while (*p1++ == *p2++); */
                   10451:   *stri=p2; 
1.145     brouard  10452: }
                   10453: 
1.330     brouard  10454: int decoderesult( char resultline[], int nres)
1.230     brouard  10455: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   10456: {
1.235     brouard  10457:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  10458:   char resultsav[MAXLINE];
1.330     brouard  10459:   /* int resultmodel[MAXLINE]; */
1.334     brouard  10460:   /* int modelresult[MAXLINE]; */
1.230     brouard  10461:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   10462: 
1.234     brouard  10463:   removefirstspace(&resultline);
1.332     brouard  10464:   printf("decoderesult:%s\n",resultline);
1.230     brouard  10465: 
1.332     brouard  10466:   strcpy(resultsav,resultline);
                   10467:   printf("Decoderesult resultsav=\"%s\" resultline=\"%s\"\n", resultsav, resultline);
1.230     brouard  10468:   if (strlen(resultsav) >1){
1.334     brouard  10469:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' in this resultline */
1.230     brouard  10470:   }
1.253     brouard  10471:   if(j == 0){ /* Resultline but no = */
                   10472:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   10473:     return (0);
                   10474:   }
1.234     brouard  10475:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
1.334     brouard  10476:     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);
                   10477:     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  10478:     /* return 1;*/
1.234     brouard  10479:   }
1.334     brouard  10480:   for(k=1; k<=j;k++){ /* Loop on any covariate of the RESULT LINE */
1.234     brouard  10481:     if(nbocc(resultsav,'=') >1){
1.318     brouard  10482:       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  10483:       /* 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  10484:       cutl(strc,strd,strb,'=');  /* strb:"V4=1" strc="1" strd="V4" */
1.332     brouard  10485:       /* If a blank, then strc="V4=" and strd='\0' */
                   10486:       if(strc[0]=='\0'){
                   10487:       printf("Error in resultline, probably a blank after the \"%s\", \"result:%s\", stra=\"%s\" resultsav=\"%s\"\n",strb,resultline, stra, resultsav);
                   10488:        fprintf(ficlog,"Error in resultline, probably a blank after the \"V%s=\", resultline=%s\n",strb,resultline);
                   10489:        return 1;
                   10490:       }
1.234     brouard  10491:     }else
                   10492:       cutl(strc,strd,resultsav,'=');
1.318     brouard  10493:     Tvalsel[k]=atof(strc); /* 1 */ /* Tvalsel of k is the float value of the kth covariate appearing in this result line */
1.234     brouard  10494:     
1.230     brouard  10495:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
1.318     brouard  10496:     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  10497:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   10498:     /* cptcovsel++;     */
                   10499:     if (nbocc(stra,'=') >0)
                   10500:       strcpy(resultsav,stra); /* and analyzes it */
                   10501:   }
1.235     brouard  10502:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  10503:   /* 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  10504:   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  10505:     if(Typevar[k1]==0){ /* Single covariate in model */
                   10506:       /* 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.234     brouard  10507:       match=0;
1.318     brouard  10508:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10509:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  10510:          modelresult[nres][k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.318     brouard  10511:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
1.234     brouard  10512:          break;
                   10513:        }
                   10514:       }
                   10515:       if(match == 0){
1.332     brouard  10516:        printf("Error in result line (Dummy single): V%d is missing in result: %s according to model=%s. Tvar[k1=%d]=%d is different from Tvarsel[k2=%d]=%d.\n",Tvar[k1], resultline, model,k1, Tvar[k1], k2, Tvarsel[k2]);
                   10517:        fprintf(ficlog,"Error in result line (Dummy single): V%d is missing in result: %s according to model=%s\n",Tvar[k1], resultline, model);
1.310     brouard  10518:        return 1;
1.234     brouard  10519:       }
1.332     brouard  10520:     }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*/
                   10521:       /* We feed resultmodel[k1]=k2; */
                   10522:       match=0;
                   10523:       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 */
                   10524:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  10525:          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  10526:          resultmodel[nres][k1]=k2; /* Added here */
                   10527:          printf("Decoderesult first modelresult[k2=%d]=%d (k1) V%d*AGE\n",k2,k1,Tvar[k1]);
                   10528:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10529:          break;
                   10530:        }
                   10531:       }
                   10532:       if(match == 0){
                   10533:        printf("Error in result line (Product with age): V%d is missing in result: %s according to model=%s (Tvarsel[k2=%d]=%d)\n",Tvar[k1], resultline, model, k2, Tvarsel[k2]);
1.333     brouard  10534:        fprintf(ficlog,"Error in result line (Product with age): V%d is missing in result: %s according to model=%s (Tvarsel[k2=%d]=%d)\n",Tvar[k1], resultline, model, k2, Tvarsel[k2]);
1.332     brouard  10535:       return 1;
                   10536:       }
                   10537:     }else if(Typevar[k1]==2){ /* Product No age We want to get the position in the resultline of the product in the model line*/
                   10538:       /* resultmodel[nres][of such a Vn * Vm product k1] is not unique, so can't exist, we feed Tvard[k1][1] and [2] */ 
                   10539:       match=0;
                   10540:       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]);
                   10541:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10542:        if(Tvardk[k1][1]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   10543:          /* modelresult[k2]=k1; */
                   10544:          printf("Decoderesult first Product modelresult[k2=%d]=%d (k1) V%d * \n",k2,k1,Tvarsel[k2]);
                   10545:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10546:        }
                   10547:       }
                   10548:       if(match == 0){
                   10549:        printf("Error in result line (Product without age first variable): V%d is missing in result: %s according to model=%s\n",Tvardk[k1][1], resultline, model);
1.333     brouard  10550:        fprintf(ficlog,"Error in result line (Product without age first variable): V%d is missing in result: %s according to model=%s\n",Tvardk[k1][1], resultline, model);
1.332     brouard  10551:        return 1;
                   10552:       }
                   10553:       match=0;
                   10554:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10555:        if(Tvardk[k1][2]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   10556:          /* modelresult[k2]=k1;*/
                   10557:          printf("Decoderesult second Product modelresult[k2=%d]=%d (k1) * V%d \n ",k2,k1,Tvarsel[k2]);
                   10558:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10559:          break;
                   10560:        }
                   10561:       }
                   10562:       if(match == 0){
                   10563:        printf("Error in result line (Product without age second variable): V%d is missing in result: %s according to model=%s\n",Tvardk[k1][2], resultline, model);
1.333     brouard  10564:        fprintf(ficlog,"Error in result line (Product without age second variable): V%d is missing in result : %s according to model=%s\n",Tvardk[k1][2], resultline, model);
1.332     brouard  10565:        return 1;
                   10566:       }
                   10567:     }/* End of testing */
1.333     brouard  10568:   }/* End loop cptcovt */
1.235     brouard  10569:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  10570:   /* Feeds resultmodel[nres][k1]=k2 for single covariate (k1) in the model equation */
1.334     brouard  10571:   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)
                   10572:                           * Loop on resultline variables: result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  10573:     match=0;
1.318     brouard  10574:     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  10575:       if(Typevar[k1]==0){ /* Single only */
1.237     brouard  10576:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4   */
1.330     brouard  10577:          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  10578:          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  10579:          ++match;
                   10580:        }
                   10581:       }
                   10582:     }
                   10583:     if(match == 0){
1.332     brouard  10584:       printf("Error in result line: variable V%d is missing in model; result: %s, model=%s\n",Tvarsel[k2], resultline, model);
                   10585:       fprintf(ficlog,"Error in result line: variable V%d is missing in model; result: %s, model=%s\n",Tvarsel[k2], resultline, model);
1.310     brouard  10586:       return 1;
1.234     brouard  10587:     }else if(match > 1){
                   10588:       printf("Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
1.310     brouard  10589:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
                   10590:       return 1;
1.234     brouard  10591:     }
                   10592:   }
1.334     brouard  10593:   /* cptcovres=j /\* Number of variables in the resultline is equal to cptcovs and thus useless *\/     */
1.234     brouard  10594:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  10595:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.330     brouard  10596:   /* nres=1st result line: V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   10597:   /* 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*/
                   10598:   /* nres=2nd result line: V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.235     brouard  10599:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   10600:   /*    1 0 0 0 */
                   10601:   /*    2 1 0 0 */
                   10602:   /*    3 0 1 0 */ 
1.330     brouard  10603:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 (nres=2)*/
1.235     brouard  10604:   /*    5 0 0 1 */
1.330     brouard  10605:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 (nres=1)*/
1.235     brouard  10606:   /*    7 0 1 1 */
                   10607:   /*    8 1 1 1 */
1.237     brouard  10608:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   10609:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   10610:   /* V5*age V5 known which value for nres?  */
                   10611:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.334     brouard  10612:   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.
                   10613:                                                   * loop on position k1 in the MODEL LINE */
1.331     brouard  10614:     /* k counting number of combination of single dummies in the equation model */
                   10615:     /* k4 counting single dummies in the equation model */
                   10616:     /* k4q counting single quantitatives in the equation model */
1.334     brouard  10617:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Dummy and Single, k1 is sorting according to MODEL, but k3 to resultline */
                   10618:        /* 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  10619:       /* 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  10620:       /* Value in the (current nres) resultline of the variable at the k1th position in the model equation resultmodel[nres][k1]= k3 */
1.332     brouard  10621:       /* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline                        */
                   10622:       /*      k3 is the position in the nres result line of the k1th variable of the model equation                                  */
                   10623:       /* Tvarsel[k3]: Name of the variable at the k3th position in the result line.                                                  */
                   10624:       /* Tvalsel[k3]: Value of the variable at the k3th position in the result line.                                                 */
                   10625:       /* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline                   */
1.334     brouard  10626:       /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline                     */
1.332     brouard  10627:       /* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line                                        */
1.330     brouard  10628:       /* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line                                                      */
1.332     brouard  10629:       k3= resultmodel[nres][k1]; /* From position k1 in model get position k3 in result line */
                   10630:       /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   10631:       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  10632:       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  10633:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][Name]=Value; stores the value into the name of the variable. */
1.332     brouard  10634:       /* Tinvresult[nres][4]=1 */
1.334     brouard  10635:       /* Tresult[nres][k4+1]=Tvalsel[k3];/\* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) *\/ */
                   10636:       Tresult[nres][k3]=Tvalsel[k3];/* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) */
                   10637:       /* Tvresult[nres][k4+1]=(int)Tvarsel[k3];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   10638:       Tvresult[nres][k3]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
1.237     brouard  10639:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.334     brouard  10640:       precov[nres][k1]=Tvalsel[k3]; /* Value from resultline of the variable at the k1 position in the model */
1.332     brouard  10641:       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  10642:       k4++;;
1.331     brouard  10643:     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Quantitative and single */
1.330     brouard  10644:       /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 */
1.332     brouard  10645:       /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline                                 */
1.330     brouard  10646:       /* Tqinvresult[nres][Name of a quantitative variable]= value of the variable in the result line                                                      */
1.332     brouard  10647:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 5 =k3q */
                   10648:       k2q=(int)Tvarsel[k3q]; /*  Name of variable at k3q th position in the resultline */
                   10649:       /* Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  10650:       /* Tqresult[nres][k4q+1]=Tvalsel[k3q]; /\* Tqresult[nres][1]=25.1 *\/ */
                   10651:       /* Tvresult[nres][k4q+1]=(int)Tvarsel[k3q];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   10652:       /* Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /\* Tvqresult[nres][1]=5 *\/ */
                   10653:       Tqresult[nres][k3q]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   10654:       Tvresult[nres][k3q]=(int)Tvarsel[k3q];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   10655:       Tvqresult[nres][k3q]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
1.237     brouard  10656:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.330     brouard  10657:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.332     brouard  10658:       precov[nres][k1]=Tvalsel[k3q];
                   10659:       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  10660:       k4q++;;
1.331     brouard  10661:     }else if( Dummy[k1]==2 ){ /* For dummy with age product */
                   10662:       /* Tvar[k1]; */ /* Age variable */
1.332     brouard  10663:       /* Wrong we want the value of variable name Tvar[k1] */
                   10664:       
                   10665:       k3= resultmodel[nres][k1]; /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
1.331     brouard  10666:       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  10667:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][4]=1 */
1.332     brouard  10668:       precov[nres][k1]=Tvalsel[k3];
                   10669:       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  10670:     }else if( Dummy[k1]==3 ){ /* For quant with age product */
1.332     brouard  10671:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 25.1=k3q */
1.331     brouard  10672:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  10673:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* TinvDoQresult[nres][5]=25.1 */
1.332     brouard  10674:       precov[nres][k1]=Tvalsel[k3q];
1.334     brouard  10675:       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  10676:     }else if(Typevar[k1]==2 ){ /* For product quant or dummy (not with age) */
1.332     brouard  10677:       precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
                   10678:       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  10679:     }else{
1.332     brouard  10680:       printf("Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
                   10681:       fprintf(ficlog,"Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
1.235     brouard  10682:     }
                   10683:   }
1.234     brouard  10684:   
1.334     brouard  10685:   TKresult[nres]=++k; /* Number of combinations of dummies for the nresult and the model =Tvalsel[k3]*pow(2,k4) + 1*/
1.230     brouard  10686:   return (0);
                   10687: }
1.235     brouard  10688: 
1.230     brouard  10689: int decodemodel( char model[], int lastobs)
                   10690:  /**< This routine decodes the model and returns:
1.224     brouard  10691:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   10692:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   10693:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   10694:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   10695:        * - cptcovage number of covariates with age*products =2
                   10696:        * - cptcovs number of simple covariates
                   10697:        * - 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
                   10698:        *     which is a new column after the 9 (ncovcol) variables. 
1.319     brouard  10699:        * - if k is a product Vn*Vm, covar[k][i] is filled with correct values for each individual
1.224     brouard  10700:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   10701:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   10702:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   10703:        */
1.319     brouard  10704: /* 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  10705: {
1.238     brouard  10706:   int i, j, k, ks, v;
1.227     brouard  10707:   int  j1, k1, k2, k3, k4;
1.136     brouard  10708:   char modelsav[80];
1.145     brouard  10709:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  10710:   char *strpt;
1.136     brouard  10711: 
1.145     brouard  10712:   /*removespace(model);*/
1.136     brouard  10713:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  10714:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  10715:     if (strstr(model,"AGE") !=0){
1.192     brouard  10716:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   10717:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  10718:       return 1;
                   10719:     }
1.141     brouard  10720:     if (strstr(model,"v") !=0){
                   10721:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   10722:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   10723:       return 1;
                   10724:     }
1.187     brouard  10725:     strcpy(modelsav,model); 
                   10726:     if ((strpt=strstr(model,"age*age")) !=0){
                   10727:       printf(" strpt=%s, model=%s\n",strpt, model);
                   10728:       if(strpt != model){
1.234     brouard  10729:        printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  10730:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  10731:  corresponding column of parameters.\n",model);
1.234     brouard  10732:        fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  10733:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  10734:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  10735:        return 1;
1.225     brouard  10736:       }
1.187     brouard  10737:       nagesqr=1;
                   10738:       if (strstr(model,"+age*age") !=0)
1.234     brouard  10739:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  10740:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  10741:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  10742:       else 
1.234     brouard  10743:        substrchaine(modelsav, model, "age*age");
1.187     brouard  10744:     }else
                   10745:       nagesqr=0;
                   10746:     if (strlen(modelsav) >1){
                   10747:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   10748:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224     brouard  10749:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  10750:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  10751:                     * cst, age and age*age 
                   10752:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   10753:       /* including age products which are counted in cptcovage.
                   10754:        * but the covariates which are products must be treated 
                   10755:        * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  10756:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   10757:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.225     brouard  10758:       
                   10759:       
1.187     brouard  10760:       /*   Design
                   10761:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   10762:        *  <          ncovcol=8                >
                   10763:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   10764:        *   k=  1    2      3       4     5       6      7        8
                   10765:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   10766:        *  covar[k,i], value of kth covariate if not including age for individual i:
1.224     brouard  10767:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   10768:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  10769:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   10770:        *  Tage[++cptcovage]=k
                   10771:        *       if products, new covar are created after ncovcol with k1
                   10772:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   10773:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   10774:        *  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
                   10775:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   10776:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   10777:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   10778:        *  <          ncovcol=8                >
                   10779:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   10780:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   10781:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
1.319     brouard  10782:        * p Tvar[1]@12={2,   1,     3,      3,  11,     10,     8,       8,   7,   8,   5,  6}
1.187     brouard  10783:        * p Tprod[1]@2={                         6, 5}
                   10784:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   10785:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   10786:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1.319     brouard  10787:        *How to reorganize? Tvars(orted)
1.187     brouard  10788:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   10789:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   10790:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   10791:        * Struct []
                   10792:        */
1.225     brouard  10793:       
1.187     brouard  10794:       /* This loop fills the array Tvar from the string 'model'.*/
                   10795:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   10796:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   10797:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   10798:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   10799:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   10800:       /*       k=1 Tvar[1]=2 (from V2) */
                   10801:       /*       k=5 Tvar[5] */
                   10802:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  10803:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  10804:       /*       } */
1.198     brouard  10805:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  10806:       /*
                   10807:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  10808:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   10809:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   10810:       }
1.187     brouard  10811:       cptcovage=0;
1.319     brouard  10812:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model line */
                   10813:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' cutl from left to right
                   10814:                                         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" */
                   10815:        if (nbocc(modelsav,'+')==0)
                   10816:          strcpy(strb,modelsav); /* and analyzes it */
1.234     brouard  10817:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   10818:        /*scanf("%d",i);*/
1.319     brouard  10819:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V5*age+ V4+V3*age strb=V3*age */
                   10820:          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  10821:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   10822:            /* covar is not filled and then is empty */
                   10823:            cptcovprod--;
                   10824:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
1.319     brouard  10825:            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  10826:            Typevar[k]=1;  /* 1 for age product */
1.319     brouard  10827:            cptcovage++; /* Counts the number of covariates which include age as a product */
                   10828:            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  10829:            /*printf("stre=%s ", stre);*/
                   10830:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   10831:            cptcovprod--;
                   10832:            cutl(stre,strb,strc,'V');
                   10833:            Tvar[k]=atoi(stre);
                   10834:            Typevar[k]=1;  /* 1 for age product */
                   10835:            cptcovage++;
                   10836:            Tage[cptcovage]=k;
                   10837:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   10838:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   10839:            cptcovn++;
                   10840:            cptcovprodnoage++;k1++;
                   10841:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   10842:            Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* For model-covariate k tells which data-covariate to use but
                   10843:                                                because this model-covariate is a construction we invent a new column
                   10844:                                                which is after existing variables ncovcol+nqv+ntv+nqtv + k1
1.335     brouard  10845:                                                If already ncovcol=4 and model= V2 + V1 + V1*V4 + age*V3 + V3*V2
1.319     brouard  10846:                                                thus after V4 we invent V5 and V6 because age*V3 will be computed in 4
                   10847:                                                Tvar[3=V1*V4]=4+1=5 Tvar[5=V3*V2]=4 + 2= 6, Tvar[4=age*V3]=4 etc */
1.335     brouard  10848:            /* Please remark that the new variables are model dependent */
                   10849:            /* If we have 4 variable but the model uses only 3, like in
                   10850:             * model= V1 + age*V1 + V2 + V3 + age*V2 + age*V3 + V1*V2 + V1*V3
                   10851:             *  k=     1     2       3   4     5        6        7       8
                   10852:             * Tvar[k]=1     1       2   3     2        3       (5       6) (and not 4 5 because of V4 missing)
                   10853:             * Tage[kk]    [1]= 2           [2]=5      [3]=6                  kk=1 to cptcovage=3
                   10854:             * Tvar[Tage[kk]][1]=2          [2]=2      [3]=3
                   10855:             */
1.234     brouard  10856:            Typevar[k]=2;  /* 2 for double fixed dummy covariates */
                   10857:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   10858:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
1.319     brouard  10859:            Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 */
1.234     brouard  10860:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
1.330     brouard  10861:            Tvardk[k][1] =atoi(strc); /* m 1 for V1*/
1.234     brouard  10862:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
1.330     brouard  10863:            Tvardk[k][2] =atoi(stre); /* n 4 for V4*/
1.234     brouard  10864:            k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   10865:            /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   10866:            /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
1.225     brouard  10867:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
1.234     brouard  10868:            /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   10869:            for (i=1; i<=lastobs;i++){
                   10870:              /* Computes the new covariate which is a product of
                   10871:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   10872:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   10873:            }
                   10874:          } /* End age is not in the model */
                   10875:        } /* End if model includes a product */
1.319     brouard  10876:        else { /* not a product */
1.234     brouard  10877:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   10878:          /*  scanf("%d",i);*/
                   10879:          cutl(strd,strc,strb,'V');
                   10880:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   10881:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   10882:          Tvar[k]=atoi(strd);
                   10883:          Typevar[k]=0;  /* 0 for simple covariates */
                   10884:        }
                   10885:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  10886:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  10887:                                  scanf("%d",i);*/
1.187     brouard  10888:       } /* end of loop + on total covariates */
                   10889:     } /* end if strlen(modelsave == 0) age*age might exist */
                   10890:   } /* end if strlen(model == 0) */
1.136     brouard  10891:   
                   10892:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   10893:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  10894:   
1.136     brouard  10895:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  10896:      printf("cptcovprod=%d ", cptcovprod);
                   10897:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   10898:      scanf("%d ",i);*/
                   10899: 
                   10900: 
1.230     brouard  10901: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   10902:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  10903: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   10904:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   10905:    k =           1    2   3     4       5       6      7      8        9
                   10906:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
1.319     brouard  10907:    Typevar[k]=   0    0   0     2       1       0      2      1        0
1.227     brouard  10908:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   10909:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   10910:          Tmodelind[combination of covar]=k;
1.225     brouard  10911: */  
                   10912: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  10913:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  10914:   /* 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  10915:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.318     brouard  10916:   printf("Model=1+age+%s\n\
1.227     brouard  10917: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   10918: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   10919: 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  10920:   fprintf(ficlog,"Model=1+age+%s\n\
1.227     brouard  10921: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   10922: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   10923: 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  10924:   for(k=-1;k<=cptcovt; k++){ Fixed[k]=0; Dummy[k]=0;}
1.234     brouard  10925:   for(k=1, ncovf=0, nsd=0, nsq=0, ncovv=0, ncova=0, ncoveff=0, nqfveff=0, ntveff=0, nqtveff=0;k<=cptcovt; k++){ /* or cptocvt */
                   10926:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  10927:       Fixed[k]= 0;
                   10928:       Dummy[k]= 0;
1.225     brouard  10929:       ncoveff++;
1.232     brouard  10930:       ncovf++;
1.234     brouard  10931:       nsd++;
                   10932:       modell[k].maintype= FTYPE;
                   10933:       TvarsD[nsd]=Tvar[k];
                   10934:       TvarsDind[nsd]=k;
1.330     brouard  10935:       TnsdVar[Tvar[k]]=nsd;
1.234     brouard  10936:       TvarF[ncovf]=Tvar[k];
                   10937:       TvarFind[ncovf]=k;
                   10938:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   10939:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   10940:     }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /* Product of fixed dummy (<=ncovcol) covariates */
                   10941:       Fixed[k]= 0;
                   10942:       Dummy[k]= 0;
                   10943:       ncoveff++;
                   10944:       ncovf++;
                   10945:       modell[k].maintype= FTYPE;
                   10946:       TvarF[ncovf]=Tvar[k];
1.330     brouard  10947:       /* TnsdVar[Tvar[k]]=nsd; */ /* To be done */
1.234     brouard  10948:       TvarFind[ncovf]=k;
1.230     brouard  10949:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  10950:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.240     brouard  10951:     }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  10952:       Fixed[k]= 0;
                   10953:       Dummy[k]= 1;
1.230     brouard  10954:       nqfveff++;
1.234     brouard  10955:       modell[k].maintype= FTYPE;
                   10956:       modell[k].subtype= FQ;
                   10957:       nsq++;
1.334     brouard  10958:       TvarsQ[nsq]=Tvar[k]; /* Gives the variable name (extended to products) of first nsq simple quantitative covariates (fixed or time vary see below */
                   10959:       TvarsQind[nsq]=k;    /* Gives the position in the model equation of the first nsq simple quantitative covariates (fixed or time vary) */
1.232     brouard  10960:       ncovf++;
1.234     brouard  10961:       TvarF[ncovf]=Tvar[k];
                   10962:       TvarFind[ncovf]=k;
1.231     brouard  10963:       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  10964:       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  10965:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.227     brouard  10966:       Fixed[k]= 1;
                   10967:       Dummy[k]= 0;
1.225     brouard  10968:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  10969:       modell[k].maintype= VTYPE;
                   10970:       modell[k].subtype= VD;
                   10971:       nsd++;
                   10972:       TvarsD[nsd]=Tvar[k];
                   10973:       TvarsDind[nsd]=k;
1.330     brouard  10974:       TnsdVar[Tvar[k]]=nsd; /* To be verified */
1.234     brouard  10975:       ncovv++; /* Only simple time varying variables */
                   10976:       TvarV[ncovv]=Tvar[k];
1.242     brouard  10977:       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  10978:       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 */
                   10979:       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  10980:       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);
                   10981:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  10982:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.234     brouard  10983:       Fixed[k]= 1;
                   10984:       Dummy[k]= 1;
                   10985:       nqtveff++;
                   10986:       modell[k].maintype= VTYPE;
                   10987:       modell[k].subtype= VQ;
                   10988:       ncovv++; /* Only simple time varying variables */
                   10989:       nsq++;
1.334     brouard  10990:       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) */
                   10991:       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  10992:       TvarV[ncovv]=Tvar[k];
1.242     brouard  10993:       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  10994:       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 */
                   10995:       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  10996:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   10997:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
                   10998:       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  10999:       printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv);
1.227     brouard  11000:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  11001:       ncova++;
                   11002:       TvarA[ncova]=Tvar[k];
                   11003:       TvarAind[ncova]=k;
1.231     brouard  11004:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  11005:        Fixed[k]= 2;
                   11006:        Dummy[k]= 2;
                   11007:        modell[k].maintype= ATYPE;
                   11008:        modell[k].subtype= APFD;
                   11009:        /* ncoveff++; */
1.227     brouard  11010:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  11011:        Fixed[k]= 2;
                   11012:        Dummy[k]= 3;
                   11013:        modell[k].maintype= ATYPE;
                   11014:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   11015:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  11016:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  11017:        Fixed[k]= 3;
                   11018:        Dummy[k]= 2;
                   11019:        modell[k].maintype= ATYPE;
                   11020:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   11021:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  11022:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  11023:        Fixed[k]= 3;
                   11024:        Dummy[k]= 3;
                   11025:        modell[k].maintype= ATYPE;
                   11026:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   11027:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  11028:       }
                   11029:     }else if (Typevar[k] == 2) {  /* product without age */
                   11030:       k1=Tposprod[k];
                   11031:       if(Tvard[k1][1] <=ncovcol){
1.240     brouard  11032:        if(Tvard[k1][2] <=ncovcol){
                   11033:          Fixed[k]= 1;
                   11034:          Dummy[k]= 0;
                   11035:          modell[k].maintype= FTYPE;
                   11036:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
                   11037:          ncovf++; /* Fixed variables without age */
                   11038:          TvarF[ncovf]=Tvar[k];
                   11039:          TvarFind[ncovf]=k;
                   11040:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   11041:          Fixed[k]= 0;  /* or 2 ?*/
                   11042:          Dummy[k]= 1;
                   11043:          modell[k].maintype= FTYPE;
                   11044:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
                   11045:          ncovf++; /* Varying variables without age */
                   11046:          TvarF[ncovf]=Tvar[k];
                   11047:          TvarFind[ncovf]=k;
                   11048:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   11049:          Fixed[k]= 1;
                   11050:          Dummy[k]= 0;
                   11051:          modell[k].maintype= VTYPE;
                   11052:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
                   11053:          ncovv++; /* Varying variables without age */
                   11054:          TvarV[ncovv]=Tvar[k];
                   11055:          TvarVind[ncovv]=k;
                   11056:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   11057:          Fixed[k]= 1;
                   11058:          Dummy[k]= 1;
                   11059:          modell[k].maintype= VTYPE;
                   11060:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
                   11061:          ncovv++; /* Varying variables without age */
                   11062:          TvarV[ncovv]=Tvar[k];
                   11063:          TvarVind[ncovv]=k;
                   11064:        }
1.227     brouard  11065:       }else if(Tvard[k1][1] <=ncovcol+nqv){
1.240     brouard  11066:        if(Tvard[k1][2] <=ncovcol){
                   11067:          Fixed[k]= 0;  /* or 2 ?*/
                   11068:          Dummy[k]= 1;
                   11069:          modell[k].maintype= FTYPE;
                   11070:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
                   11071:          ncovf++; /* Fixed variables without age */
                   11072:          TvarF[ncovf]=Tvar[k];
                   11073:          TvarFind[ncovf]=k;
                   11074:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   11075:          Fixed[k]= 1;
                   11076:          Dummy[k]= 1;
                   11077:          modell[k].maintype= VTYPE;
                   11078:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
                   11079:          ncovv++; /* Varying variables without age */
                   11080:          TvarV[ncovv]=Tvar[k];
                   11081:          TvarVind[ncovv]=k;
                   11082:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   11083:          Fixed[k]= 1;
                   11084:          Dummy[k]= 1;
                   11085:          modell[k].maintype= VTYPE;
                   11086:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
                   11087:          ncovv++; /* Varying variables without age */
                   11088:          TvarV[ncovv]=Tvar[k];
                   11089:          TvarVind[ncovv]=k;
                   11090:          ncovv++; /* Varying variables without age */
                   11091:          TvarV[ncovv]=Tvar[k];
                   11092:          TvarVind[ncovv]=k;
                   11093:        }
1.227     brouard  11094:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){
1.240     brouard  11095:        if(Tvard[k1][2] <=ncovcol){
                   11096:          Fixed[k]= 1;
                   11097:          Dummy[k]= 1;
                   11098:          modell[k].maintype= VTYPE;
                   11099:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
                   11100:          ncovv++; /* Varying variables without age */
                   11101:          TvarV[ncovv]=Tvar[k];
                   11102:          TvarVind[ncovv]=k;
                   11103:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   11104:          Fixed[k]= 1;
                   11105:          Dummy[k]= 1;
                   11106:          modell[k].maintype= VTYPE;
                   11107:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
                   11108:          ncovv++; /* Varying variables without age */
                   11109:          TvarV[ncovv]=Tvar[k];
                   11110:          TvarVind[ncovv]=k;
                   11111:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   11112:          Fixed[k]= 1;
                   11113:          Dummy[k]= 0;
                   11114:          modell[k].maintype= VTYPE;
                   11115:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
                   11116:          ncovv++; /* Varying variables without age */
                   11117:          TvarV[ncovv]=Tvar[k];
                   11118:          TvarVind[ncovv]=k;
                   11119:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   11120:          Fixed[k]= 1;
                   11121:          Dummy[k]= 1;
                   11122:          modell[k].maintype= VTYPE;
                   11123:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
                   11124:          ncovv++; /* Varying variables without age */
                   11125:          TvarV[ncovv]=Tvar[k];
                   11126:          TvarVind[ncovv]=k;
                   11127:        }
1.227     brouard  11128:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  11129:        if(Tvard[k1][2] <=ncovcol){
                   11130:          Fixed[k]= 1;
                   11131:          Dummy[k]= 1;
                   11132:          modell[k].maintype= VTYPE;
                   11133:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
                   11134:          ncovv++; /* Varying variables without age */
                   11135:          TvarV[ncovv]=Tvar[k];
                   11136:          TvarVind[ncovv]=k;
                   11137:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   11138:          Fixed[k]= 1;
                   11139:          Dummy[k]= 1;
                   11140:          modell[k].maintype= VTYPE;
                   11141:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
                   11142:          ncovv++; /* Varying variables without age */
                   11143:          TvarV[ncovv]=Tvar[k];
                   11144:          TvarVind[ncovv]=k;
                   11145:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   11146:          Fixed[k]= 1;
                   11147:          Dummy[k]= 1;
                   11148:          modell[k].maintype= VTYPE;
                   11149:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
                   11150:          ncovv++; /* Varying variables without age */
                   11151:          TvarV[ncovv]=Tvar[k];
                   11152:          TvarVind[ncovv]=k;
                   11153:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   11154:          Fixed[k]= 1;
                   11155:          Dummy[k]= 1;
                   11156:          modell[k].maintype= VTYPE;
                   11157:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
                   11158:          ncovv++; /* Varying variables without age */
                   11159:          TvarV[ncovv]=Tvar[k];
                   11160:          TvarVind[ncovv]=k;
                   11161:        }
1.227     brouard  11162:       }else{
1.240     brouard  11163:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   11164:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   11165:       } /*end k1*/
1.225     brouard  11166:     }else{
1.226     brouard  11167:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   11168:       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  11169:     }
1.227     brouard  11170:     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  11171:     printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype);
1.227     brouard  11172:     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]);
                   11173:   }
                   11174:   /* Searching for doublons in the model */
                   11175:   for(k1=1; k1<= cptcovt;k1++){
                   11176:     for(k2=1; k2 <k1;k2++){
1.285     brouard  11177:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   11178:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  11179:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   11180:          if(Tvar[k1]==Tvar[k2]){
1.285     brouard  11181:            printf("Error duplication in the model=%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]);
                   11182:            fprintf(ficlog,"Error duplication in the model=%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  11183:            return(1);
                   11184:          }
                   11185:        }else if (Typevar[k1] ==2){
                   11186:          k3=Tposprod[k1];
                   11187:          k4=Tposprod[k2];
                   11188:          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])) ){
                   11189:            printf("Error duplication in the model=%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]]);
                   11190:            fprintf(ficlog,"Error duplication in the model=%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);
                   11191:            return(1);
                   11192:          }
                   11193:        }
1.227     brouard  11194:       }
                   11195:     }
1.225     brouard  11196:   }
                   11197:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   11198:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  11199:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   11200:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.137     brouard  11201:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  11202:   /*endread:*/
1.225     brouard  11203:   printf("Exiting decodemodel: ");
                   11204:   return (1);
1.136     brouard  11205: }
                   11206: 
1.169     brouard  11207: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  11208: {/* Check ages at death */
1.136     brouard  11209:   int i, m;
1.218     brouard  11210:   int firstone=0;
                   11211:   
1.136     brouard  11212:   for (i=1; i<=imx; i++) {
                   11213:     for(m=2; (m<= maxwav); m++) {
                   11214:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   11215:        anint[m][i]=9999;
1.216     brouard  11216:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   11217:          s[m][i]=-1;
1.136     brouard  11218:       }
                   11219:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  11220:        *nberr = *nberr + 1;
1.218     brouard  11221:        if(firstone == 0){
                   11222:          firstone=1;
1.260     brouard  11223:        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  11224:        }
1.262     brouard  11225:        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  11226:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  11227:       }
                   11228:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  11229:        (*nberr)++;
1.259     brouard  11230:        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  11231:        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  11232:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  11233:       }
                   11234:     }
                   11235:   }
                   11236: 
                   11237:   for (i=1; i<=imx; i++)  {
                   11238:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   11239:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  11240:       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  11241:        if (s[m][i] >= nlstate+1) {
1.169     brouard  11242:          if(agedc[i]>0){
                   11243:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  11244:              agev[m][i]=agedc[i];
1.214     brouard  11245:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  11246:            }else {
1.136     brouard  11247:              if ((int)andc[i]!=9999){
                   11248:                nbwarn++;
                   11249:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   11250:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   11251:                agev[m][i]=-1;
                   11252:              }
                   11253:            }
1.169     brouard  11254:          } /* agedc > 0 */
1.214     brouard  11255:        } /* end if */
1.136     brouard  11256:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   11257:                                 years but with the precision of a month */
                   11258:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   11259:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   11260:            agev[m][i]=1;
                   11261:          else if(agev[m][i] < *agemin){ 
                   11262:            *agemin=agev[m][i];
                   11263:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   11264:          }
                   11265:          else if(agev[m][i] >*agemax){
                   11266:            *agemax=agev[m][i];
1.156     brouard  11267:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  11268:          }
                   11269:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   11270:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  11271:        } /* en if 9*/
1.136     brouard  11272:        else { /* =9 */
1.214     brouard  11273:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  11274:          agev[m][i]=1;
                   11275:          s[m][i]=-1;
                   11276:        }
                   11277:       }
1.214     brouard  11278:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  11279:        agev[m][i]=1;
1.214     brouard  11280:       else{
                   11281:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   11282:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   11283:        agev[m][i]=0;
                   11284:       }
                   11285:     } /* End for lastpass */
                   11286:   }
1.136     brouard  11287:     
                   11288:   for (i=1; i<=imx; i++)  {
                   11289:     for(m=firstpass; (m<=lastpass); m++){
                   11290:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  11291:        (*nberr)++;
1.136     brouard  11292:        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);     
                   11293:        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);     
                   11294:        return 1;
                   11295:       }
                   11296:     }
                   11297:   }
                   11298: 
                   11299:   /*for (i=1; i<=imx; i++){
                   11300:   for (m=firstpass; (m<lastpass); m++){
                   11301:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   11302: }
                   11303: 
                   11304: }*/
                   11305: 
                   11306: 
1.139     brouard  11307:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   11308:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  11309: 
                   11310:   return (0);
1.164     brouard  11311:  /* endread:*/
1.136     brouard  11312:     printf("Exiting calandcheckages: ");
                   11313:     return (1);
                   11314: }
                   11315: 
1.172     brouard  11316: #if defined(_MSC_VER)
                   11317: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   11318: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   11319: //#include "stdafx.h"
                   11320: //#include <stdio.h>
                   11321: //#include <tchar.h>
                   11322: //#include <windows.h>
                   11323: //#include <iostream>
                   11324: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   11325: 
                   11326: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   11327: 
                   11328: BOOL IsWow64()
                   11329: {
                   11330:        BOOL bIsWow64 = FALSE;
                   11331: 
                   11332:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   11333:        //  (HANDLE, PBOOL);
                   11334: 
                   11335:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   11336: 
                   11337:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   11338:        const char funcName[] = "IsWow64Process";
                   11339:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   11340:                GetProcAddress(module, funcName);
                   11341: 
                   11342:        if (NULL != fnIsWow64Process)
                   11343:        {
                   11344:                if (!fnIsWow64Process(GetCurrentProcess(),
                   11345:                        &bIsWow64))
                   11346:                        //throw std::exception("Unknown error");
                   11347:                        printf("Unknown error\n");
                   11348:        }
                   11349:        return bIsWow64 != FALSE;
                   11350: }
                   11351: #endif
1.177     brouard  11352: 
1.191     brouard  11353: void syscompilerinfo(int logged)
1.292     brouard  11354: {
                   11355: #include <stdint.h>
                   11356: 
                   11357:   /* #include "syscompilerinfo.h"*/
1.185     brouard  11358:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   11359:    /* /GS /W3 /Gy
                   11360:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   11361:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   11362:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  11363:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   11364:    */ 
                   11365:    /* 64 bits */
1.185     brouard  11366:    /*
                   11367:      /GS /W3 /Gy
                   11368:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   11369:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   11370:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   11371:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   11372:    /* Optimization are useless and O3 is slower than O2 */
                   11373:    /*
                   11374:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   11375:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   11376:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   11377:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   11378:    */
1.186     brouard  11379:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  11380:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   11381:       /PDB:"visual studio
                   11382:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   11383:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   11384:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   11385:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   11386:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   11387:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   11388:       uiAccess='false'"
                   11389:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   11390:       /NOLOGO /TLBID:1
                   11391:    */
1.292     brouard  11392: 
                   11393: 
1.177     brouard  11394: #if defined __INTEL_COMPILER
1.178     brouard  11395: #if defined(__GNUC__)
                   11396:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   11397: #endif
1.177     brouard  11398: #elif defined(__GNUC__) 
1.179     brouard  11399: #ifndef  __APPLE__
1.174     brouard  11400: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  11401: #endif
1.177     brouard  11402:    struct utsname sysInfo;
1.178     brouard  11403:    int cross = CROSS;
                   11404:    if (cross){
                   11405:           printf("Cross-");
1.191     brouard  11406:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  11407:    }
1.174     brouard  11408: #endif
                   11409: 
1.191     brouard  11410:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  11411: #if defined(__clang__)
1.191     brouard  11412:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  11413: #endif
                   11414: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  11415:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  11416: #endif
                   11417: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  11418:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  11419: #endif
                   11420: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  11421:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  11422: #endif
                   11423: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  11424:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  11425: #endif
                   11426: #if defined(_MSC_VER)
1.191     brouard  11427:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  11428: #endif
                   11429: #if defined(__PGI)
1.191     brouard  11430:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  11431: #endif
                   11432: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  11433:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  11434: #endif
1.191     brouard  11435:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  11436:    
1.167     brouard  11437: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   11438: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   11439:     // Windows (x64 and x86)
1.191     brouard  11440:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  11441: #elif __unix__ // all unices, not all compilers
                   11442:     // Unix
1.191     brouard  11443:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  11444: #elif __linux__
                   11445:     // linux
1.191     brouard  11446:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  11447: #elif __APPLE__
1.174     brouard  11448:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  11449:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  11450: #endif
                   11451: 
                   11452: /*  __MINGW32__          */
                   11453: /*  __CYGWIN__  */
                   11454: /* __MINGW64__  */
                   11455: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   11456: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   11457: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   11458: /* _WIN64  // Defined for applications for Win64. */
                   11459: /* _M_X64 // Defined for compilations that target x64 processors. */
                   11460: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  11461: 
1.167     brouard  11462: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  11463:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  11464: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  11465:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  11466: #else
1.191     brouard  11467:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  11468: #endif
                   11469: 
1.169     brouard  11470: #if defined(__GNUC__)
                   11471: # if defined(__GNUC_PATCHLEVEL__)
                   11472: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   11473:                             + __GNUC_MINOR__ * 100 \
                   11474:                             + __GNUC_PATCHLEVEL__)
                   11475: # else
                   11476: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   11477:                             + __GNUC_MINOR__ * 100)
                   11478: # endif
1.174     brouard  11479:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  11480:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  11481: 
                   11482:    if (uname(&sysInfo) != -1) {
                   11483:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  11484:         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  11485:    }
                   11486:    else
                   11487:       perror("uname() error");
1.179     brouard  11488:    //#ifndef __INTEL_COMPILER 
                   11489: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  11490:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  11491:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  11492: #endif
1.169     brouard  11493: #endif
1.172     brouard  11494: 
1.286     brouard  11495:    //   void main ()
1.172     brouard  11496:    //   {
1.169     brouard  11497: #if defined(_MSC_VER)
1.174     brouard  11498:    if (IsWow64()){
1.191     brouard  11499:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   11500:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  11501:    }
                   11502:    else{
1.191     brouard  11503:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   11504:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  11505:    }
1.172     brouard  11506:    //     printf("\nPress Enter to continue...");
                   11507:    //     getchar();
                   11508:    //   }
                   11509: 
1.169     brouard  11510: #endif
                   11511:    
1.167     brouard  11512: 
1.219     brouard  11513: }
1.136     brouard  11514: 
1.219     brouard  11515: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  11516:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.332     brouard  11517:   /* Computes the prevalence limit for each combination of the dummy covariates */
1.235     brouard  11518:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  11519:   /* double ftolpl = 1.e-10; */
1.180     brouard  11520:   double age, agebase, agelim;
1.203     brouard  11521:   double tot;
1.180     brouard  11522: 
1.202     brouard  11523:   strcpy(filerespl,"PL_");
                   11524:   strcat(filerespl,fileresu);
                   11525:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  11526:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   11527:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  11528:   }
1.288     brouard  11529:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   11530:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  11531:   pstamp(ficrespl);
1.288     brouard  11532:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  11533:   fprintf(ficrespl,"#Age ");
                   11534:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   11535:   fprintf(ficrespl,"\n");
1.180     brouard  11536:   
1.219     brouard  11537:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  11538: 
1.219     brouard  11539:   agebase=ageminpar;
                   11540:   agelim=agemaxpar;
1.180     brouard  11541: 
1.227     brouard  11542:   /* i1=pow(2,ncoveff); */
1.234     brouard  11543:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  11544:   if (cptcovn < 1){i1=1;}
1.180     brouard  11545: 
1.337   ! brouard  11546:   /* for(k=1; k<=i1;k++){ /\* For each combination k of dummy covariates in the model *\/ */
1.238     brouard  11547:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337   ! brouard  11548:       k=TKresult[nres];
        !          11549:       /* if(i1 != 1 && TKresult[nres]!= k) /\* We found the combination k corresponding to the resultline value of dummies *\/ */
        !          11550:       /*       continue; */
1.235     brouard  11551: 
1.238     brouard  11552:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11553:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   11554:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   11555:       /* k=k+1; */
                   11556:       /* to clean */
1.332     brouard  11557:       /*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*/
1.238     brouard  11558:       fprintf(ficrespl,"#******");
                   11559:       printf("#******");
                   11560:       fprintf(ficlog,"#******");
1.337   ! brouard  11561:       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  11562:        /* fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Here problem for varying dummy*\/ */
1.337   ! brouard  11563:        /* printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
        !          11564:        /* fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
        !          11565:        fprintf(ficrespl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
        !          11566:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
        !          11567:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
        !          11568:       }
        !          11569:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
        !          11570:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
        !          11571:       /*       fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
        !          11572:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
        !          11573:       /* } */
1.238     brouard  11574:       fprintf(ficrespl,"******\n");
                   11575:       printf("******\n");
                   11576:       fprintf(ficlog,"******\n");
                   11577:       if(invalidvarcomb[k]){
                   11578:        printf("\nCombination (%d) ignored because no case \n",k); 
                   11579:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   11580:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   11581:        continue;
                   11582:       }
1.219     brouard  11583: 
1.238     brouard  11584:       fprintf(ficrespl,"#Age ");
1.337   ! brouard  11585:       /* for(j=1;j<=cptcoveff;j++) { */
        !          11586:       /*       fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
        !          11587:       /* } */
        !          11588:       for(j=1;j<=cptcovs;j++) { /* New the quanti variable is added */
        !          11589:        fprintf(ficrespl,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  11590:       }
                   11591:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   11592:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  11593:     
1.238     brouard  11594:       for (age=agebase; age<=agelim; age++){
                   11595:        /* for (age=agebase; age<=agebase; age++){ */
1.337   ! brouard  11596:        /**< Computes the prevalence limit in each live state at age x and for covariate combination (k and) nres */
        !          11597:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres); /* Nicely done */
1.238     brouard  11598:        fprintf(ficrespl,"%.0f ",age );
1.337   ! brouard  11599:        /* for(j=1;j<=cptcoveff;j++) */
        !          11600:        /*   fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
        !          11601:        for(j=1;j<=cptcovs;j++)
        !          11602:          fprintf(ficrespl,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  11603:        tot=0.;
                   11604:        for(i=1; i<=nlstate;i++){
                   11605:          tot +=  prlim[i][i];
                   11606:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   11607:        }
                   11608:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   11609:       } /* Age */
                   11610:       /* was end of cptcod */
1.337   ! brouard  11611:     } /* nres */
        !          11612:   /* } /\* for each combination *\/ */
1.219     brouard  11613:   return 0;
1.180     brouard  11614: }
                   11615: 
1.218     brouard  11616: 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  11617:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  11618:        
                   11619:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   11620:    * at any age between ageminpar and agemaxpar
                   11621:         */
1.235     brouard  11622:   int i, j, k, i1, nres=0 ;
1.217     brouard  11623:   /* double ftolpl = 1.e-10; */
                   11624:   double age, agebase, agelim;
                   11625:   double tot;
1.218     brouard  11626:   /* double ***mobaverage; */
                   11627:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  11628: 
                   11629:   strcpy(fileresplb,"PLB_");
                   11630:   strcat(fileresplb,fileresu);
                   11631:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  11632:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   11633:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  11634:   }
1.288     brouard  11635:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   11636:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  11637:   pstamp(ficresplb);
1.288     brouard  11638:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  11639:   fprintf(ficresplb,"#Age ");
                   11640:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   11641:   fprintf(ficresplb,"\n");
                   11642:   
1.218     brouard  11643:   
                   11644:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   11645:   
                   11646:   agebase=ageminpar;
                   11647:   agelim=agemaxpar;
                   11648:   
                   11649:   
1.227     brouard  11650:   i1=pow(2,cptcoveff);
1.218     brouard  11651:   if (cptcovn < 1){i1=1;}
1.227     brouard  11652:   
1.238     brouard  11653:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11654:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  11655:      if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  11656:        continue;
1.332     brouard  11657:      /*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*/
1.238     brouard  11658:       fprintf(ficresplb,"#******");
                   11659:       printf("#******");
                   11660:       fprintf(ficlog,"#******");
                   11661:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
1.332     brouard  11662:        fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   11663:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   11664:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.238     brouard  11665:       }
                   11666:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  11667:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
                   11668:        fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
                   11669:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
1.238     brouard  11670:       }
                   11671:       fprintf(ficresplb,"******\n");
                   11672:       printf("******\n");
                   11673:       fprintf(ficlog,"******\n");
                   11674:       if(invalidvarcomb[k]){
                   11675:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   11676:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   11677:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   11678:        continue;
                   11679:       }
1.218     brouard  11680:     
1.238     brouard  11681:       fprintf(ficresplb,"#Age ");
                   11682:       for(j=1;j<=cptcoveff;j++) {
1.332     brouard  11683:        fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.238     brouard  11684:       }
                   11685:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   11686:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  11687:     
                   11688:     
1.238     brouard  11689:       for (age=agebase; age<=agelim; age++){
                   11690:        /* for (age=agebase; age<=agebase; age++){ */
                   11691:        if(mobilavproj > 0){
                   11692:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   11693:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  11694:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  11695:        }else if (mobilavproj == 0){
                   11696:          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);
                   11697:          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);
                   11698:          exit(1);
                   11699:        }else{
                   11700:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  11701:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  11702:          /* printf("TOTOT\n"); */
                   11703:           /* exit(1); */
1.238     brouard  11704:        }
                   11705:        fprintf(ficresplb,"%.0f ",age );
                   11706:        for(j=1;j<=cptcoveff;j++)
1.332     brouard  11707:          fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.238     brouard  11708:        tot=0.;
                   11709:        for(i=1; i<=nlstate;i++){
                   11710:          tot +=  bprlim[i][i];
                   11711:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   11712:        }
                   11713:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   11714:       } /* Age */
                   11715:       /* was end of cptcod */
1.255     brouard  11716:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.238     brouard  11717:     } /* end of any combination */
                   11718:   } /* end of nres */  
1.218     brouard  11719:   /* hBijx(p, bage, fage); */
                   11720:   /* fclose(ficrespijb); */
                   11721:   
                   11722:   return 0;
1.217     brouard  11723: }
1.218     brouard  11724:  
1.180     brouard  11725: int hPijx(double *p, int bage, int fage){
                   11726:     /*------------- h Pij x at various ages ------------*/
1.336     brouard  11727:   /* to be optimized with precov */
1.180     brouard  11728:   int stepsize;
                   11729:   int agelim;
                   11730:   int hstepm;
                   11731:   int nhstepm;
1.235     brouard  11732:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  11733: 
                   11734:   double agedeb;
                   11735:   double ***p3mat;
                   11736: 
1.337   ! brouard  11737:   strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
        !          11738:   if((ficrespij=fopen(filerespij,"w"))==NULL) {
        !          11739:     printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
        !          11740:     fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
        !          11741:   }
        !          11742:   printf("Computing pij: result on file '%s' \n", filerespij);
        !          11743:   fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
        !          11744:   
        !          11745:   stepsize=(int) (stepm+YEARM-1)/YEARM;
        !          11746:   /*if (stepm<=24) stepsize=2;*/
        !          11747:   
        !          11748:   agelim=AGESUP;
        !          11749:   hstepm=stepsize*YEARM; /* Every year of age */
        !          11750:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
        !          11751:   
        !          11752:   /* hstepm=1;   aff par mois*/
        !          11753:   pstamp(ficrespij);
        !          11754:   fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
        !          11755:   i1= pow(2,cptcoveff);
        !          11756:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
        !          11757:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
        !          11758:   /*   k=k+1;  */
        !          11759:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
        !          11760:     k=TKresult[nres];
        !          11761:     /* for(k=1; k<=i1;k++){ */
        !          11762:     /* if(i1 != 1 && TKresult[nres]!= k) */
        !          11763:     /*         continue; */
        !          11764:     fprintf(ficrespij,"\n#****** ");
        !          11765:     for(j=1;j<=cptcovs;j++){
        !          11766:       fprintf(ficrespij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
        !          11767:       /* fprintf(ficrespij,"@wV%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
        !          11768:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
        !          11769:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
        !          11770:       /*       fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
        !          11771:     }
        !          11772:     fprintf(ficrespij,"******\n");
        !          11773:     
        !          11774:     for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
        !          11775:       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
        !          11776:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
        !          11777:       
        !          11778:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
        !          11779:       
        !          11780:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
        !          11781:       oldm=oldms;savm=savms;
        !          11782:       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
        !          11783:       fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
        !          11784:       for(i=1; i<=nlstate;i++)
        !          11785:        for(j=1; j<=nlstate+ndeath;j++)
        !          11786:          fprintf(ficrespij," %1d-%1d",i,j);
        !          11787:       fprintf(ficrespij,"\n");
        !          11788:       for (h=0; h<=nhstepm; h++){
        !          11789:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
        !          11790:        fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.183     brouard  11791:        for(i=1; i<=nlstate;i++)
                   11792:          for(j=1; j<=nlstate+ndeath;j++)
1.337   ! brouard  11793:            fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.183     brouard  11794:        fprintf(ficrespij,"\n");
                   11795:       }
1.337   ! brouard  11796:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
        !          11797:       fprintf(ficrespij,"\n");
1.180     brouard  11798:     }
1.337   ! brouard  11799:   }
        !          11800:   /*}*/
        !          11801:   return 0;
1.180     brouard  11802: }
1.218     brouard  11803:  
                   11804:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  11805:     /*------------- h Bij x at various ages ------------*/
1.336     brouard  11806:     /* To be optimized with precov */
1.217     brouard  11807:   int stepsize;
1.218     brouard  11808:   /* int agelim; */
                   11809:        int ageminl;
1.217     brouard  11810:   int hstepm;
                   11811:   int nhstepm;
1.238     brouard  11812:   int h, i, i1, j, k, nres;
1.218     brouard  11813:        
1.217     brouard  11814:   double agedeb;
                   11815:   double ***p3mat;
1.218     brouard  11816:        
                   11817:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   11818:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   11819:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   11820:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   11821:   }
                   11822:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   11823:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   11824:   
                   11825:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   11826:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  11827:   
1.218     brouard  11828:   /* agelim=AGESUP; */
1.289     brouard  11829:   ageminl=AGEINF; /* was 30 */
1.218     brouard  11830:   hstepm=stepsize*YEARM; /* Every year of age */
                   11831:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   11832:   
                   11833:   /* hstepm=1;   aff par mois*/
                   11834:   pstamp(ficrespijb);
1.255     brouard  11835:   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  11836:   i1= pow(2,cptcoveff);
1.218     brouard  11837:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11838:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   11839:   /*   k=k+1;  */
1.238     brouard  11840:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337   ! brouard  11841:     k=TKresult[nres];
        !          11842:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
        !          11843:     /*    if(i1 != 1 && TKresult[nres]!= k) */
        !          11844:     /*         continue; */
        !          11845:     fprintf(ficrespijb,"\n#****** ");
        !          11846:     for(j=1;j<=cptcovs;j++){
        !          11847:       fprintf(ficrespij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
        !          11848:       /* for(j=1;j<=cptcoveff;j++) */
        !          11849:       /*       fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
        !          11850:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
        !          11851:       /*       fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
        !          11852:     }
        !          11853:     fprintf(ficrespijb,"******\n");
        !          11854:     if(invalidvarcomb[k]){  /* Is it necessary here? */
        !          11855:       fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
        !          11856:       continue;
        !          11857:     }
        !          11858:     
        !          11859:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
        !          11860:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
        !          11861:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
        !          11862:       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 */
        !          11863:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
        !          11864:       
        !          11865:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
        !          11866:       
        !          11867:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
        !          11868:       /* and memory limitations if stepm is small */
        !          11869:       
        !          11870:       /* oldm=oldms;savm=savms; */
        !          11871:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
        !          11872:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);/* Bug valgrind */
        !          11873:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
        !          11874:       fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
        !          11875:       for(i=1; i<=nlstate;i++)
        !          11876:        for(j=1; j<=nlstate+ndeath;j++)
        !          11877:          fprintf(ficrespijb," %1d-%1d",i,j);
        !          11878:       fprintf(ficrespijb,"\n");
        !          11879:       for (h=0; h<=nhstepm; h++){
        !          11880:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
        !          11881:        fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
        !          11882:        /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
1.217     brouard  11883:        for(i=1; i<=nlstate;i++)
                   11884:          for(j=1; j<=nlstate+ndeath;j++)
1.337   ! brouard  11885:            fprintf(ficrespijb," %.5f", p3mat[i][j][h]);/* Bug valgrind */
1.217     brouard  11886:        fprintf(ficrespijb,"\n");
1.337   ! brouard  11887:       }
        !          11888:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
        !          11889:       fprintf(ficrespijb,"\n");
        !          11890:     } /* end age deb */
        !          11891:     /* } /\* end combination *\/ */
1.238     brouard  11892:   } /* end nres */
1.218     brouard  11893:   return 0;
                   11894:  } /*  hBijx */
1.217     brouard  11895: 
1.180     brouard  11896: 
1.136     brouard  11897: /***********************************************/
                   11898: /**************** Main Program *****************/
                   11899: /***********************************************/
                   11900: 
                   11901: int main(int argc, char *argv[])
                   11902: {
                   11903: #ifdef GSL
                   11904:   const gsl_multimin_fminimizer_type *T;
                   11905:   size_t iteri = 0, it;
                   11906:   int rval = GSL_CONTINUE;
                   11907:   int status = GSL_SUCCESS;
                   11908:   double ssval;
                   11909: #endif
                   11910:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  11911:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   11912:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  11913:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  11914:   int jj, ll, li, lj, lk;
1.136     brouard  11915:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  11916:   int num_filled;
1.136     brouard  11917:   int itimes;
                   11918:   int NDIM=2;
                   11919:   int vpopbased=0;
1.235     brouard  11920:   int nres=0;
1.258     brouard  11921:   int endishere=0;
1.277     brouard  11922:   int noffset=0;
1.274     brouard  11923:   int ncurrv=0; /* Temporary variable */
                   11924:   
1.164     brouard  11925:   char ca[32], cb[32];
1.136     brouard  11926:   /*  FILE *fichtm; *//* Html File */
                   11927:   /* FILE *ficgp;*/ /*Gnuplot File */
                   11928:   struct stat info;
1.191     brouard  11929:   double agedeb=0.;
1.194     brouard  11930: 
                   11931:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  11932:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  11933: 
1.165     brouard  11934:   double fret;
1.191     brouard  11935:   double dum=0.; /* Dummy variable */
1.136     brouard  11936:   double ***p3mat;
1.218     brouard  11937:   /* double ***mobaverage; */
1.319     brouard  11938:   double wald;
1.164     brouard  11939: 
                   11940:   char line[MAXLINE];
1.197     brouard  11941:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   11942: 
1.234     brouard  11943:   char  modeltemp[MAXLINE];
1.332     brouard  11944:   char resultline[MAXLINE], resultlineori[MAXLINE];
1.230     brouard  11945:   
1.136     brouard  11946:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  11947:   char *tok, *val; /* pathtot */
1.334     brouard  11948:   /* int firstobs=1, lastobs=10; /\* nobs = lastobs-firstobs declared globally ;*\/ */
1.195     brouard  11949:   int c,  h , cpt, c2;
1.191     brouard  11950:   int jl=0;
                   11951:   int i1, j1, jk, stepsize=0;
1.194     brouard  11952:   int count=0;
                   11953: 
1.164     brouard  11954:   int *tab; 
1.136     brouard  11955:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  11956:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   11957:   /* double anprojf, mprojf, jprojf; */
                   11958:   /* double jintmean,mintmean,aintmean;   */
                   11959:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   11960:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   11961:   double yrfproj= 10.0; /* Number of years of forward projections */
                   11962:   double yrbproj= 10.0; /* Number of years of backward projections */
                   11963:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  11964:   int mobilav=0,popforecast=0;
1.191     brouard  11965:   int hstepm=0, nhstepm=0;
1.136     brouard  11966:   int agemortsup;
                   11967:   float  sumlpop=0.;
                   11968:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   11969:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   11970: 
1.191     brouard  11971:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  11972:   double ftolpl=FTOL;
                   11973:   double **prlim;
1.217     brouard  11974:   double **bprlim;
1.317     brouard  11975:   double ***param; /* Matrix of parameters, param[i][j][k] param=ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel) 
                   11976:                     state of origin, state of destination including death, for each covariate: constante, age, and V1 V2 etc. */
1.251     brouard  11977:   double ***paramstart; /* Matrix of starting parameter values */
                   11978:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  11979:   double **matcov; /* Matrix of covariance */
1.203     brouard  11980:   double **hess; /* Hessian matrix */
1.136     brouard  11981:   double ***delti3; /* Scale */
                   11982:   double *delti; /* Scale */
                   11983:   double ***eij, ***vareij;
                   11984:   double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  11985: 
1.136     brouard  11986:   double *epj, vepp;
1.164     brouard  11987: 
1.273     brouard  11988:   double dateprev1, dateprev2;
1.296     brouard  11989:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   11990:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   11991: 
1.217     brouard  11992: 
1.136     brouard  11993:   double **ximort;
1.145     brouard  11994:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  11995:   int *dcwave;
                   11996: 
1.164     brouard  11997:   char z[1]="c";
1.136     brouard  11998: 
                   11999:   /*char  *strt;*/
                   12000:   char strtend[80];
1.126     brouard  12001: 
1.164     brouard  12002: 
1.126     brouard  12003: /*   setlocale (LC_ALL, ""); */
                   12004: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   12005: /*   textdomain (PACKAGE); */
                   12006: /*   setlocale (LC_CTYPE, ""); */
                   12007: /*   setlocale (LC_MESSAGES, ""); */
                   12008: 
                   12009:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  12010:   rstart_time = time(NULL);  
                   12011:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   12012:   start_time = *localtime(&rstart_time);
1.126     brouard  12013:   curr_time=start_time;
1.157     brouard  12014:   /*tml = *localtime(&start_time.tm_sec);*/
                   12015:   /* strcpy(strstart,asctime(&tml)); */
                   12016:   strcpy(strstart,asctime(&start_time));
1.126     brouard  12017: 
                   12018: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  12019: /*  tp.tm_sec = tp.tm_sec +86400; */
                   12020: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  12021: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   12022: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   12023: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  12024: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  12025: /*   strt=asctime(&tmg); */
                   12026: /*   printf("Time(after) =%s",strstart);  */
                   12027: /*  (void) time (&time_value);
                   12028: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   12029: *  tm = *localtime(&time_value);
                   12030: *  strstart=asctime(&tm);
                   12031: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   12032: */
                   12033: 
                   12034:   nberr=0; /* Number of errors and warnings */
                   12035:   nbwarn=0;
1.184     brouard  12036: #ifdef WIN32
                   12037:   _getcwd(pathcd, size);
                   12038: #else
1.126     brouard  12039:   getcwd(pathcd, size);
1.184     brouard  12040: #endif
1.191     brouard  12041:   syscompilerinfo(0);
1.196     brouard  12042:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  12043:   if(argc <=1){
                   12044:     printf("\nEnter the parameter file name: ");
1.205     brouard  12045:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   12046:       printf("ERROR Empty parameter file name\n");
                   12047:       goto end;
                   12048:     }
1.126     brouard  12049:     i=strlen(pathr);
                   12050:     if(pathr[i-1]=='\n')
                   12051:       pathr[i-1]='\0';
1.156     brouard  12052:     i=strlen(pathr);
1.205     brouard  12053:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  12054:       pathr[i-1]='\0';
1.205     brouard  12055:     }
                   12056:     i=strlen(pathr);
                   12057:     if( i==0 ){
                   12058:       printf("ERROR Empty parameter file name\n");
                   12059:       goto end;
                   12060:     }
                   12061:     for (tok = pathr; tok != NULL; ){
1.126     brouard  12062:       printf("Pathr |%s|\n",pathr);
                   12063:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   12064:       printf("val= |%s| pathr=%s\n",val,pathr);
                   12065:       strcpy (pathtot, val);
                   12066:       if(pathr[0] == '\0') break; /* Dirty */
                   12067:     }
                   12068:   }
1.281     brouard  12069:   else if (argc<=2){
                   12070:     strcpy(pathtot,argv[1]);
                   12071:   }
1.126     brouard  12072:   else{
                   12073:     strcpy(pathtot,argv[1]);
1.281     brouard  12074:     strcpy(z,argv[2]);
                   12075:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  12076:   }
                   12077:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   12078:   /*cygwin_split_path(pathtot,path,optionfile);
                   12079:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   12080:   /* cutv(path,optionfile,pathtot,'\\');*/
                   12081: 
                   12082:   /* Split argv[0], imach program to get pathimach */
                   12083:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   12084:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   12085:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   12086:  /*   strcpy(pathimach,argv[0]); */
                   12087:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   12088:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   12089:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  12090: #ifdef WIN32
                   12091:   _chdir(path); /* Can be a relative path */
                   12092:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   12093: #else
1.126     brouard  12094:   chdir(path); /* Can be a relative path */
1.184     brouard  12095:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   12096: #endif
                   12097:   printf("Current directory %s!\n",pathcd);
1.126     brouard  12098:   strcpy(command,"mkdir ");
                   12099:   strcat(command,optionfilefiname);
                   12100:   if((outcmd=system(command)) != 0){
1.169     brouard  12101:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  12102:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   12103:     /* fclose(ficlog); */
                   12104: /*     exit(1); */
                   12105:   }
                   12106: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   12107: /*     perror("mkdir"); */
                   12108: /*   } */
                   12109: 
                   12110:   /*-------- arguments in the command line --------*/
                   12111: 
1.186     brouard  12112:   /* Main Log file */
1.126     brouard  12113:   strcat(filelog, optionfilefiname);
                   12114:   strcat(filelog,".log");    /* */
                   12115:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   12116:     printf("Problem with logfile %s\n",filelog);
                   12117:     goto end;
                   12118:   }
                   12119:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  12120:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  12121:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   12122:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   12123:  path=%s \n\
                   12124:  optionfile=%s\n\
                   12125:  optionfilext=%s\n\
1.156     brouard  12126:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  12127: 
1.197     brouard  12128:   syscompilerinfo(1);
1.167     brouard  12129: 
1.126     brouard  12130:   printf("Local time (at start):%s",strstart);
                   12131:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   12132:   fflush(ficlog);
                   12133: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  12134: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  12135: 
                   12136:   /* */
                   12137:   strcpy(fileres,"r");
                   12138:   strcat(fileres, optionfilefiname);
1.201     brouard  12139:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  12140:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  12141:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  12142: 
1.186     brouard  12143:   /* Main ---------arguments file --------*/
1.126     brouard  12144: 
                   12145:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  12146:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   12147:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  12148:     fflush(ficlog);
1.149     brouard  12149:     /* goto end; */
                   12150:     exit(70); 
1.126     brouard  12151:   }
                   12152: 
                   12153:   strcpy(filereso,"o");
1.201     brouard  12154:   strcat(filereso,fileresu);
1.126     brouard  12155:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   12156:     printf("Problem with Output resultfile: %s\n", filereso);
                   12157:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   12158:     fflush(ficlog);
                   12159:     goto end;
                   12160:   }
1.278     brouard  12161:       /*-------- Rewriting parameter file ----------*/
                   12162:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   12163:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   12164:   strcat(rfileres,".");    /* */
                   12165:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   12166:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   12167:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   12168:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   12169:     fflush(ficlog);
                   12170:     goto end;
                   12171:   }
                   12172:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  12173: 
1.278     brouard  12174:                                      
1.126     brouard  12175:   /* Reads comments: lines beginning with '#' */
                   12176:   numlinepar=0;
1.277     brouard  12177:   /* Is it a BOM UTF-8 Windows file? */
                   12178:   /* First parameter line */
1.197     brouard  12179:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  12180:     noffset=0;
                   12181:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   12182:     {
                   12183:       noffset=noffset+3;
                   12184:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   12185:     }
1.302     brouard  12186: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   12187:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
1.277     brouard  12188:     {
                   12189:       noffset=noffset+2;
                   12190:       printf("# File is an UTF16BE BOM file\n");
                   12191:     }
                   12192:     else if( line[0] == 0 && line[1] == 0)
                   12193:     {
                   12194:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   12195:        noffset=noffset+4;
                   12196:        printf("# File is an UTF16BE BOM file\n");
                   12197:       }
                   12198:     } else{
                   12199:       ;/*printf(" Not a BOM file\n");*/
                   12200:     }
                   12201:   
1.197     brouard  12202:     /* If line starts with a # it is a comment */
1.277     brouard  12203:     if (line[noffset] == '#') {
1.197     brouard  12204:       numlinepar++;
                   12205:       fputs(line,stdout);
                   12206:       fputs(line,ficparo);
1.278     brouard  12207:       fputs(line,ficres);
1.197     brouard  12208:       fputs(line,ficlog);
                   12209:       continue;
                   12210:     }else
                   12211:       break;
                   12212:   }
                   12213:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   12214:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   12215:     if (num_filled != 5) {
                   12216:       printf("Should be 5 parameters\n");
1.283     brouard  12217:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  12218:     }
1.126     brouard  12219:     numlinepar++;
1.197     brouard  12220:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  12221:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   12222:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   12223:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  12224:   }
                   12225:   /* Second parameter line */
                   12226:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  12227:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   12228:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  12229:     if (line[0] == '#') {
                   12230:       numlinepar++;
1.283     brouard  12231:       printf("%s",line);
                   12232:       fprintf(ficres,"%s",line);
                   12233:       fprintf(ficparo,"%s",line);
                   12234:       fprintf(ficlog,"%s",line);
1.197     brouard  12235:       continue;
                   12236:     }else
                   12237:       break;
                   12238:   }
1.223     brouard  12239:   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", \
                   12240:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   12241:     if (num_filled != 11) {
                   12242:       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  12243:       printf("but line=%s\n",line);
1.283     brouard  12244:       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");
                   12245:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  12246:     }
1.286     brouard  12247:     if( lastpass > maxwav){
                   12248:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   12249:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   12250:       fflush(ficlog);
                   12251:       goto end;
                   12252:     }
                   12253:       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  12254:     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  12255:     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  12256:     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  12257:   }
1.203     brouard  12258:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  12259:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  12260:   /* Third parameter line */
                   12261:   while(fgets(line, MAXLINE, ficpar)) {
                   12262:     /* If line starts with a # it is a comment */
                   12263:     if (line[0] == '#') {
                   12264:       numlinepar++;
1.283     brouard  12265:       printf("%s",line);
                   12266:       fprintf(ficres,"%s",line);
                   12267:       fprintf(ficparo,"%s",line);
                   12268:       fprintf(ficlog,"%s",line);
1.197     brouard  12269:       continue;
                   12270:     }else
                   12271:       break;
                   12272:   }
1.201     brouard  12273:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
1.279     brouard  12274:     if (num_filled != 1){
1.302     brouard  12275:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   12276:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
1.197     brouard  12277:       model[0]='\0';
                   12278:       goto end;
                   12279:     }
                   12280:     else{
                   12281:       if (model[0]=='+'){
                   12282:        for(i=1; i<=strlen(model);i++)
                   12283:          modeltemp[i-1]=model[i];
1.201     brouard  12284:        strcpy(model,modeltemp); 
1.197     brouard  12285:       }
                   12286:     }
1.199     brouard  12287:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  12288:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  12289:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   12290:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   12291:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  12292:   }
                   12293:   /* 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); */
                   12294:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   12295:   /* 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  12296:   /* 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); */
                   12297:   /* 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  12298:   fflush(ficlog);
1.190     brouard  12299:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   12300:   if(model[0]=='#'){
1.279     brouard  12301:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   12302:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   12303:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  12304:     if(mle != -1){
1.279     brouard  12305:       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  12306:       exit(1);
                   12307:     }
                   12308:   }
1.126     brouard  12309:   while((c=getc(ficpar))=='#' && c!= EOF){
                   12310:     ungetc(c,ficpar);
                   12311:     fgets(line, MAXLINE, ficpar);
                   12312:     numlinepar++;
1.195     brouard  12313:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   12314:       z[0]=line[1];
                   12315:     }
                   12316:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  12317:     fputs(line, stdout);
                   12318:     //puts(line);
1.126     brouard  12319:     fputs(line,ficparo);
                   12320:     fputs(line,ficlog);
                   12321:   }
                   12322:   ungetc(c,ficpar);
                   12323: 
                   12324:    
1.290     brouard  12325:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   12326:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   12327:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
                   12328:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /**< Time varying covariate (dummy and quantitative)*/
1.136     brouard  12329:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   12330:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   12331:      v1+v2*age+v2*v3 makes cptcovn = 3
                   12332:   */
                   12333:   if (strlen(model)>1) 
1.187     brouard  12334:     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  12335:   else
1.187     brouard  12336:     ncovmodel=2; /* Constant and age */
1.133     brouard  12337:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   12338:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  12339:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   12340:     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);
                   12341:     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);
                   12342:     fflush(stdout);
                   12343:     fclose (ficlog);
                   12344:     goto end;
                   12345:   }
1.126     brouard  12346:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   12347:   delti=delti3[1][1];
                   12348:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   12349:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  12350: /* We could also provide initial parameters values giving by simple logistic regression 
                   12351:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   12352:       /* for(i=1;i<nlstate;i++){ */
                   12353:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   12354:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   12355:       /* } */
1.126     brouard  12356:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  12357:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   12358:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  12359:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   12360:     fclose (ficparo);
                   12361:     fclose (ficlog);
                   12362:     goto end;
                   12363:     exit(0);
1.220     brouard  12364:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  12365:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  12366:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   12367:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  12368:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   12369:     matcov=matrix(1,npar,1,npar);
1.203     brouard  12370:     hess=matrix(1,npar,1,npar);
1.220     brouard  12371:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  12372:     /* Read guessed parameters */
1.126     brouard  12373:     /* Reads comments: lines beginning with '#' */
                   12374:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12375:       ungetc(c,ficpar);
                   12376:       fgets(line, MAXLINE, ficpar);
                   12377:       numlinepar++;
1.141     brouard  12378:       fputs(line,stdout);
1.126     brouard  12379:       fputs(line,ficparo);
                   12380:       fputs(line,ficlog);
                   12381:     }
                   12382:     ungetc(c,ficpar);
                   12383:     
                   12384:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  12385:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  12386:     for(i=1; i <=nlstate; i++){
1.234     brouard  12387:       j=0;
1.126     brouard  12388:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  12389:        if(jj==i) continue;
                   12390:        j++;
1.292     brouard  12391:        while((c=getc(ficpar))=='#' && c!= EOF){
                   12392:          ungetc(c,ficpar);
                   12393:          fgets(line, MAXLINE, ficpar);
                   12394:          numlinepar++;
                   12395:          fputs(line,stdout);
                   12396:          fputs(line,ficparo);
                   12397:          fputs(line,ficlog);
                   12398:        }
                   12399:        ungetc(c,ficpar);
1.234     brouard  12400:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   12401:        if ((i1 != i) || (j1 != jj)){
                   12402:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  12403: It might be a problem of design; if ncovcol and the model are correct\n \
                   12404: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  12405:          exit(1);
                   12406:        }
                   12407:        fprintf(ficparo,"%1d%1d",i1,j1);
                   12408:        if(mle==1)
                   12409:          printf("%1d%1d",i,jj);
                   12410:        fprintf(ficlog,"%1d%1d",i,jj);
                   12411:        for(k=1; k<=ncovmodel;k++){
                   12412:          fscanf(ficpar," %lf",&param[i][j][k]);
                   12413:          if(mle==1){
                   12414:            printf(" %lf",param[i][j][k]);
                   12415:            fprintf(ficlog," %lf",param[i][j][k]);
                   12416:          }
                   12417:          else
                   12418:            fprintf(ficlog," %lf",param[i][j][k]);
                   12419:          fprintf(ficparo," %lf",param[i][j][k]);
                   12420:        }
                   12421:        fscanf(ficpar,"\n");
                   12422:        numlinepar++;
                   12423:        if(mle==1)
                   12424:          printf("\n");
                   12425:        fprintf(ficlog,"\n");
                   12426:        fprintf(ficparo,"\n");
1.126     brouard  12427:       }
                   12428:     }  
                   12429:     fflush(ficlog);
1.234     brouard  12430:     
1.251     brouard  12431:     /* Reads parameters values */
1.126     brouard  12432:     p=param[1][1];
1.251     brouard  12433:     pstart=paramstart[1][1];
1.126     brouard  12434:     
                   12435:     /* Reads comments: lines beginning with '#' */
                   12436:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12437:       ungetc(c,ficpar);
                   12438:       fgets(line, MAXLINE, ficpar);
                   12439:       numlinepar++;
1.141     brouard  12440:       fputs(line,stdout);
1.126     brouard  12441:       fputs(line,ficparo);
                   12442:       fputs(line,ficlog);
                   12443:     }
                   12444:     ungetc(c,ficpar);
                   12445: 
                   12446:     for(i=1; i <=nlstate; i++){
                   12447:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  12448:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   12449:        if ( (i1-i) * (j1-j) != 0){
                   12450:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   12451:          exit(1);
                   12452:        }
                   12453:        printf("%1d%1d",i,j);
                   12454:        fprintf(ficparo,"%1d%1d",i1,j1);
                   12455:        fprintf(ficlog,"%1d%1d",i1,j1);
                   12456:        for(k=1; k<=ncovmodel;k++){
                   12457:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   12458:          printf(" %le",delti3[i][j][k]);
                   12459:          fprintf(ficparo," %le",delti3[i][j][k]);
                   12460:          fprintf(ficlog," %le",delti3[i][j][k]);
                   12461:        }
                   12462:        fscanf(ficpar,"\n");
                   12463:        numlinepar++;
                   12464:        printf("\n");
                   12465:        fprintf(ficparo,"\n");
                   12466:        fprintf(ficlog,"\n");
1.126     brouard  12467:       }
                   12468:     }
                   12469:     fflush(ficlog);
1.234     brouard  12470:     
1.145     brouard  12471:     /* Reads covariance matrix */
1.126     brouard  12472:     delti=delti3[1][1];
1.220     brouard  12473:                
                   12474:                
1.126     brouard  12475:     /* 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  12476:                
1.126     brouard  12477:     /* Reads comments: lines beginning with '#' */
                   12478:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12479:       ungetc(c,ficpar);
                   12480:       fgets(line, MAXLINE, ficpar);
                   12481:       numlinepar++;
1.141     brouard  12482:       fputs(line,stdout);
1.126     brouard  12483:       fputs(line,ficparo);
                   12484:       fputs(line,ficlog);
                   12485:     }
                   12486:     ungetc(c,ficpar);
1.220     brouard  12487:                
1.126     brouard  12488:     matcov=matrix(1,npar,1,npar);
1.203     brouard  12489:     hess=matrix(1,npar,1,npar);
1.131     brouard  12490:     for(i=1; i <=npar; i++)
                   12491:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  12492:                
1.194     brouard  12493:     /* Scans npar lines */
1.126     brouard  12494:     for(i=1; i <=npar; i++){
1.226     brouard  12495:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  12496:       if(count != 3){
1.226     brouard  12497:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  12498: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   12499: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  12500:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  12501: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   12502: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  12503:        exit(1);
1.220     brouard  12504:       }else{
1.226     brouard  12505:        if(mle==1)
                   12506:          printf("%1d%1d%d",i1,j1,jk);
                   12507:       }
                   12508:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   12509:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  12510:       for(j=1; j <=i; j++){
1.226     brouard  12511:        fscanf(ficpar," %le",&matcov[i][j]);
                   12512:        if(mle==1){
                   12513:          printf(" %.5le",matcov[i][j]);
                   12514:        }
                   12515:        fprintf(ficlog," %.5le",matcov[i][j]);
                   12516:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  12517:       }
                   12518:       fscanf(ficpar,"\n");
                   12519:       numlinepar++;
                   12520:       if(mle==1)
1.220     brouard  12521:                                printf("\n");
1.126     brouard  12522:       fprintf(ficlog,"\n");
                   12523:       fprintf(ficparo,"\n");
                   12524:     }
1.194     brouard  12525:     /* End of read covariance matrix npar lines */
1.126     brouard  12526:     for(i=1; i <=npar; i++)
                   12527:       for(j=i+1;j<=npar;j++)
1.226     brouard  12528:        matcov[i][j]=matcov[j][i];
1.126     brouard  12529:     
                   12530:     if(mle==1)
                   12531:       printf("\n");
                   12532:     fprintf(ficlog,"\n");
                   12533:     
                   12534:     fflush(ficlog);
                   12535:     
                   12536:   }    /* End of mle != -3 */
1.218     brouard  12537:   
1.186     brouard  12538:   /*  Main data
                   12539:    */
1.290     brouard  12540:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   12541:   /* num=lvector(1,n); */
                   12542:   /* moisnais=vector(1,n); */
                   12543:   /* annais=vector(1,n); */
                   12544:   /* moisdc=vector(1,n); */
                   12545:   /* andc=vector(1,n); */
                   12546:   /* weight=vector(1,n); */
                   12547:   /* agedc=vector(1,n); */
                   12548:   /* cod=ivector(1,n); */
                   12549:   /* for(i=1;i<=n;i++){ */
                   12550:   num=lvector(firstobs,lastobs);
                   12551:   moisnais=vector(firstobs,lastobs);
                   12552:   annais=vector(firstobs,lastobs);
                   12553:   moisdc=vector(firstobs,lastobs);
                   12554:   andc=vector(firstobs,lastobs);
                   12555:   weight=vector(firstobs,lastobs);
                   12556:   agedc=vector(firstobs,lastobs);
                   12557:   cod=ivector(firstobs,lastobs);
                   12558:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  12559:     num[i]=0;
                   12560:     moisnais[i]=0;
                   12561:     annais[i]=0;
                   12562:     moisdc[i]=0;
                   12563:     andc[i]=0;
                   12564:     agedc[i]=0;
                   12565:     cod[i]=0;
                   12566:     weight[i]=1.0; /* Equal weights, 1 by default */
                   12567:   }
1.290     brouard  12568:   mint=matrix(1,maxwav,firstobs,lastobs);
                   12569:   anint=matrix(1,maxwav,firstobs,lastobs);
1.325     brouard  12570:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */
1.336     brouard  12571:   /* printf("BUG ncovmodel=%d NCOVMAX=%d 2**ncovmodel=%f BUG\n",ncovmodel,NCOVMAX,pow(2,ncovmodel)); */
1.126     brouard  12572:   tab=ivector(1,NCOVMAX);
1.144     brouard  12573:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  12574:   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  12575: 
1.136     brouard  12576:   /* Reads data from file datafile */
                   12577:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   12578:     goto end;
                   12579: 
                   12580:   /* Calculation of the number of parameters from char model */
1.234     brouard  12581:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  12582:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   12583:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   12584:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   12585:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  12586:   */
                   12587:   
                   12588:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   12589:   TvarsDind=ivector(1,NCOVMAX); /*  */
1.330     brouard  12590:   TnsdVar=ivector(1,NCOVMAX); /*  */
1.335     brouard  12591:     /* for(i=1; i<=NCOVMAX;i++) TnsdVar[i]=3; */
1.234     brouard  12592:   TvarsD=ivector(1,NCOVMAX); /*  */
                   12593:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   12594:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  12595:   TvarF=ivector(1,NCOVMAX); /*  */
                   12596:   TvarFind=ivector(1,NCOVMAX); /*  */
                   12597:   TvarV=ivector(1,NCOVMAX); /*  */
                   12598:   TvarVind=ivector(1,NCOVMAX); /*  */
                   12599:   TvarA=ivector(1,NCOVMAX); /*  */
                   12600:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  12601:   TvarFD=ivector(1,NCOVMAX); /*  */
                   12602:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   12603:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   12604:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   12605:   TvarVD=ivector(1,NCOVMAX); /*  */
                   12606:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   12607:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   12608:   TvarVQind=ivector(1,NCOVMAX); /*  */
                   12609: 
1.230     brouard  12610:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  12611:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  12612:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   12613:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   12614:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.137     brouard  12615:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   12616:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   12617:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   12618:   */
                   12619:   /* For model-covariate k tells which data-covariate to use but
                   12620:     because this model-covariate is a construction we invent a new column
                   12621:     ncovcol + k1
                   12622:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   12623:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  12624:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   12625:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  12626:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   12627:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  12628:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  12629:   */
1.145     brouard  12630:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   12631:   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  12632:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   12633:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.330     brouard  12634:   Tvardk=imatrix(1,NCOVMAX,1,2);
1.145     brouard  12635:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  12636:                         4 covariates (3 plus signs)
                   12637:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
1.328     brouard  12638:                           */  
                   12639:   for(i=1;i<NCOVMAX;i++)
                   12640:     Tage[i]=0;
1.230     brouard  12641:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  12642:                                * individual dummy, fixed or varying:
                   12643:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   12644:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  12645:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   12646:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   12647:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   12648:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   12649:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  12650:                                * individual quantitative, fixed or varying:
                   12651:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   12652:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   12653:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.186     brouard  12654: /* Main decodemodel */
                   12655: 
1.187     brouard  12656: 
1.223     brouard  12657:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  12658:     goto end;
                   12659: 
1.137     brouard  12660:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   12661:     nbwarn++;
                   12662:     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); 
                   12663:     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); 
                   12664:   }
1.136     brouard  12665:     /*  if(mle==1){*/
1.137     brouard  12666:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   12667:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  12668:   }
                   12669: 
                   12670:     /*-calculation of age at interview from date of interview and age at death -*/
                   12671:   agev=matrix(1,maxwav,1,imx);
                   12672: 
                   12673:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   12674:     goto end;
                   12675: 
1.126     brouard  12676: 
1.136     brouard  12677:   agegomp=(int)agemin;
1.290     brouard  12678:   free_vector(moisnais,firstobs,lastobs);
                   12679:   free_vector(annais,firstobs,lastobs);
1.126     brouard  12680:   /* free_matrix(mint,1,maxwav,1,n);
                   12681:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  12682:   /* free_vector(moisdc,1,n); */
                   12683:   /* free_vector(andc,1,n); */
1.145     brouard  12684:   /* */
                   12685:   
1.126     brouard  12686:   wav=ivector(1,imx);
1.214     brouard  12687:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   12688:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   12689:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   12690:   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.*/
                   12691:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   12692:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  12693:    
                   12694:   /* Concatenates waves */
1.214     brouard  12695:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   12696:      Death is a valid wave (if date is known).
                   12697:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   12698:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   12699:      and mw[mi+1][i]. dh depends on stepm.
                   12700:   */
                   12701: 
1.126     brouard  12702:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  12703:   /* Concatenates waves */
1.145     brouard  12704:  
1.290     brouard  12705:   free_vector(moisdc,firstobs,lastobs);
                   12706:   free_vector(andc,firstobs,lastobs);
1.215     brouard  12707: 
1.126     brouard  12708:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   12709:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   12710:   ncodemax[1]=1;
1.145     brouard  12711:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  12712:   cptcoveff=0;
1.220     brouard  12713:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
1.335     brouard  12714:     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  12715:   }
                   12716:   
                   12717:   ncovcombmax=pow(2,cptcoveff);
                   12718:   invalidvarcomb=ivector(1, ncovcombmax); 
                   12719:   for(i=1;i<ncovcombmax;i++)
                   12720:     invalidvarcomb[i]=0;
                   12721:   
1.211     brouard  12722:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  12723:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  12724:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  12725:   
1.200     brouard  12726:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  12727:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  12728:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  12729:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   12730:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   12731:    * (currently 0 or 1) in the data.
                   12732:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   12733:    * corresponding modality (h,j).
                   12734:    */
                   12735: 
1.145     brouard  12736:   h=0;
                   12737:   /*if (cptcovn > 0) */
1.126     brouard  12738:   m=pow(2,cptcoveff);
                   12739:  
1.144     brouard  12740:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  12741:           * For k=4 covariates, h goes from 1 to m=2**k
                   12742:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   12743:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.329     brouard  12744:           *     h\k   1     2     3     4   *  h-1\k-1  4  3  2  1          
                   12745:           *______________________________   *______________________
                   12746:           *     1 i=1 1 i=1 1 i=1 1 i=1 1   *     0     0  0  0  0 
                   12747:           *     2     2     1     1     1   *     1     0  0  0  1 
                   12748:           *     3 i=2 1     2     1     1   *     2     0  0  1  0 
                   12749:           *     4     2     2     1     1   *     3     0  0  1  1 
                   12750:           *     5 i=3 1 i=2 1     2     1   *     4     0  1  0  0 
                   12751:           *     6     2     1     2     1   *     5     0  1  0  1 
                   12752:           *     7 i=4 1     2     2     1   *     6     0  1  1  0 
                   12753:           *     8     2     2     2     1   *     7     0  1  1  1 
                   12754:           *     9 i=5 1 i=3 1 i=2 1     2   *     8     1  0  0  0 
                   12755:           *    10     2     1     1     2   *     9     1  0  0  1 
                   12756:           *    11 i=6 1     2     1     2   *    10     1  0  1  0 
                   12757:           *    12     2     2     1     2   *    11     1  0  1  1 
                   12758:           *    13 i=7 1 i=4 1     2     2   *    12     1  1  0  0  
                   12759:           *    14     2     1     2     2   *    13     1  1  0  1 
                   12760:           *    15 i=8 1     2     2     2   *    14     1  1  1  0 
                   12761:           *    16     2     2     2     2   *    15     1  1  1  1          
                   12762:           */                                     
1.212     brouard  12763:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  12764:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   12765:      * and the value of each covariate?
                   12766:      * V1=1, V2=1, V3=2, V4=1 ?
                   12767:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   12768:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   12769:      * In order to get the real value in the data, we use nbcode
                   12770:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   12771:      * We are keeping this crazy system in order to be able (in the future?) 
                   12772:      * to have more than 2 values (0 or 1) for a covariate.
                   12773:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   12774:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   12775:      *              bbbbbbbb
                   12776:      *              76543210     
                   12777:      *   h-1        00000101 (6-1=5)
1.219     brouard  12778:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  12779:      *           &
                   12780:      *     1        00000001 (1)
1.219     brouard  12781:      *              00000000        = 1 & ((h-1) >> (k-1))
                   12782:      *          +1= 00000001 =1 
1.211     brouard  12783:      *
                   12784:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   12785:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   12786:      *    >>k'            11
                   12787:      *          &   00000001
                   12788:      *            = 00000001
                   12789:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   12790:      * Reverse h=6 and m=16?
                   12791:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   12792:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   12793:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   12794:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   12795:      * V3=decodtabm(14,3,2**4)=2
                   12796:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   12797:      *(h-1) >> (j-1)    0011 =13 >> 2
                   12798:      *          &1 000000001
                   12799:      *           = 000000001
                   12800:      *         +1= 000000010 =2
                   12801:      *                  2211
                   12802:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   12803:      *                  V3=2
1.220     brouard  12804:                 * codtabm and decodtabm are identical
1.211     brouard  12805:      */
                   12806: 
1.145     brouard  12807: 
                   12808:  free_ivector(Ndum,-1,NCOVMAX);
                   12809: 
                   12810: 
1.126     brouard  12811:     
1.186     brouard  12812:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  12813:   strcpy(optionfilegnuplot,optionfilefiname);
                   12814:   if(mle==-3)
1.201     brouard  12815:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  12816:   strcat(optionfilegnuplot,".gp");
                   12817: 
                   12818:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   12819:     printf("Problem with file %s",optionfilegnuplot);
                   12820:   }
                   12821:   else{
1.204     brouard  12822:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  12823:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  12824:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   12825:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  12826:   }
                   12827:   /*  fclose(ficgp);*/
1.186     brouard  12828: 
                   12829: 
                   12830:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  12831: 
                   12832:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   12833:   if(mle==-3)
1.201     brouard  12834:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  12835:   strcat(optionfilehtm,".htm");
                   12836:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  12837:     printf("Problem with %s \n",optionfilehtm);
                   12838:     exit(0);
1.126     brouard  12839:   }
                   12840: 
                   12841:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   12842:   strcat(optionfilehtmcov,"-cov.htm");
                   12843:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   12844:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   12845:   }
                   12846:   else{
                   12847:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   12848: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  12849: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  12850:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   12851:   }
                   12852: 
1.335     brouard  12853:   fprintf(fichtm,"<html><head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n\
                   12854: <title>IMaCh %s</title></head>\n\
                   12855:  <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n\
                   12856: <font size=\"3\">Sponsored by Copyright (C)  2002-2015 <a href=http://www.ined.fr>INED</a>\
                   12857: -EUROREVES-Institut de longévité-2013-2022-Japan Society for the Promotion of Sciences 日本学術振興会 \
                   12858: (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - \
                   12859: <a href=https://software.intel.com/en-us>Intel Software 2015-2018</a></font><br> \n", optionfilehtm);
                   12860:   
                   12861:   fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  12862: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  12863: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.337   ! brouard  12864: 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  12865: \n\
                   12866: <hr  size=\"2\" color=\"#EC5E5E\">\
                   12867:  <ul><li><h4>Parameter files</h4>\n\
                   12868:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   12869:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   12870:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   12871:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   12872:  - Date and time at start: %s</ul>\n",\
1.335     brouard  12873:          version,fullversion,optionfilehtm,optionfilehtm,title,datafile,datafile,firstpass,lastpass,stepm, weightopt, model, \
1.126     brouard  12874:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   12875:          fileres,fileres,\
                   12876:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   12877:   fflush(fichtm);
                   12878: 
                   12879:   strcpy(pathr,path);
                   12880:   strcat(pathr,optionfilefiname);
1.184     brouard  12881: #ifdef WIN32
                   12882:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   12883: #else
1.126     brouard  12884:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  12885: #endif
                   12886:          
1.126     brouard  12887:   
1.220     brouard  12888:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   12889:                 and for any valid combination of covariates
1.126     brouard  12890:      and prints on file fileres'p'. */
1.251     brouard  12891:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  12892:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  12893: 
                   12894:   fprintf(fichtm,"\n");
1.286     brouard  12895:   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  12896:          ftol, stepm);
                   12897:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   12898:   ncurrv=1;
                   12899:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   12900:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   12901:   ncurrv=i;
                   12902:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  12903:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  12904:   ncurrv=i;
                   12905:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  12906:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  12907:   ncurrv=i;
                   12908:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   12909:   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", \
                   12910:           nlstate, ndeath, maxwav, mle, weightopt);
                   12911: 
                   12912:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   12913: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   12914: 
                   12915:   
1.317     brouard  12916:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Number of (used) observations=%d <br>\n\
1.126     brouard  12917: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   12918: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  12919:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  12920:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  12921:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   12922:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   12923:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   12924:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  12925: 
1.126     brouard  12926:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   12927:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   12928:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   12929: 
                   12930:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  12931:   /* For mortality only */
1.126     brouard  12932:   if (mle==-3){
1.136     brouard  12933:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  12934:     for(i=1;i<=NDIM;i++)
                   12935:       for(j=1;j<=NDIM;j++)
                   12936:        ximort[i][j]=0.;
1.186     brouard  12937:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  12938:     cens=ivector(firstobs,lastobs);
                   12939:     ageexmed=vector(firstobs,lastobs);
                   12940:     agecens=vector(firstobs,lastobs);
                   12941:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  12942:                
1.126     brouard  12943:     for (i=1; i<=imx; i++){
                   12944:       dcwave[i]=-1;
                   12945:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  12946:        if (s[m][i]>nlstate) {
                   12947:          dcwave[i]=m;
                   12948:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   12949:          break;
                   12950:        }
1.126     brouard  12951:     }
1.226     brouard  12952:     
1.126     brouard  12953:     for (i=1; i<=imx; i++) {
                   12954:       if (wav[i]>0){
1.226     brouard  12955:        ageexmed[i]=agev[mw[1][i]][i];
                   12956:        j=wav[i];
                   12957:        agecens[i]=1.; 
                   12958:        
                   12959:        if (ageexmed[i]> 1 && wav[i] > 0){
                   12960:          agecens[i]=agev[mw[j][i]][i];
                   12961:          cens[i]= 1;
                   12962:        }else if (ageexmed[i]< 1) 
                   12963:          cens[i]= -1;
                   12964:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   12965:          cens[i]=0 ;
1.126     brouard  12966:       }
                   12967:       else cens[i]=-1;
                   12968:     }
                   12969:     
                   12970:     for (i=1;i<=NDIM;i++) {
                   12971:       for (j=1;j<=NDIM;j++)
1.226     brouard  12972:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  12973:     }
                   12974:     
1.302     brouard  12975:     p[1]=0.0268; p[NDIM]=0.083;
                   12976:     /* printf("%lf %lf", p[1], p[2]); */
1.126     brouard  12977:     
                   12978:     
1.136     brouard  12979: #ifdef GSL
                   12980:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  12981: #else
1.126     brouard  12982:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  12983: #endif
1.201     brouard  12984:     strcpy(filerespow,"POW-MORT_"); 
                   12985:     strcat(filerespow,fileresu);
1.126     brouard  12986:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   12987:       printf("Problem with resultfile: %s\n", filerespow);
                   12988:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   12989:     }
1.136     brouard  12990: #ifdef GSL
                   12991:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  12992: #else
1.126     brouard  12993:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  12994: #endif
1.126     brouard  12995:     /*  for (i=1;i<=nlstate;i++)
                   12996:        for(j=1;j<=nlstate+ndeath;j++)
                   12997:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   12998:     */
                   12999:     fprintf(ficrespow,"\n");
1.136     brouard  13000: #ifdef GSL
                   13001:     /* gsl starts here */ 
                   13002:     T = gsl_multimin_fminimizer_nmsimplex;
                   13003:     gsl_multimin_fminimizer *sfm = NULL;
                   13004:     gsl_vector *ss, *x;
                   13005:     gsl_multimin_function minex_func;
                   13006: 
                   13007:     /* Initial vertex size vector */
                   13008:     ss = gsl_vector_alloc (NDIM);
                   13009:     
                   13010:     if (ss == NULL){
                   13011:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   13012:     }
                   13013:     /* Set all step sizes to 1 */
                   13014:     gsl_vector_set_all (ss, 0.001);
                   13015: 
                   13016:     /* Starting point */
1.126     brouard  13017:     
1.136     brouard  13018:     x = gsl_vector_alloc (NDIM);
                   13019:     
                   13020:     if (x == NULL){
                   13021:       gsl_vector_free(ss);
                   13022:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   13023:     }
                   13024:   
                   13025:     /* Initialize method and iterate */
                   13026:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  13027:     /*     gsl_vector_set(x, 0, 0.0268); */
                   13028:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  13029:     gsl_vector_set(x, 0, p[1]);
                   13030:     gsl_vector_set(x, 1, p[2]);
                   13031: 
                   13032:     minex_func.f = &gompertz_f;
                   13033:     minex_func.n = NDIM;
                   13034:     minex_func.params = (void *)&p; /* ??? */
                   13035:     
                   13036:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   13037:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   13038:     
                   13039:     printf("Iterations beginning .....\n\n");
                   13040:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   13041: 
                   13042:     iteri=0;
                   13043:     while (rval == GSL_CONTINUE){
                   13044:       iteri++;
                   13045:       status = gsl_multimin_fminimizer_iterate(sfm);
                   13046:       
                   13047:       if (status) printf("error: %s\n", gsl_strerror (status));
                   13048:       fflush(0);
                   13049:       
                   13050:       if (status) 
                   13051:         break;
                   13052:       
                   13053:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   13054:       ssval = gsl_multimin_fminimizer_size (sfm);
                   13055:       
                   13056:       if (rval == GSL_SUCCESS)
                   13057:         printf ("converged to a local maximum at\n");
                   13058:       
                   13059:       printf("%5d ", iteri);
                   13060:       for (it = 0; it < NDIM; it++){
                   13061:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   13062:       }
                   13063:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   13064:     }
                   13065:     
                   13066:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   13067:     
                   13068:     gsl_vector_free(x); /* initial values */
                   13069:     gsl_vector_free(ss); /* inital step size */
                   13070:     for (it=0; it<NDIM; it++){
                   13071:       p[it+1]=gsl_vector_get(sfm->x,it);
                   13072:       fprintf(ficrespow," %.12lf", p[it]);
                   13073:     }
                   13074:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   13075: #endif
                   13076: #ifdef POWELL
                   13077:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   13078: #endif  
1.126     brouard  13079:     fclose(ficrespow);
                   13080:     
1.203     brouard  13081:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  13082: 
                   13083:     for(i=1; i <=NDIM; i++)
                   13084:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  13085:                                matcov[i][j]=matcov[j][i];
1.126     brouard  13086:     
                   13087:     printf("\nCovariance matrix\n ");
1.203     brouard  13088:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  13089:     for(i=1; i <=NDIM; i++) {
                   13090:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  13091:                                printf("%f ",matcov[i][j]);
                   13092:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  13093:       }
1.203     brouard  13094:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  13095:     }
                   13096:     
                   13097:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  13098:     for (i=1;i<=NDIM;i++) {
1.126     brouard  13099:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  13100:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   13101:     }
1.302     brouard  13102:     lsurv=vector(agegomp,AGESUP);
                   13103:     lpop=vector(agegomp,AGESUP);
                   13104:     tpop=vector(agegomp,AGESUP);
1.126     brouard  13105:     lsurv[agegomp]=100000;
                   13106:     
                   13107:     for (k=agegomp;k<=AGESUP;k++) {
                   13108:       agemortsup=k;
                   13109:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   13110:     }
                   13111:     
                   13112:     for (k=agegomp;k<agemortsup;k++)
                   13113:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   13114:     
                   13115:     for (k=agegomp;k<agemortsup;k++){
                   13116:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   13117:       sumlpop=sumlpop+lpop[k];
                   13118:     }
                   13119:     
                   13120:     tpop[agegomp]=sumlpop;
                   13121:     for (k=agegomp;k<(agemortsup-3);k++){
                   13122:       /*  tpop[k+1]=2;*/
                   13123:       tpop[k+1]=tpop[k]-lpop[k];
                   13124:     }
                   13125:     
                   13126:     
                   13127:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   13128:     for (k=agegomp;k<(agemortsup-2);k++) 
                   13129:       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]);
                   13130:     
                   13131:     
                   13132:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  13133:                ageminpar=50;
                   13134:                agemaxpar=100;
1.194     brouard  13135:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   13136:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   13137: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13138: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   13139:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   13140: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13141: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  13142:     }else{
                   13143:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   13144:                        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  13145:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  13146:                }
1.201     brouard  13147:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  13148:                     stepm, weightopt,\
                   13149:                     model,imx,p,matcov,agemortsup);
                   13150:     
1.302     brouard  13151:     free_vector(lsurv,agegomp,AGESUP);
                   13152:     free_vector(lpop,agegomp,AGESUP);
                   13153:     free_vector(tpop,agegomp,AGESUP);
1.220     brouard  13154:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  13155:     free_ivector(dcwave,firstobs,lastobs);
                   13156:     free_vector(agecens,firstobs,lastobs);
                   13157:     free_vector(ageexmed,firstobs,lastobs);
                   13158:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  13159: #ifdef GSL
1.136     brouard  13160: #endif
1.186     brouard  13161:   } /* Endof if mle==-3 mortality only */
1.205     brouard  13162:   /* Standard  */
                   13163:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   13164:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   13165:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  13166:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  13167:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   13168:     for (k=1; k<=npar;k++)
                   13169:       printf(" %d %8.5f",k,p[k]);
                   13170:     printf("\n");
1.205     brouard  13171:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   13172:       /* mlikeli uses func not funcone */
1.247     brouard  13173:       /* for(i=1;i<nlstate;i++){ */
                   13174:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   13175:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   13176:       /* } */
1.205     brouard  13177:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   13178:     }
                   13179:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   13180:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   13181:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   13182:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   13183:     }
                   13184:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  13185:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   13186:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
1.335     brouard  13187:           /* exit(0); */
1.126     brouard  13188:     for (k=1; k<=npar;k++)
                   13189:       printf(" %d %8.5f",k,p[k]);
                   13190:     printf("\n");
                   13191:     
                   13192:     /*--------- results files --------------*/
1.283     brouard  13193:     /* 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  13194:     
                   13195:     
                   13196:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  13197:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); /* Printing model equation */
1.126     brouard  13198:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  13199: 
                   13200:     printf("#model=  1      +     age ");
                   13201:     fprintf(ficres,"#model=  1      +     age ");
                   13202:     fprintf(ficlog,"#model=  1      +     age ");
                   13203:     fprintf(fichtm,"\n<ul><li> model=1+age+%s\n \
                   13204: </ul>", model);
                   13205: 
                   13206:     fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">\n");
                   13207:     fprintf(fichtm, "<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   13208:     if(nagesqr==1){
                   13209:       printf("  + age*age  ");
                   13210:       fprintf(ficres,"  + age*age  ");
                   13211:       fprintf(ficlog,"  + age*age  ");
                   13212:       fprintf(fichtm, "<th>+ age*age</th>");
                   13213:     }
                   13214:     for(j=1;j <=ncovmodel-2;j++){
                   13215:       if(Typevar[j]==0) {
                   13216:        printf("  +      V%d  ",Tvar[j]);
                   13217:        fprintf(ficres,"  +      V%d  ",Tvar[j]);
                   13218:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   13219:        fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   13220:       }else if(Typevar[j]==1) {
                   13221:        printf("  +    V%d*age ",Tvar[j]);
                   13222:        fprintf(ficres,"  +    V%d*age ",Tvar[j]);
                   13223:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   13224:        fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   13225:       }else if(Typevar[j]==2) {
                   13226:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13227:        fprintf(ficres,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13228:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13229:        fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13230:       }
                   13231:     }
                   13232:     printf("\n");
                   13233:     fprintf(ficres,"\n");
                   13234:     fprintf(ficlog,"\n");
                   13235:     fprintf(fichtm, "</tr>");
                   13236:     fprintf(fichtm, "\n");
                   13237:     
                   13238:     
1.126     brouard  13239:     for(i=1,jk=1; i <=nlstate; i++){
                   13240:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  13241:        if (k != i) {
1.319     brouard  13242:          fprintf(fichtm, "<tr>");
1.225     brouard  13243:          printf("%d%d ",i,k);
                   13244:          fprintf(ficlog,"%d%d ",i,k);
                   13245:          fprintf(ficres,"%1d%1d ",i,k);
1.319     brouard  13246:          fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  13247:          for(j=1; j <=ncovmodel; j++){
                   13248:            printf("%12.7f ",p[jk]);
                   13249:            fprintf(ficlog,"%12.7f ",p[jk]);
                   13250:            fprintf(ficres,"%12.7f ",p[jk]);
1.319     brouard  13251:            fprintf(fichtm, "<td>%12.7f</td>",p[jk]);
1.225     brouard  13252:            jk++; 
                   13253:          }
                   13254:          printf("\n");
                   13255:          fprintf(ficlog,"\n");
                   13256:          fprintf(ficres,"\n");
1.319     brouard  13257:          fprintf(fichtm, "</tr>\n");
1.225     brouard  13258:        }
1.126     brouard  13259:       }
                   13260:     }
1.319     brouard  13261:     /* fprintf(fichtm,"</tr>\n"); */
                   13262:     fprintf(fichtm,"</table>\n");
                   13263:     fprintf(fichtm, "\n");
                   13264: 
1.203     brouard  13265:     if(mle != 0){
                   13266:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  13267:       ftolhess=ftol; /* Usually correct */
1.203     brouard  13268:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   13269:       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");
                   13270:       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  13271:       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  13272:       fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">");
                   13273:       fprintf(fichtm, "\n<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   13274:       if(nagesqr==1){
                   13275:        printf("  + age*age  ");
                   13276:        fprintf(ficres,"  + age*age  ");
                   13277:        fprintf(ficlog,"  + age*age  ");
                   13278:        fprintf(fichtm, "<th>+ age*age</th>");
                   13279:       }
                   13280:       for(j=1;j <=ncovmodel-2;j++){
                   13281:        if(Typevar[j]==0) {
                   13282:          printf("  +      V%d  ",Tvar[j]);
                   13283:          fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   13284:        }else if(Typevar[j]==1) {
                   13285:          printf("  +    V%d*age ",Tvar[j]);
                   13286:          fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   13287:        }else if(Typevar[j]==2) {
                   13288:          fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13289:        }
                   13290:       }
                   13291:       fprintf(fichtm, "</tr>\n");
                   13292:  
1.203     brouard  13293:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  13294:        for(k=1; k <=(nlstate+ndeath); k++){
                   13295:          if (k != i) {
1.319     brouard  13296:            fprintf(fichtm, "<tr valign=top>");
1.225     brouard  13297:            printf("%d%d ",i,k);
                   13298:            fprintf(ficlog,"%d%d ",i,k);
1.319     brouard  13299:            fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  13300:            for(j=1; j <=ncovmodel; j++){
1.319     brouard  13301:              wald=p[jk]/sqrt(matcov[jk][jk]);
1.324     brouard  13302:              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]));
                   13303:              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  13304:              if(fabs(wald) > 1.96){
1.321     brouard  13305:                fprintf(fichtm, "<td><b>%12.7f</b></br> (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
1.319     brouard  13306:              }else{
                   13307:                fprintf(fichtm, "<td>%12.7f (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
                   13308:              }
1.324     brouard  13309:              fprintf(fichtm,"W=%8.3f</br>",wald);
1.319     brouard  13310:              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  13311:              jk++; 
                   13312:            }
                   13313:            printf("\n");
                   13314:            fprintf(ficlog,"\n");
1.319     brouard  13315:            fprintf(fichtm, "</tr>\n");
1.225     brouard  13316:          }
                   13317:        }
1.193     brouard  13318:       }
1.203     brouard  13319:     } /* end of hesscov and Wald tests */
1.319     brouard  13320:     fprintf(fichtm,"</table>\n");
1.225     brouard  13321:     
1.203     brouard  13322:     /*  */
1.126     brouard  13323:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   13324:     printf("# Scales (for hessian or gradient estimation)\n");
                   13325:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   13326:     for(i=1,jk=1; i <=nlstate; i++){
                   13327:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  13328:        if (j!=i) {
                   13329:          fprintf(ficres,"%1d%1d",i,j);
                   13330:          printf("%1d%1d",i,j);
                   13331:          fprintf(ficlog,"%1d%1d",i,j);
                   13332:          for(k=1; k<=ncovmodel;k++){
                   13333:            printf(" %.5e",delti[jk]);
                   13334:            fprintf(ficlog," %.5e",delti[jk]);
                   13335:            fprintf(ficres," %.5e",delti[jk]);
                   13336:            jk++;
                   13337:          }
                   13338:          printf("\n");
                   13339:          fprintf(ficlog,"\n");
                   13340:          fprintf(ficres,"\n");
                   13341:        }
1.126     brouard  13342:       }
                   13343:     }
                   13344:     
                   13345:     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  13346:     if(mle >= 1) /* To big for the screen */
1.126     brouard  13347:       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");
                   13348:     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");
                   13349:     /* # 121 Var(a12)\n\ */
                   13350:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   13351:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   13352:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   13353:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   13354:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   13355:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   13356:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   13357:     
                   13358:     
                   13359:     /* Just to have a covariance matrix which will be more understandable
                   13360:        even is we still don't want to manage dictionary of variables
                   13361:     */
                   13362:     for(itimes=1;itimes<=2;itimes++){
                   13363:       jj=0;
                   13364:       for(i=1; i <=nlstate; i++){
1.225     brouard  13365:        for(j=1; j <=nlstate+ndeath; j++){
                   13366:          if(j==i) continue;
                   13367:          for(k=1; k<=ncovmodel;k++){
                   13368:            jj++;
                   13369:            ca[0]= k+'a'-1;ca[1]='\0';
                   13370:            if(itimes==1){
                   13371:              if(mle>=1)
                   13372:                printf("#%1d%1d%d",i,j,k);
                   13373:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   13374:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   13375:            }else{
                   13376:              if(mle>=1)
                   13377:                printf("%1d%1d%d",i,j,k);
                   13378:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   13379:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   13380:            }
                   13381:            ll=0;
                   13382:            for(li=1;li <=nlstate; li++){
                   13383:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   13384:                if(lj==li) continue;
                   13385:                for(lk=1;lk<=ncovmodel;lk++){
                   13386:                  ll++;
                   13387:                  if(ll<=jj){
                   13388:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   13389:                    if(ll<jj){
                   13390:                      if(itimes==1){
                   13391:                        if(mle>=1)
                   13392:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13393:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13394:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13395:                      }else{
                   13396:                        if(mle>=1)
                   13397:                          printf(" %.5e",matcov[jj][ll]); 
                   13398:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   13399:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   13400:                      }
                   13401:                    }else{
                   13402:                      if(itimes==1){
                   13403:                        if(mle>=1)
                   13404:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   13405:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   13406:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   13407:                      }else{
                   13408:                        if(mle>=1)
                   13409:                          printf(" %.7e",matcov[jj][ll]); 
                   13410:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   13411:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   13412:                      }
                   13413:                    }
                   13414:                  }
                   13415:                } /* end lk */
                   13416:              } /* end lj */
                   13417:            } /* end li */
                   13418:            if(mle>=1)
                   13419:              printf("\n");
                   13420:            fprintf(ficlog,"\n");
                   13421:            fprintf(ficres,"\n");
                   13422:            numlinepar++;
                   13423:          } /* end k*/
                   13424:        } /*end j */
1.126     brouard  13425:       } /* end i */
                   13426:     } /* end itimes */
                   13427:     
                   13428:     fflush(ficlog);
                   13429:     fflush(ficres);
1.225     brouard  13430:     while(fgets(line, MAXLINE, ficpar)) {
                   13431:       /* If line starts with a # it is a comment */
                   13432:       if (line[0] == '#') {
                   13433:        numlinepar++;
                   13434:        fputs(line,stdout);
                   13435:        fputs(line,ficparo);
                   13436:        fputs(line,ficlog);
1.299     brouard  13437:        fputs(line,ficres);
1.225     brouard  13438:        continue;
                   13439:       }else
                   13440:        break;
                   13441:     }
                   13442:     
1.209     brouard  13443:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   13444:     /*   ungetc(c,ficpar); */
                   13445:     /*   fgets(line, MAXLINE, ficpar); */
                   13446:     /*   fputs(line,stdout); */
                   13447:     /*   fputs(line,ficparo); */
                   13448:     /* } */
                   13449:     /* ungetc(c,ficpar); */
1.126     brouard  13450:     
                   13451:     estepm=0;
1.209     brouard  13452:     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  13453:       
                   13454:       if (num_filled != 6) {
                   13455:        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);
                   13456:        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);
                   13457:        goto end;
                   13458:       }
                   13459:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   13460:     }
                   13461:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   13462:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   13463:     
1.209     brouard  13464:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  13465:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   13466:     if (fage <= 2) {
                   13467:       bage = ageminpar;
                   13468:       fage = agemaxpar;
                   13469:     }
                   13470:     
                   13471:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  13472:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   13473:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  13474:                
1.186     brouard  13475:     /* Other stuffs, more or less useful */    
1.254     brouard  13476:     while(fgets(line, MAXLINE, ficpar)) {
                   13477:       /* If line starts with a # it is a comment */
                   13478:       if (line[0] == '#') {
                   13479:        numlinepar++;
                   13480:        fputs(line,stdout);
                   13481:        fputs(line,ficparo);
                   13482:        fputs(line,ficlog);
1.299     brouard  13483:        fputs(line,ficres);
1.254     brouard  13484:        continue;
                   13485:       }else
                   13486:        break;
                   13487:     }
                   13488: 
                   13489:     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){
                   13490:       
                   13491:       if (num_filled != 7) {
                   13492:        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);
                   13493:        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);
                   13494:        goto end;
                   13495:       }
                   13496:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   13497:       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);
                   13498:       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);
                   13499:       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  13500:     }
1.254     brouard  13501: 
                   13502:     while(fgets(line, MAXLINE, ficpar)) {
                   13503:       /* If line starts with a # it is a comment */
                   13504:       if (line[0] == '#') {
                   13505:        numlinepar++;
                   13506:        fputs(line,stdout);
                   13507:        fputs(line,ficparo);
                   13508:        fputs(line,ficlog);
1.299     brouard  13509:        fputs(line,ficres);
1.254     brouard  13510:        continue;
                   13511:       }else
                   13512:        break;
1.126     brouard  13513:     }
                   13514:     
                   13515:     
                   13516:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   13517:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   13518:     
1.254     brouard  13519:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   13520:       if (num_filled != 1) {
                   13521:        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);
                   13522:        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);
                   13523:        goto end;
                   13524:       }
                   13525:       printf("pop_based=%d\n",popbased);
                   13526:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   13527:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   13528:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   13529:     }
                   13530:      
1.258     brouard  13531:     /* Results */
1.332     brouard  13532:     /* Value of covariate in each resultine will be compututed (if product) and sorted according to model rank */
                   13533:     /* It is precov[] because we need the varying age in order to compute the real cov[] of the model equation */  
                   13534:     precov=matrix(1,MAXRESULTLINESPONE,1,NCOVMAX+1);
1.307     brouard  13535:     endishere=0;
1.258     brouard  13536:     nresult=0;
1.308     brouard  13537:     parameterline=0;
1.258     brouard  13538:     do{
                   13539:       if(!fgets(line, MAXLINE, ficpar)){
                   13540:        endishere=1;
1.308     brouard  13541:        parameterline=15;
1.258     brouard  13542:       }else if (line[0] == '#') {
                   13543:        /* If line starts with a # it is a comment */
1.254     brouard  13544:        numlinepar++;
                   13545:        fputs(line,stdout);
                   13546:        fputs(line,ficparo);
                   13547:        fputs(line,ficlog);
1.299     brouard  13548:        fputs(line,ficres);
1.254     brouard  13549:        continue;
1.258     brouard  13550:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   13551:        parameterline=11;
1.296     brouard  13552:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  13553:        parameterline=12;
1.307     brouard  13554:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
1.258     brouard  13555:        parameterline=13;
1.307     brouard  13556:       }
1.258     brouard  13557:       else{
                   13558:        parameterline=14;
1.254     brouard  13559:       }
1.308     brouard  13560:       switch (parameterline){ /* =0 only if only comments */
1.258     brouard  13561:       case 11:
1.296     brouard  13562:        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)){
                   13563:                  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  13564:          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);
                   13565:          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);
                   13566:          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);
                   13567:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  13568:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   13569:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  13570:           prvforecast = 1;
                   13571:        } 
                   13572:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.313     brouard  13573:          printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   13574:          fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   13575:          fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  13576:           prvforecast = 2;
                   13577:        }
                   13578:        else {
                   13579:          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);
                   13580:          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);
                   13581:          goto end;
1.258     brouard  13582:        }
1.254     brouard  13583:        break;
1.258     brouard  13584:       case 12:
1.296     brouard  13585:        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)){
                   13586:           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);
                   13587:          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);
                   13588:          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);
                   13589:          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);
                   13590:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  13591:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   13592:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  13593:           prvbackcast = 1;
                   13594:        } 
                   13595:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.313     brouard  13596:          printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   13597:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   13598:          fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  13599:           prvbackcast = 2;
                   13600:        }
                   13601:        else {
                   13602:          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);
                   13603:          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);
                   13604:          goto end;
1.258     brouard  13605:        }
1.230     brouard  13606:        break;
1.258     brouard  13607:       case 13:
1.332     brouard  13608:        num_filled=sscanf(line,"result:%[^\n]\n",resultlineori);
1.307     brouard  13609:        nresult++; /* Sum of resultlines */
1.332     brouard  13610:        printf("Result %d: result:%s\n",nresult, resultlineori);
                   13611:        /* removefirstspace(&resultlineori); */
                   13612:        
                   13613:        if(strstr(resultlineori,"v") !=0){
                   13614:          printf("Error. 'v' must be in upper case 'V' result: %s ",resultlineori);
                   13615:          fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultlineori);fflush(ficlog);
                   13616:          return 1;
                   13617:        }
                   13618:        trimbb(resultline, resultlineori); /* Suppressing double blank in the resultline */
                   13619:        printf("Decoderesult resultline=\"%s\" resultlineori=\"%s\"\n", resultline, resultlineori);
1.318     brouard  13620:        if(nresult > MAXRESULTLINESPONE-1){
                   13621:          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);
                   13622:          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  13623:          goto end;
                   13624:        }
1.332     brouard  13625:        
1.310     brouard  13626:        if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.314     brouard  13627:          fprintf(ficparo,"result: %s\n",resultline);
                   13628:          fprintf(ficres,"result: %s\n",resultline);
                   13629:          fprintf(ficlog,"result: %s\n",resultline);
1.310     brouard  13630:        } else
                   13631:          goto end;
1.307     brouard  13632:        break;
                   13633:       case 14:
                   13634:        printf("Error: Unknown command '%s'\n",line);
                   13635:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
1.314     brouard  13636:        if(line[0] == ' ' || line[0] == '\n'){
                   13637:          printf("It should not be an empty line '%s'\n",line);
                   13638:          fprintf(ficlog,"It should not be an empty line '%s'\n",line);
                   13639:        }         
1.307     brouard  13640:        if(ncovmodel >=2 && nresult==0 ){
                   13641:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   13642:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  13643:        }
1.307     brouard  13644:        /* goto end; */
                   13645:        break;
1.308     brouard  13646:       case 15:
                   13647:        printf("End of resultlines.\n");
                   13648:        fprintf(ficlog,"End of resultlines.\n");
                   13649:        break;
                   13650:       default: /* parameterline =0 */
1.307     brouard  13651:        nresult=1;
                   13652:        decoderesult(".",nresult ); /* No covariate */
1.258     brouard  13653:       } /* End switch parameterline */
                   13654:     }while(endishere==0); /* End do */
1.126     brouard  13655:     
1.230     brouard  13656:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  13657:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  13658:     
                   13659:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  13660:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  13661:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  13662: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13663: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  13664:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  13665: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13666: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  13667:     }else{
1.270     brouard  13668:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  13669:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   13670:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   13671:       if(prvforecast==1){
                   13672:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   13673:         jprojd=jproj1;
                   13674:         mprojd=mproj1;
                   13675:         anprojd=anproj1;
                   13676:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   13677:         jprojf=jproj2;
                   13678:         mprojf=mproj2;
                   13679:         anprojf=anproj2;
                   13680:       } else if(prvforecast == 2){
                   13681:         dateprojd=dateintmean;
                   13682:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   13683:         dateprojf=dateintmean+yrfproj;
                   13684:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   13685:       }
                   13686:       if(prvbackcast==1){
                   13687:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   13688:         jbackd=jback1;
                   13689:         mbackd=mback1;
                   13690:         anbackd=anback1;
                   13691:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   13692:         jbackf=jback2;
                   13693:         mbackf=mback2;
                   13694:         anbackf=anback2;
                   13695:       } else if(prvbackcast == 2){
                   13696:         datebackd=dateintmean;
                   13697:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   13698:         datebackf=dateintmean-yrbproj;
                   13699:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   13700:       }
                   13701:       
                   13702:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);
1.220     brouard  13703:     }
                   13704:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  13705:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   13706:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  13707:                
1.225     brouard  13708:     /*------------ free_vector  -------------*/
                   13709:     /*  chdir(path); */
1.220     brouard  13710:                
1.215     brouard  13711:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   13712:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   13713:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   13714:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  13715:     free_lvector(num,firstobs,lastobs);
                   13716:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  13717:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   13718:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   13719:     fclose(ficparo);
                   13720:     fclose(ficres);
1.220     brouard  13721:                
                   13722:                
1.186     brouard  13723:     /* Other results (useful)*/
1.220     brouard  13724:                
                   13725:                
1.126     brouard  13726:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  13727:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   13728:     prlim=matrix(1,nlstate,1,nlstate);
1.332     brouard  13729:     /* Computes the prevalence limit for each combination k of the dummy covariates by calling prevalim(k) */
1.209     brouard  13730:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  13731:     fclose(ficrespl);
                   13732: 
                   13733:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  13734:     /*#include "hpijx.h"*/
1.332     brouard  13735:     /** 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?*/
                   13736:     /* calls hpxij with combination k */
1.180     brouard  13737:     hPijx(p, bage, fage);
1.145     brouard  13738:     fclose(ficrespij);
1.227     brouard  13739:     
1.220     brouard  13740:     /* ncovcombmax=  pow(2,cptcoveff); */
1.332     brouard  13741:     /*-------------- Variance of one-step probabilities for a combination ij or for nres ?---*/
1.145     brouard  13742:     k=1;
1.126     brouard  13743:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  13744:     
1.269     brouard  13745:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   13746:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   13747:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  13748:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  13749:        for(k=1;k<=ncovcombmax;k++)
                   13750:          probs[i][j][k]=0.;
1.269     brouard  13751:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   13752:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  13753:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  13754:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   13755:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  13756:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  13757:          for(k=1;k<=ncovcombmax;k++)
                   13758:            mobaverages[i][j][k]=0.;
1.219     brouard  13759:       mobaverage=mobaverages;
                   13760:       if (mobilav!=0) {
1.235     brouard  13761:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  13762:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  13763:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   13764:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   13765:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   13766:        }
1.269     brouard  13767:       } else if (mobilavproj !=0) {
1.235     brouard  13768:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  13769:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  13770:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   13771:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   13772:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   13773:        }
1.269     brouard  13774:       }else{
                   13775:        printf("Internal error moving average\n");
                   13776:        fflush(stdout);
                   13777:        exit(1);
1.219     brouard  13778:       }
                   13779:     }/* end if moving average */
1.227     brouard  13780:     
1.126     brouard  13781:     /*---------- Forecasting ------------------*/
1.296     brouard  13782:     if(prevfcast==1){ 
                   13783:       /*   /\*    if(stepm ==1){*\/ */
                   13784:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   13785:       /*This done previously after freqsummary.*/
                   13786:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   13787:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   13788:       
                   13789:       /* } else if (prvforecast==2){ */
                   13790:       /*   /\*    if(stepm ==1){*\/ */
                   13791:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   13792:       /* } */
                   13793:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   13794:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  13795:     }
1.269     brouard  13796: 
1.296     brouard  13797:     /* Prevbcasting */
                   13798:     if(prevbcast==1){
1.219     brouard  13799:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   13800:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   13801:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   13802: 
                   13803:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   13804: 
                   13805:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  13806: 
1.219     brouard  13807:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   13808:       fclose(ficresplb);
                   13809: 
1.222     brouard  13810:       hBijx(p, bage, fage, mobaverage);
                   13811:       fclose(ficrespijb);
1.219     brouard  13812: 
1.296     brouard  13813:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   13814:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   13815:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   13816:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   13817:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   13818:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   13819: 
                   13820:       
1.269     brouard  13821:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  13822: 
                   13823:       
1.269     brouard  13824:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  13825:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   13826:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   13827:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  13828:     }    /* end  Prevbcasting */
1.268     brouard  13829:  
1.186     brouard  13830:  
                   13831:     /* ------ Other prevalence ratios------------ */
1.126     brouard  13832: 
1.215     brouard  13833:     free_ivector(wav,1,imx);
                   13834:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   13835:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   13836:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  13837:                
                   13838:                
1.127     brouard  13839:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  13840:                
1.201     brouard  13841:     strcpy(filerese,"E_");
                   13842:     strcat(filerese,fileresu);
1.126     brouard  13843:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   13844:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   13845:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   13846:     }
1.208     brouard  13847:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   13848:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  13849: 
                   13850:     pstamp(ficreseij);
1.219     brouard  13851:                
1.235     brouard  13852:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   13853:     if (cptcovn < 1){i1=1;}
                   13854:     
                   13855:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   13856:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  13857:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  13858:        continue;
1.219     brouard  13859:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  13860:       printf("\n#****** ");
1.225     brouard  13861:       for(j=1;j<=cptcoveff;j++) {
1.332     brouard  13862:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   13863:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.235     brouard  13864:       }
                   13865:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.337   ! brouard  13866:        printf(" V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]); /* TvarsQ[j] gives the name of the jth quantitative (fixed or time v) */
        !          13867:        fprintf(ficreseij,"V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]);
1.219     brouard  13868:       }
                   13869:       fprintf(ficreseij,"******\n");
1.235     brouard  13870:       printf("******\n");
1.219     brouard  13871:       
                   13872:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   13873:       oldm=oldms;savm=savms;
1.330     brouard  13874:       /* 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  13875:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  13876:       
1.219     brouard  13877:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  13878:     }
                   13879:     fclose(ficreseij);
1.208     brouard  13880:     printf("done evsij\n");fflush(stdout);
                   13881:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  13882: 
1.218     brouard  13883:                
1.227     brouard  13884:     /*---------- State-specific expectancies and variances ------------*/
1.336     brouard  13885:     /* Should be moved in a function */                
1.201     brouard  13886:     strcpy(filerest,"T_");
                   13887:     strcat(filerest,fileresu);
1.127     brouard  13888:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   13889:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   13890:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   13891:     }
1.208     brouard  13892:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   13893:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  13894:     strcpy(fileresstde,"STDE_");
                   13895:     strcat(fileresstde,fileresu);
1.126     brouard  13896:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  13897:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   13898:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  13899:     }
1.227     brouard  13900:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   13901:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  13902: 
1.201     brouard  13903:     strcpy(filerescve,"CVE_");
                   13904:     strcat(filerescve,fileresu);
1.126     brouard  13905:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  13906:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   13907:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  13908:     }
1.227     brouard  13909:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   13910:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  13911: 
1.201     brouard  13912:     strcpy(fileresv,"V_");
                   13913:     strcat(fileresv,fileresu);
1.126     brouard  13914:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   13915:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   13916:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   13917:     }
1.227     brouard  13918:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   13919:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  13920: 
1.235     brouard  13921:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   13922:     if (cptcovn < 1){i1=1;}
                   13923:     
1.334     brouard  13924:     for(nres=1; nres <= nresult; nres++) /* For each resultline, find the combination and output results according to the values of dummies and then quanti.  */
                   13925:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying. For each nres and each value at position k
                   13926:                          * we know Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline
                   13927:                          * Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline 
                   13928:                          * and Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
                   13929:       /* */
                   13930:       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  13931:        continue;
1.321     brouard  13932:       printf("\n# model %s \n#****** Result for:", model);
                   13933:       fprintf(ficrest,"\n# model %s \n#****** Result for:", model);
                   13934:       fprintf(ficlog,"\n# model %s \n#****** Result for:", model);
1.334     brouard  13935:       /* It might not be a good idea to mix dummies and quantitative */
                   13936:       /* 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 *\/ */
                   13937:       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 */
                   13938:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* Output by variables in the resultline *\/ */
                   13939:        /* Tvaraff[j] is the name of the dummy variable in position j in the equation model:
                   13940:         * Tvaraff[1]@9={4, 3, 0, 0, 0, 0, 0, 0, 0}, in model=V5+V4+V3+V4*V3+V5*age
                   13941:         * (V5 is quanti) V4 and V3 are dummies
                   13942:         * TnsdVar[4] is the position 1 and TnsdVar[3]=2 in codtabm(k,l)(V4  V3)=V4  V3
                   13943:         *                                                              l=1 l=2
                   13944:         *                                                           k=1  1   1   0   0
                   13945:         *                                                           k=2  2   1   1   0
                   13946:         *                                                           k=3 [1] [2]  0   1
                   13947:         *                                                           k=4  2   2   1   1
                   13948:         * If nres=1 result: V3=1 V4=0 then k=3 and outputs
                   13949:         * If nres=2 result: V4=1 V3=0 then k=2 and outputs
                   13950:         * nres=1 =>k=3 j=1 V4= nbcode[4][codtabm(3,1)=1)=0; j=2  V3= nbcode[3][codtabm(3,2)=2]=1
                   13951:         * nres=2 =>k=2 j=1 V4= nbcode[4][codtabm(2,1)=2)=1; j=2  V3= nbcode[3][codtabm(2,2)=1]=0
                   13952:         */
                   13953:        /* Tvresult[nres][j] Name of the variable at position j in this resultline */
                   13954:        /* Tresult[nres][j] Value of this variable at position j could be a float if quantitative  */
                   13955: /* We give up with the combinations!! */
                   13956:        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 */
                   13957: 
                   13958:        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  13959:          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  */
        !          13960:          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  */
        !          13961:          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  13962:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   13963:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   13964:          }else{
                   13965:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   13966:          }
                   13967:          /* fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   13968:          /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   13969:        }else if(Dummy[modelresult[nres][j]]==1){ /* Quanti variable */
                   13970:          /* For each selected (single) quantitative value */
1.337   ! brouard  13971:          printf(" V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
        !          13972:          fprintf(ficlog," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
        !          13973:          fprintf(ficrest," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
1.334     brouard  13974:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   13975:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   13976:          }else{
                   13977:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   13978:          }
                   13979:        }else{
                   13980:          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 */
                   13981:          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 */
                   13982:          exit(1);
                   13983:        }
1.335     brouard  13984:       } /* End loop for each variable in the resultline */
1.334     brouard  13985:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   13986:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /\* Wrong j is not in the equation model *\/ */
                   13987:       /*       fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   13988:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   13989:       /* }      */
1.208     brouard  13990:       fprintf(ficrest,"******\n");
1.227     brouard  13991:       fprintf(ficlog,"******\n");
                   13992:       printf("******\n");
1.208     brouard  13993:       
                   13994:       fprintf(ficresstdeij,"\n#****** ");
                   13995:       fprintf(ficrescveij,"\n#****** ");
1.337   ! brouard  13996:       /* It could have been: for(j=1;j<=cptcoveff;j++) {printf("V=%d=%lg",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);} */
        !          13997:       /* But it won't be sorted and depends on how the resultline is ordered */
1.225     brouard  13998:       for(j=1;j<=cptcoveff;j++) {
1.334     brouard  13999:        fprintf(ficresstdeij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   14000:        /* fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14001:        /* fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14002:       }
                   14003:       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  14004:        fprintf(ficresstdeij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
        !          14005:        fprintf(ficrescveij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
1.235     brouard  14006:       }        
1.208     brouard  14007:       fprintf(ficresstdeij,"******\n");
                   14008:       fprintf(ficrescveij,"******\n");
                   14009:       
                   14010:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  14011:       /* pstamp(ficresvij); */
1.225     brouard  14012:       for(j=1;j<=cptcoveff;j++) 
1.335     brouard  14013:        fprintf(ficresvij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   14014:        /* fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[TnsdVar[Tvaraff[j]]])]); */
1.235     brouard  14015:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  14016:        /* fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]); /\* To solve *\/ */
1.337   ! brouard  14017:        fprintf(ficresvij," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /* Solved */
1.235     brouard  14018:       }        
1.208     brouard  14019:       fprintf(ficresvij,"******\n");
                   14020:       
                   14021:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   14022:       oldm=oldms;savm=savms;
1.235     brouard  14023:       printf(" cvevsij ");
                   14024:       fprintf(ficlog, " cvevsij ");
                   14025:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  14026:       printf(" end cvevsij \n ");
                   14027:       fprintf(ficlog, " end cvevsij \n ");
                   14028:       
                   14029:       /*
                   14030:        */
                   14031:       /* goto endfree; */
                   14032:       
                   14033:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   14034:       pstamp(ficrest);
                   14035:       
1.269     brouard  14036:       epj=vector(1,nlstate+1);
1.208     brouard  14037:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  14038:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   14039:        cptcod= 0; /* To be deleted */
                   14040:        printf("varevsij vpopbased=%d \n",vpopbased);
                   14041:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  14042:        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  14043:        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 ");
                   14044:        if(vpopbased==1)
                   14045:          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);
                   14046:        else
1.288     brouard  14047:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
1.335     brouard  14048:        fprintf(ficrest,"# Age popbased mobilav e.. (std) "); /* Adding covariate values? */
1.227     brouard  14049:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   14050:        fprintf(ficrest,"\n");
                   14051:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  14052:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   14053:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  14054:        for(age=bage; age <=fage ;age++){
1.235     brouard  14055:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  14056:          if (vpopbased==1) {
                   14057:            if(mobilav ==0){
                   14058:              for(i=1; i<=nlstate;i++)
                   14059:                prlim[i][i]=probs[(int)age][i][k];
                   14060:            }else{ /* mobilav */ 
                   14061:              for(i=1; i<=nlstate;i++)
                   14062:                prlim[i][i]=mobaverage[(int)age][i][k];
                   14063:            }
                   14064:          }
1.219     brouard  14065:          
1.227     brouard  14066:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   14067:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   14068:          /* printf(" age %4.0f ",age); */
                   14069:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   14070:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   14071:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   14072:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   14073:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   14074:            }
                   14075:            epj[nlstate+1] +=epj[j];
                   14076:          }
                   14077:          /* printf(" age %4.0f \n",age); */
1.219     brouard  14078:          
1.227     brouard  14079:          for(i=1, vepp=0.;i <=nlstate;i++)
                   14080:            for(j=1;j <=nlstate;j++)
                   14081:              vepp += vareij[i][j][(int)age];
                   14082:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   14083:          for(j=1;j <=nlstate;j++){
                   14084:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   14085:          }
                   14086:          fprintf(ficrest,"\n");
                   14087:        }
1.208     brouard  14088:       } /* End vpopbased */
1.269     brouard  14089:       free_vector(epj,1,nlstate+1);
1.208     brouard  14090:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   14091:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  14092:       printf("done selection\n");fflush(stdout);
                   14093:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  14094:       
1.335     brouard  14095:     } /* End k selection or end covariate selection for nres */
1.227     brouard  14096: 
                   14097:     printf("done State-specific expectancies\n");fflush(stdout);
                   14098:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   14099: 
1.335     brouard  14100:     /* variance-covariance of forward period prevalence */
1.269     brouard  14101:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  14102: 
1.227     brouard  14103:     
1.290     brouard  14104:     free_vector(weight,firstobs,lastobs);
1.330     brouard  14105:     free_imatrix(Tvardk,1,NCOVMAX,1,2);
1.227     brouard  14106:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  14107:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   14108:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   14109:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   14110:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  14111:     free_ivector(tab,1,NCOVMAX);
                   14112:     fclose(ficresstdeij);
                   14113:     fclose(ficrescveij);
                   14114:     fclose(ficresvij);
                   14115:     fclose(ficrest);
                   14116:     fclose(ficpar);
                   14117:     
                   14118:     
1.126     brouard  14119:     /*---------- End : free ----------------*/
1.219     brouard  14120:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  14121:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   14122:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  14123:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   14124:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  14125:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  14126:   /* endfree:*/
                   14127:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   14128:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   14129:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.290     brouard  14130:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs);
                   14131:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   14132:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   14133:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  14134:   free_matrix(matcov,1,npar,1,npar);
                   14135:   free_matrix(hess,1,npar,1,npar);
                   14136:   /*free_vector(delti,1,npar);*/
                   14137:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   14138:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  14139:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  14140:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   14141:   
                   14142:   free_ivector(ncodemax,1,NCOVMAX);
                   14143:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   14144:   free_ivector(Dummy,-1,NCOVMAX);
                   14145:   free_ivector(Fixed,-1,NCOVMAX);
1.238     brouard  14146:   free_ivector(DummyV,1,NCOVMAX);
                   14147:   free_ivector(FixedV,1,NCOVMAX);
1.227     brouard  14148:   free_ivector(Typevar,-1,NCOVMAX);
                   14149:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  14150:   free_ivector(TvarsQ,1,NCOVMAX);
                   14151:   free_ivector(TvarsQind,1,NCOVMAX);
                   14152:   free_ivector(TvarsD,1,NCOVMAX);
1.330     brouard  14153:   free_ivector(TnsdVar,1,NCOVMAX);
1.234     brouard  14154:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  14155:   free_ivector(TvarFD,1,NCOVMAX);
                   14156:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  14157:   free_ivector(TvarF,1,NCOVMAX);
                   14158:   free_ivector(TvarFind,1,NCOVMAX);
                   14159:   free_ivector(TvarV,1,NCOVMAX);
                   14160:   free_ivector(TvarVind,1,NCOVMAX);
                   14161:   free_ivector(TvarA,1,NCOVMAX);
                   14162:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  14163:   free_ivector(TvarFQ,1,NCOVMAX);
                   14164:   free_ivector(TvarFQind,1,NCOVMAX);
                   14165:   free_ivector(TvarVD,1,NCOVMAX);
                   14166:   free_ivector(TvarVDind,1,NCOVMAX);
                   14167:   free_ivector(TvarVQ,1,NCOVMAX);
                   14168:   free_ivector(TvarVQind,1,NCOVMAX);
1.230     brouard  14169:   free_ivector(Tvarsel,1,NCOVMAX);
                   14170:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  14171:   free_ivector(Tposprod,1,NCOVMAX);
                   14172:   free_ivector(Tprod,1,NCOVMAX);
                   14173:   free_ivector(Tvaraff,1,NCOVMAX);
                   14174:   free_ivector(invalidvarcomb,1,ncovcombmax);
                   14175:   free_ivector(Tage,1,NCOVMAX);
                   14176:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  14177:   free_ivector(TmodelInvind,1,NCOVMAX);
                   14178:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.332     brouard  14179: 
                   14180:   free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /* Could be elsewhere ?*/
                   14181: 
1.227     brouard  14182:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   14183:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  14184:   fflush(fichtm);
                   14185:   fflush(ficgp);
                   14186:   
1.227     brouard  14187:   
1.126     brouard  14188:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  14189:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   14190:     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  14191:   }else{
                   14192:     printf("End of Imach\n");
                   14193:     fprintf(ficlog,"End of Imach\n");
                   14194:   }
                   14195:   printf("See log file on %s\n",filelog);
                   14196:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  14197:   /*(void) gettimeofday(&end_time,&tzp);*/
                   14198:   rend_time = time(NULL);  
                   14199:   end_time = *localtime(&rend_time);
                   14200:   /* tml = *localtime(&end_time.tm_sec); */
                   14201:   strcpy(strtend,asctime(&end_time));
1.126     brouard  14202:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   14203:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  14204:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  14205:   
1.157     brouard  14206:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   14207:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   14208:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  14209:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   14210: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   14211:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   14212:   fclose(fichtm);
                   14213:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   14214:   fclose(fichtmcov);
                   14215:   fclose(ficgp);
                   14216:   fclose(ficlog);
                   14217:   /*------ End -----------*/
1.227     brouard  14218:   
1.281     brouard  14219: 
                   14220: /* Executes gnuplot */
1.227     brouard  14221:   
                   14222:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  14223: #ifdef WIN32
1.227     brouard  14224:   if (_chdir(pathcd) != 0)
                   14225:     printf("Can't move to directory %s!\n",path);
                   14226:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  14227: #else
1.227     brouard  14228:     if(chdir(pathcd) != 0)
                   14229:       printf("Can't move to directory %s!\n", path);
                   14230:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  14231: #endif 
1.126     brouard  14232:     printf("Current directory %s!\n",pathcd);
                   14233:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   14234:   sprintf(plotcmd,"gnuplot");
1.157     brouard  14235: #ifdef _WIN32
1.126     brouard  14236:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   14237: #endif
                   14238:   if(!stat(plotcmd,&info)){
1.158     brouard  14239:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  14240:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  14241:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  14242:     }else
                   14243:       strcpy(pplotcmd,plotcmd);
1.157     brouard  14244: #ifdef __unix
1.126     brouard  14245:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   14246:     if(!stat(plotcmd,&info)){
1.158     brouard  14247:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  14248:     }else
                   14249:       strcpy(pplotcmd,plotcmd);
                   14250: #endif
                   14251:   }else
                   14252:     strcpy(pplotcmd,plotcmd);
                   14253:   
                   14254:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  14255:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  14256:   strcpy(pplotcmd,plotcmd);
1.227     brouard  14257:   
1.126     brouard  14258:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  14259:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  14260:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  14261:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  14262:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  14263:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  14264:       strcpy(plotcmd,pplotcmd);
                   14265:     }
1.126     brouard  14266:   }
1.158     brouard  14267:   printf(" Successful, please wait...");
1.126     brouard  14268:   while (z[0] != 'q') {
                   14269:     /* chdir(path); */
1.154     brouard  14270:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  14271:     scanf("%s",z);
                   14272: /*     if (z[0] == 'c') system("./imach"); */
                   14273:     if (z[0] == 'e') {
1.158     brouard  14274: #ifdef __APPLE__
1.152     brouard  14275:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  14276: #elif __linux
                   14277:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  14278: #else
1.152     brouard  14279:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  14280: #endif
                   14281:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   14282:       system(pplotcmd);
1.126     brouard  14283:     }
                   14284:     else if (z[0] == 'g') system(plotcmd);
                   14285:     else if (z[0] == 'q') exit(0);
                   14286:   }
1.227     brouard  14287: end:
1.126     brouard  14288:   while (z[0] != 'q') {
1.195     brouard  14289:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  14290:     scanf("%s",z);
                   14291:   }
1.283     brouard  14292:   printf("End\n");
1.282     brouard  14293:   exit(0);
1.126     brouard  14294: }

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