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

1.331   ! brouard     1: /* $Id: imach.c,v 1.330 2022/08/06 07:18:25 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.331   ! brouard     4:   Revision 1.330  2022/08/06 07:18:25  brouard
        !             5:   Summary: last 0.99r31
        !             6: 
        !             7:   *  imach.c (Module): Version of imach using partly decoderesult to rebuild xpxij function
        !             8: 
1.330     brouard     9:   Revision 1.329  2022/08/03 17:29:54  brouard
                     10:   *  imach.c (Module): Many errors in graphs fixed with Vn*age covariates.
                     11: 
1.329     brouard    12:   Revision 1.328  2022/07/27 17:40:48  brouard
                     13:   Summary: valgrind bug fixed by initializing to zero DummyV as well as Tage
                     14: 
1.328     brouard    15:   Revision 1.327  2022/07/27 14:47:35  brouard
                     16:   Summary: Still a problem for one-step probabilities in case of quantitative variables
                     17: 
1.327     brouard    18:   Revision 1.326  2022/07/26 17:33:55  brouard
                     19:   Summary: some test with nres=1
                     20: 
1.326     brouard    21:   Revision 1.325  2022/07/25 14:27:23  brouard
                     22:   Summary: r30
                     23: 
                     24:   * imach.c (Module): Error cptcovn instead of nsd in bmij (was
                     25:   coredumped, revealed by Feiuno, thank you.
                     26: 
1.325     brouard    27:   Revision 1.324  2022/07/23 17:44:26  brouard
                     28:   *** empty log message ***
                     29: 
1.324     brouard    30:   Revision 1.323  2022/07/22 12:30:08  brouard
                     31:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                     32: 
1.323     brouard    33:   Revision 1.322  2022/07/22 12:27:48  brouard
                     34:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                     35: 
1.322     brouard    36:   Revision 1.321  2022/07/22 12:04:24  brouard
                     37:   Summary: r28
                     38: 
                     39:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                     40: 
1.321     brouard    41:   Revision 1.320  2022/06/02 05:10:11  brouard
                     42:   *** empty log message ***
                     43: 
1.320     brouard    44:   Revision 1.319  2022/06/02 04:45:11  brouard
                     45:   * imach.c (Module): Adding the Wald tests from the log to the main
                     46:   htm for better display of the maximum likelihood estimators.
                     47: 
1.319     brouard    48:   Revision 1.318  2022/05/24 08:10:59  brouard
                     49:   * imach.c (Module): Some attempts to find a bug of wrong estimates
                     50:   of confidencce intervals with product in the equation modelC
                     51: 
1.318     brouard    52:   Revision 1.317  2022/05/15 15:06:23  brouard
                     53:   * imach.c (Module):  Some minor improvements
                     54: 
1.317     brouard    55:   Revision 1.316  2022/05/11 15:11:31  brouard
                     56:   Summary: r27
                     57: 
1.316     brouard    58:   Revision 1.315  2022/05/11 15:06:32  brouard
                     59:   *** empty log message ***
                     60: 
1.315     brouard    61:   Revision 1.314  2022/04/13 17:43:09  brouard
                     62:   * imach.c (Module): Adding link to text data files
                     63: 
1.314     brouard    64:   Revision 1.313  2022/04/11 15:57:42  brouard
                     65:   * imach.c (Module): Error in rewriting the 'r' file with yearsfproj or yearsbproj fixed
                     66: 
1.313     brouard    67:   Revision 1.312  2022/04/05 21:24:39  brouard
                     68:   *** empty log message ***
                     69: 
1.312     brouard    70:   Revision 1.311  2022/04/05 21:03:51  brouard
                     71:   Summary: Fixed quantitative covariates
                     72: 
                     73:          Fixed covariates (dummy or quantitative)
                     74:        with missing values have never been allowed but are ERRORS and
                     75:        program quits. Standard deviations of fixed covariates were
                     76:        wrongly computed. Mean and standard deviations of time varying
                     77:        covariates are still not computed.
                     78: 
1.311     brouard    79:   Revision 1.310  2022/03/17 08:45:53  brouard
                     80:   Summary: 99r25
                     81: 
                     82:   Improving detection of errors: result lines should be compatible with
                     83:   the model.
                     84: 
1.310     brouard    85:   Revision 1.309  2021/05/20 12:39:14  brouard
                     86:   Summary: Version 0.99r24
                     87: 
1.309     brouard    88:   Revision 1.308  2021/03/31 13:11:57  brouard
                     89:   Summary: Version 0.99r23
                     90: 
                     91: 
                     92:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
                     93: 
1.308     brouard    94:   Revision 1.307  2021/03/08 18:11:32  brouard
                     95:   Summary: 0.99r22 fixed bug on result:
                     96: 
1.307     brouard    97:   Revision 1.306  2021/02/20 15:44:02  brouard
                     98:   Summary: Version 0.99r21
                     99: 
                    100:   * imach.c (Module): Fix bug on quitting after result lines!
                    101:   (Module): Version 0.99r21
                    102: 
1.306     brouard   103:   Revision 1.305  2021/02/20 15:28:30  brouard
                    104:   * imach.c (Module): Fix bug on quitting after result lines!
                    105: 
1.305     brouard   106:   Revision 1.304  2021/02/12 11:34:20  brouard
                    107:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
                    108: 
1.304     brouard   109:   Revision 1.303  2021/02/11 19:50:15  brouard
                    110:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
                    111: 
1.303     brouard   112:   Revision 1.302  2020/02/22 21:00:05  brouard
                    113:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
                    114:   and life table from the data without any state)
                    115: 
1.302     brouard   116:   Revision 1.301  2019/06/04 13:51:20  brouard
                    117:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                    118: 
1.301     brouard   119:   Revision 1.300  2019/05/22 19:09:45  brouard
                    120:   Summary: version 0.99r19 of May 2019
                    121: 
1.300     brouard   122:   Revision 1.299  2019/05/22 18:37:08  brouard
                    123:   Summary: Cleaned 0.99r19
                    124: 
1.299     brouard   125:   Revision 1.298  2019/05/22 18:19:56  brouard
                    126:   *** empty log message ***
                    127: 
1.298     brouard   128:   Revision 1.297  2019/05/22 17:56:10  brouard
                    129:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                    130: 
1.297     brouard   131:   Revision 1.296  2019/05/20 13:03:18  brouard
                    132:   Summary: Projection syntax simplified
                    133: 
                    134: 
                    135:   We can now start projections, forward or backward, from the mean date
                    136:   of inteviews up to or down to a number of years of projection:
                    137:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                    138:   or
                    139:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                    140:   or
                    141:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                    142:   or
                    143:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                    144: 
1.296     brouard   145:   Revision 1.295  2019/05/18 09:52:50  brouard
                    146:   Summary: doxygen tex bug
                    147: 
1.295     brouard   148:   Revision 1.294  2019/05/16 14:54:33  brouard
                    149:   Summary: There was some wrong lines added
                    150: 
1.294     brouard   151:   Revision 1.293  2019/05/09 15:17:34  brouard
                    152:   *** empty log message ***
                    153: 
1.293     brouard   154:   Revision 1.292  2019/05/09 14:17:20  brouard
                    155:   Summary: Some updates
                    156: 
1.292     brouard   157:   Revision 1.291  2019/05/09 13:44:18  brouard
                    158:   Summary: Before ncovmax
                    159: 
1.291     brouard   160:   Revision 1.290  2019/05/09 13:39:37  brouard
                    161:   Summary: 0.99r18 unlimited number of individuals
                    162: 
                    163:   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.
                    164: 
1.290     brouard   165:   Revision 1.289  2018/12/13 09:16:26  brouard
                    166:   Summary: Bug for young ages (<-30) will be in r17
                    167: 
1.289     brouard   168:   Revision 1.288  2018/05/02 20:58:27  brouard
                    169:   Summary: Some bugs fixed
                    170: 
1.288     brouard   171:   Revision 1.287  2018/05/01 17:57:25  brouard
                    172:   Summary: Bug fixed by providing frequencies only for non missing covariates
                    173: 
1.287     brouard   174:   Revision 1.286  2018/04/27 14:27:04  brouard
                    175:   Summary: some minor bugs
                    176: 
1.286     brouard   177:   Revision 1.285  2018/04/21 21:02:16  brouard
                    178:   Summary: Some bugs fixed, valgrind tested
                    179: 
1.285     brouard   180:   Revision 1.284  2018/04/20 05:22:13  brouard
                    181:   Summary: Computing mean and stdeviation of fixed quantitative variables
                    182: 
1.284     brouard   183:   Revision 1.283  2018/04/19 14:49:16  brouard
                    184:   Summary: Some minor bugs fixed
                    185: 
1.283     brouard   186:   Revision 1.282  2018/02/27 22:50:02  brouard
                    187:   *** empty log message ***
                    188: 
1.282     brouard   189:   Revision 1.281  2018/02/27 19:25:23  brouard
                    190:   Summary: Adding second argument for quitting
                    191: 
1.281     brouard   192:   Revision 1.280  2018/02/21 07:58:13  brouard
                    193:   Summary: 0.99r15
                    194: 
                    195:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                    196: 
1.280     brouard   197:   Revision 1.279  2017/07/20 13:35:01  brouard
                    198:   Summary: temporary working
                    199: 
1.279     brouard   200:   Revision 1.278  2017/07/19 14:09:02  brouard
                    201:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                    202: 
1.278     brouard   203:   Revision 1.277  2017/07/17 08:53:49  brouard
                    204:   Summary: BOM files can be read now
                    205: 
1.277     brouard   206:   Revision 1.276  2017/06/30 15:48:31  brouard
                    207:   Summary: Graphs improvements
                    208: 
1.276     brouard   209:   Revision 1.275  2017/06/30 13:39:33  brouard
                    210:   Summary: Saito's color
                    211: 
1.275     brouard   212:   Revision 1.274  2017/06/29 09:47:08  brouard
                    213:   Summary: Version 0.99r14
                    214: 
1.274     brouard   215:   Revision 1.273  2017/06/27 11:06:02  brouard
                    216:   Summary: More documentation on projections
                    217: 
1.273     brouard   218:   Revision 1.272  2017/06/27 10:22:40  brouard
                    219:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    220: 
1.272     brouard   221:   Revision 1.271  2017/06/27 10:17:50  brouard
                    222:   Summary: Some bug with rint
                    223: 
1.271     brouard   224:   Revision 1.270  2017/05/24 05:45:29  brouard
                    225:   *** empty log message ***
                    226: 
1.270     brouard   227:   Revision 1.269  2017/05/23 08:39:25  brouard
                    228:   Summary: Code into subroutine, cleanings
                    229: 
1.269     brouard   230:   Revision 1.268  2017/05/18 20:09:32  brouard
                    231:   Summary: backprojection and confidence intervals of backprevalence
                    232: 
1.268     brouard   233:   Revision 1.267  2017/05/13 10:25:05  brouard
                    234:   Summary: temporary save for backprojection
                    235: 
1.267     brouard   236:   Revision 1.266  2017/05/13 07:26:12  brouard
                    237:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    238: 
1.266     brouard   239:   Revision 1.265  2017/04/26 16:22:11  brouard
                    240:   Summary: imach 0.99r13 Some bugs fixed
                    241: 
1.265     brouard   242:   Revision 1.264  2017/04/26 06:01:29  brouard
                    243:   Summary: Labels in graphs
                    244: 
1.264     brouard   245:   Revision 1.263  2017/04/24 15:23:15  brouard
                    246:   Summary: to save
                    247: 
1.263     brouard   248:   Revision 1.262  2017/04/18 16:48:12  brouard
                    249:   *** empty log message ***
                    250: 
1.262     brouard   251:   Revision 1.261  2017/04/05 10:14:09  brouard
                    252:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    253: 
1.261     brouard   254:   Revision 1.260  2017/04/04 17:46:59  brouard
                    255:   Summary: Gnuplot indexations fixed (humm)
                    256: 
1.260     brouard   257:   Revision 1.259  2017/04/04 13:01:16  brouard
                    258:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    259: 
1.259     brouard   260:   Revision 1.258  2017/04/03 10:17:47  brouard
                    261:   Summary: Version 0.99r12
                    262: 
                    263:   Some cleanings, conformed with updated documentation.
                    264: 
1.258     brouard   265:   Revision 1.257  2017/03/29 16:53:30  brouard
                    266:   Summary: Temp
                    267: 
1.257     brouard   268:   Revision 1.256  2017/03/27 05:50:23  brouard
                    269:   Summary: Temporary
                    270: 
1.256     brouard   271:   Revision 1.255  2017/03/08 16:02:28  brouard
                    272:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    273: 
1.255     brouard   274:   Revision 1.254  2017/03/08 07:13:00  brouard
                    275:   Summary: Fixing data parameter line
                    276: 
1.254     brouard   277:   Revision 1.253  2016/12/15 11:59:41  brouard
                    278:   Summary: 0.99 in progress
                    279: 
1.253     brouard   280:   Revision 1.252  2016/09/15 21:15:37  brouard
                    281:   *** empty log message ***
                    282: 
1.252     brouard   283:   Revision 1.251  2016/09/15 15:01:13  brouard
                    284:   Summary: not working
                    285: 
1.251     brouard   286:   Revision 1.250  2016/09/08 16:07:27  brouard
                    287:   Summary: continue
                    288: 
1.250     brouard   289:   Revision 1.249  2016/09/07 17:14:18  brouard
                    290:   Summary: Starting values from frequencies
                    291: 
1.249     brouard   292:   Revision 1.248  2016/09/07 14:10:18  brouard
                    293:   *** empty log message ***
                    294: 
1.248     brouard   295:   Revision 1.247  2016/09/02 11:11:21  brouard
                    296:   *** empty log message ***
                    297: 
1.247     brouard   298:   Revision 1.246  2016/09/02 08:49:22  brouard
                    299:   *** empty log message ***
                    300: 
1.246     brouard   301:   Revision 1.245  2016/09/02 07:25:01  brouard
                    302:   *** empty log message ***
                    303: 
1.245     brouard   304:   Revision 1.244  2016/09/02 07:17:34  brouard
                    305:   *** empty log message ***
                    306: 
1.244     brouard   307:   Revision 1.243  2016/09/02 06:45:35  brouard
                    308:   *** empty log message ***
                    309: 
1.243     brouard   310:   Revision 1.242  2016/08/30 15:01:20  brouard
                    311:   Summary: Fixing a lots
                    312: 
1.242     brouard   313:   Revision 1.241  2016/08/29 17:17:25  brouard
                    314:   Summary: gnuplot problem in Back projection to fix
                    315: 
1.241     brouard   316:   Revision 1.240  2016/08/29 07:53:18  brouard
                    317:   Summary: Better
                    318: 
1.240     brouard   319:   Revision 1.239  2016/08/26 15:51:03  brouard
                    320:   Summary: Improvement in Powell output in order to copy and paste
                    321: 
                    322:   Author:
                    323: 
1.239     brouard   324:   Revision 1.238  2016/08/26 14:23:35  brouard
                    325:   Summary: Starting tests of 0.99
                    326: 
1.238     brouard   327:   Revision 1.237  2016/08/26 09:20:19  brouard
                    328:   Summary: to valgrind
                    329: 
1.237     brouard   330:   Revision 1.236  2016/08/25 10:50:18  brouard
                    331:   *** empty log message ***
                    332: 
1.236     brouard   333:   Revision 1.235  2016/08/25 06:59:23  brouard
                    334:   *** empty log message ***
                    335: 
1.235     brouard   336:   Revision 1.234  2016/08/23 16:51:20  brouard
                    337:   *** empty log message ***
                    338: 
1.234     brouard   339:   Revision 1.233  2016/08/23 07:40:50  brouard
                    340:   Summary: not working
                    341: 
1.233     brouard   342:   Revision 1.232  2016/08/22 14:20:21  brouard
                    343:   Summary: not working
                    344: 
1.232     brouard   345:   Revision 1.231  2016/08/22 07:17:15  brouard
                    346:   Summary: not working
                    347: 
1.231     brouard   348:   Revision 1.230  2016/08/22 06:55:53  brouard
                    349:   Summary: Not working
                    350: 
1.230     brouard   351:   Revision 1.229  2016/07/23 09:45:53  brouard
                    352:   Summary: Completing for func too
                    353: 
1.229     brouard   354:   Revision 1.228  2016/07/22 17:45:30  brouard
                    355:   Summary: Fixing some arrays, still debugging
                    356: 
1.227     brouard   357:   Revision 1.226  2016/07/12 18:42:34  brouard
                    358:   Summary: temp
                    359: 
1.226     brouard   360:   Revision 1.225  2016/07/12 08:40:03  brouard
                    361:   Summary: saving but not running
                    362: 
1.225     brouard   363:   Revision 1.224  2016/07/01 13:16:01  brouard
                    364:   Summary: Fixes
                    365: 
1.224     brouard   366:   Revision 1.223  2016/02/19 09:23:35  brouard
                    367:   Summary: temporary
                    368: 
1.223     brouard   369:   Revision 1.222  2016/02/17 08:14:50  brouard
                    370:   Summary: Probably last 0.98 stable version 0.98r6
                    371: 
1.222     brouard   372:   Revision 1.221  2016/02/15 23:35:36  brouard
                    373:   Summary: minor bug
                    374: 
1.220     brouard   375:   Revision 1.219  2016/02/15 00:48:12  brouard
                    376:   *** empty log message ***
                    377: 
1.219     brouard   378:   Revision 1.218  2016/02/12 11:29:23  brouard
                    379:   Summary: 0.99 Back projections
                    380: 
1.218     brouard   381:   Revision 1.217  2015/12/23 17:18:31  brouard
                    382:   Summary: Experimental backcast
                    383: 
1.217     brouard   384:   Revision 1.216  2015/12/18 17:32:11  brouard
                    385:   Summary: 0.98r4 Warning and status=-2
                    386: 
                    387:   Version 0.98r4 is now:
                    388:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    389:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    390:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    391: 
1.216     brouard   392:   Revision 1.215  2015/12/16 08:52:24  brouard
                    393:   Summary: 0.98r4 working
                    394: 
1.215     brouard   395:   Revision 1.214  2015/12/16 06:57:54  brouard
                    396:   Summary: temporary not working
                    397: 
1.214     brouard   398:   Revision 1.213  2015/12/11 18:22:17  brouard
                    399:   Summary: 0.98r4
                    400: 
1.213     brouard   401:   Revision 1.212  2015/11/21 12:47:24  brouard
                    402:   Summary: minor typo
                    403: 
1.212     brouard   404:   Revision 1.211  2015/11/21 12:41:11  brouard
                    405:   Summary: 0.98r3 with some graph of projected cross-sectional
                    406: 
                    407:   Author: Nicolas Brouard
                    408: 
1.211     brouard   409:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   410:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   411:   Summary: Adding ftolpl parameter
                    412:   Author: N Brouard
                    413: 
                    414:   We had difficulties to get smoothed confidence intervals. It was due
                    415:   to the period prevalence which wasn't computed accurately. The inner
                    416:   parameter ftolpl is now an outer parameter of the .imach parameter
                    417:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    418:   computation are long.
                    419: 
1.209     brouard   420:   Revision 1.208  2015/11/17 14:31:57  brouard
                    421:   Summary: temporary
                    422: 
1.208     brouard   423:   Revision 1.207  2015/10/27 17:36:57  brouard
                    424:   *** empty log message ***
                    425: 
1.207     brouard   426:   Revision 1.206  2015/10/24 07:14:11  brouard
                    427:   *** empty log message ***
                    428: 
1.206     brouard   429:   Revision 1.205  2015/10/23 15:50:53  brouard
                    430:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    431: 
1.205     brouard   432:   Revision 1.204  2015/10/01 16:20:26  brouard
                    433:   Summary: Some new graphs of contribution to likelihood
                    434: 
1.204     brouard   435:   Revision 1.203  2015/09/30 17:45:14  brouard
                    436:   Summary: looking at better estimation of the hessian
                    437: 
                    438:   Also a better criteria for convergence to the period prevalence And
                    439:   therefore adding the number of years needed to converge. (The
                    440:   prevalence in any alive state shold sum to one
                    441: 
1.203     brouard   442:   Revision 1.202  2015/09/22 19:45:16  brouard
                    443:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    444: 
1.202     brouard   445:   Revision 1.201  2015/09/15 17:34:58  brouard
                    446:   Summary: 0.98r0
                    447: 
                    448:   - Some new graphs like suvival functions
                    449:   - Some bugs fixed like model=1+age+V2.
                    450: 
1.201     brouard   451:   Revision 1.200  2015/09/09 16:53:55  brouard
                    452:   Summary: Big bug thanks to Flavia
                    453: 
                    454:   Even model=1+age+V2. did not work anymore
                    455: 
1.200     brouard   456:   Revision 1.199  2015/09/07 14:09:23  brouard
                    457:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    458: 
1.199     brouard   459:   Revision 1.198  2015/09/03 07:14:39  brouard
                    460:   Summary: 0.98q5 Flavia
                    461: 
1.198     brouard   462:   Revision 1.197  2015/09/01 18:24:39  brouard
                    463:   *** empty log message ***
                    464: 
1.197     brouard   465:   Revision 1.196  2015/08/18 23:17:52  brouard
                    466:   Summary: 0.98q5
                    467: 
1.196     brouard   468:   Revision 1.195  2015/08/18 16:28:39  brouard
                    469:   Summary: Adding a hack for testing purpose
                    470: 
                    471:   After reading the title, ftol and model lines, if the comment line has
                    472:   a q, starting with #q, the answer at the end of the run is quit. It
                    473:   permits to run test files in batch with ctest. The former workaround was
                    474:   $ echo q | imach foo.imach
                    475: 
1.195     brouard   476:   Revision 1.194  2015/08/18 13:32:00  brouard
                    477:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    478: 
1.194     brouard   479:   Revision 1.193  2015/08/04 07:17:42  brouard
                    480:   Summary: 0.98q4
                    481: 
1.193     brouard   482:   Revision 1.192  2015/07/16 16:49:02  brouard
                    483:   Summary: Fixing some outputs
                    484: 
1.192     brouard   485:   Revision 1.191  2015/07/14 10:00:33  brouard
                    486:   Summary: Some fixes
                    487: 
1.191     brouard   488:   Revision 1.190  2015/05/05 08:51:13  brouard
                    489:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    490: 
                    491:   Fix 1+age+.
                    492: 
1.190     brouard   493:   Revision 1.189  2015/04/30 14:45:16  brouard
                    494:   Summary: 0.98q2
                    495: 
1.189     brouard   496:   Revision 1.188  2015/04/30 08:27:53  brouard
                    497:   *** empty log message ***
                    498: 
1.188     brouard   499:   Revision 1.187  2015/04/29 09:11:15  brouard
                    500:   *** empty log message ***
                    501: 
1.187     brouard   502:   Revision 1.186  2015/04/23 12:01:52  brouard
                    503:   Summary: V1*age is working now, version 0.98q1
                    504: 
                    505:   Some codes had been disabled in order to simplify and Vn*age was
                    506:   working in the optimization phase, ie, giving correct MLE parameters,
                    507:   but, as usual, outputs were not correct and program core dumped.
                    508: 
1.186     brouard   509:   Revision 1.185  2015/03/11 13:26:42  brouard
                    510:   Summary: Inclusion of compile and links command line for Intel Compiler
                    511: 
1.185     brouard   512:   Revision 1.184  2015/03/11 11:52:39  brouard
                    513:   Summary: Back from Windows 8. Intel Compiler
                    514: 
1.184     brouard   515:   Revision 1.183  2015/03/10 20:34:32  brouard
                    516:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    517: 
                    518:   We use directest instead of original Powell test; probably no
                    519:   incidence on the results, but better justifications;
                    520:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    521:   wrong results.
                    522: 
1.183     brouard   523:   Revision 1.182  2015/02/12 08:19:57  brouard
                    524:   Summary: Trying to keep directest which seems simpler and more general
                    525:   Author: Nicolas Brouard
                    526: 
1.182     brouard   527:   Revision 1.181  2015/02/11 23:22:24  brouard
                    528:   Summary: Comments on Powell added
                    529: 
                    530:   Author:
                    531: 
1.181     brouard   532:   Revision 1.180  2015/02/11 17:33:45  brouard
                    533:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    534: 
1.180     brouard   535:   Revision 1.179  2015/01/04 09:57:06  brouard
                    536:   Summary: back to OS/X
                    537: 
1.179     brouard   538:   Revision 1.178  2015/01/04 09:35:48  brouard
                    539:   *** empty log message ***
                    540: 
1.178     brouard   541:   Revision 1.177  2015/01/03 18:40:56  brouard
                    542:   Summary: Still testing ilc32 on OSX
                    543: 
1.177     brouard   544:   Revision 1.176  2015/01/03 16:45:04  brouard
                    545:   *** empty log message ***
                    546: 
1.176     brouard   547:   Revision 1.175  2015/01/03 16:33:42  brouard
                    548:   *** empty log message ***
                    549: 
1.175     brouard   550:   Revision 1.174  2015/01/03 16:15:49  brouard
                    551:   Summary: Still in cross-compilation
                    552: 
1.174     brouard   553:   Revision 1.173  2015/01/03 12:06:26  brouard
                    554:   Summary: trying to detect cross-compilation
                    555: 
1.173     brouard   556:   Revision 1.172  2014/12/27 12:07:47  brouard
                    557:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    558: 
1.172     brouard   559:   Revision 1.171  2014/12/23 13:26:59  brouard
                    560:   Summary: Back from Visual C
                    561: 
                    562:   Still problem with utsname.h on Windows
                    563: 
1.171     brouard   564:   Revision 1.170  2014/12/23 11:17:12  brouard
                    565:   Summary: Cleaning some \%% back to %%
                    566: 
                    567:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    568: 
1.170     brouard   569:   Revision 1.169  2014/12/22 23:08:31  brouard
                    570:   Summary: 0.98p
                    571: 
                    572:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    573: 
1.169     brouard   574:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   575:   Summary: update
1.169     brouard   576: 
1.168     brouard   577:   Revision 1.167  2014/12/22 13:50:56  brouard
                    578:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    579: 
                    580:   Testing on Linux 64
                    581: 
1.167     brouard   582:   Revision 1.166  2014/12/22 11:40:47  brouard
                    583:   *** empty log message ***
                    584: 
1.166     brouard   585:   Revision 1.165  2014/12/16 11:20:36  brouard
                    586:   Summary: After compiling on Visual C
                    587: 
                    588:   * imach.c (Module): Merging 1.61 to 1.162
                    589: 
1.165     brouard   590:   Revision 1.164  2014/12/16 10:52:11  brouard
                    591:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    592: 
                    593:   * imach.c (Module): Merging 1.61 to 1.162
                    594: 
1.164     brouard   595:   Revision 1.163  2014/12/16 10:30:11  brouard
                    596:   * imach.c (Module): Merging 1.61 to 1.162
                    597: 
1.163     brouard   598:   Revision 1.162  2014/09/25 11:43:39  brouard
                    599:   Summary: temporary backup 0.99!
                    600: 
1.162     brouard   601:   Revision 1.1  2014/09/16 11:06:58  brouard
                    602:   Summary: With some code (wrong) for nlopt
                    603: 
                    604:   Author:
                    605: 
                    606:   Revision 1.161  2014/09/15 20:41:41  brouard
                    607:   Summary: Problem with macro SQR on Intel compiler
                    608: 
1.161     brouard   609:   Revision 1.160  2014/09/02 09:24:05  brouard
                    610:   *** empty log message ***
                    611: 
1.160     brouard   612:   Revision 1.159  2014/09/01 10:34:10  brouard
                    613:   Summary: WIN32
                    614:   Author: Brouard
                    615: 
1.159     brouard   616:   Revision 1.158  2014/08/27 17:11:51  brouard
                    617:   *** empty log message ***
                    618: 
1.158     brouard   619:   Revision 1.157  2014/08/27 16:26:55  brouard
                    620:   Summary: Preparing windows Visual studio version
                    621:   Author: Brouard
                    622: 
                    623:   In order to compile on Visual studio, time.h is now correct and time_t
                    624:   and tm struct should be used. difftime should be used but sometimes I
                    625:   just make the differences in raw time format (time(&now).
                    626:   Trying to suppress #ifdef LINUX
                    627:   Add xdg-open for __linux in order to open default browser.
                    628: 
1.157     brouard   629:   Revision 1.156  2014/08/25 20:10:10  brouard
                    630:   *** empty log message ***
                    631: 
1.156     brouard   632:   Revision 1.155  2014/08/25 18:32:34  brouard
                    633:   Summary: New compile, minor changes
                    634:   Author: Brouard
                    635: 
1.155     brouard   636:   Revision 1.154  2014/06/20 17:32:08  brouard
                    637:   Summary: Outputs now all graphs of convergence to period prevalence
                    638: 
1.154     brouard   639:   Revision 1.153  2014/06/20 16:45:46  brouard
                    640:   Summary: If 3 live state, convergence to period prevalence on same graph
                    641:   Author: Brouard
                    642: 
1.153     brouard   643:   Revision 1.152  2014/06/18 17:54:09  brouard
                    644:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    645: 
1.152     brouard   646:   Revision 1.151  2014/06/18 16:43:30  brouard
                    647:   *** empty log message ***
                    648: 
1.151     brouard   649:   Revision 1.150  2014/06/18 16:42:35  brouard
                    650:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    651:   Author: brouard
                    652: 
1.150     brouard   653:   Revision 1.149  2014/06/18 15:51:14  brouard
                    654:   Summary: Some fixes in parameter files errors
                    655:   Author: Nicolas Brouard
                    656: 
1.149     brouard   657:   Revision 1.148  2014/06/17 17:38:48  brouard
                    658:   Summary: Nothing new
                    659:   Author: Brouard
                    660: 
                    661:   Just a new packaging for OS/X version 0.98nS
                    662: 
1.148     brouard   663:   Revision 1.147  2014/06/16 10:33:11  brouard
                    664:   *** empty log message ***
                    665: 
1.147     brouard   666:   Revision 1.146  2014/06/16 10:20:28  brouard
                    667:   Summary: Merge
                    668:   Author: Brouard
                    669: 
                    670:   Merge, before building revised version.
                    671: 
1.146     brouard   672:   Revision 1.145  2014/06/10 21:23:15  brouard
                    673:   Summary: Debugging with valgrind
                    674:   Author: Nicolas Brouard
                    675: 
                    676:   Lot of changes in order to output the results with some covariates
                    677:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    678:   improve the code.
                    679:   No more memory valgrind error but a lot has to be done in order to
                    680:   continue the work of splitting the code into subroutines.
                    681:   Also, decodemodel has been improved. Tricode is still not
                    682:   optimal. nbcode should be improved. Documentation has been added in
                    683:   the source code.
                    684: 
1.144     brouard   685:   Revision 1.143  2014/01/26 09:45:38  brouard
                    686:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    687: 
                    688:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    689:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    690: 
1.143     brouard   691:   Revision 1.142  2014/01/26 03:57:36  brouard
                    692:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    693: 
                    694:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    695: 
1.142     brouard   696:   Revision 1.141  2014/01/26 02:42:01  brouard
                    697:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    698: 
1.141     brouard   699:   Revision 1.140  2011/09/02 10:37:54  brouard
                    700:   Summary: times.h is ok with mingw32 now.
                    701: 
1.140     brouard   702:   Revision 1.139  2010/06/14 07:50:17  brouard
                    703:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    704:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    705: 
1.139     brouard   706:   Revision 1.138  2010/04/30 18:19:40  brouard
                    707:   *** empty log message ***
                    708: 
1.138     brouard   709:   Revision 1.137  2010/04/29 18:11:38  brouard
                    710:   (Module): Checking covariates for more complex models
                    711:   than V1+V2. A lot of change to be done. Unstable.
                    712: 
1.137     brouard   713:   Revision 1.136  2010/04/26 20:30:53  brouard
                    714:   (Module): merging some libgsl code. Fixing computation
                    715:   of likelione (using inter/intrapolation if mle = 0) in order to
                    716:   get same likelihood as if mle=1.
                    717:   Some cleaning of code and comments added.
                    718: 
1.136     brouard   719:   Revision 1.135  2009/10/29 15:33:14  brouard
                    720:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    721: 
1.135     brouard   722:   Revision 1.134  2009/10/29 13:18:53  brouard
                    723:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    724: 
1.134     brouard   725:   Revision 1.133  2009/07/06 10:21:25  brouard
                    726:   just nforces
                    727: 
1.133     brouard   728:   Revision 1.132  2009/07/06 08:22:05  brouard
                    729:   Many tings
                    730: 
1.132     brouard   731:   Revision 1.131  2009/06/20 16:22:47  brouard
                    732:   Some dimensions resccaled
                    733: 
1.131     brouard   734:   Revision 1.130  2009/05/26 06:44:34  brouard
                    735:   (Module): Max Covariate is now set to 20 instead of 8. A
                    736:   lot of cleaning with variables initialized to 0. Trying to make
                    737:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    738: 
1.130     brouard   739:   Revision 1.129  2007/08/31 13:49:27  lievre
                    740:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    741: 
1.129     lievre    742:   Revision 1.128  2006/06/30 13:02:05  brouard
                    743:   (Module): Clarifications on computing e.j
                    744: 
1.128     brouard   745:   Revision 1.127  2006/04/28 18:11:50  brouard
                    746:   (Module): Yes the sum of survivors was wrong since
                    747:   imach-114 because nhstepm was no more computed in the age
                    748:   loop. Now we define nhstepma in the age loop.
                    749:   (Module): In order to speed up (in case of numerous covariates) we
                    750:   compute health expectancies (without variances) in a first step
                    751:   and then all the health expectancies with variances or standard
                    752:   deviation (needs data from the Hessian matrices) which slows the
                    753:   computation.
                    754:   In the future we should be able to stop the program is only health
                    755:   expectancies and graph are needed without standard deviations.
                    756: 
1.127     brouard   757:   Revision 1.126  2006/04/28 17:23:28  brouard
                    758:   (Module): Yes the sum of survivors was wrong since
                    759:   imach-114 because nhstepm was no more computed in the age
                    760:   loop. Now we define nhstepma in the age loop.
                    761:   Version 0.98h
                    762: 
1.126     brouard   763:   Revision 1.125  2006/04/04 15:20:31  lievre
                    764:   Errors in calculation of health expectancies. Age was not initialized.
                    765:   Forecasting file added.
                    766: 
                    767:   Revision 1.124  2006/03/22 17:13:53  lievre
                    768:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    769:   The log-likelihood is printed in the log file
                    770: 
                    771:   Revision 1.123  2006/03/20 10:52:43  brouard
                    772:   * imach.c (Module): <title> changed, corresponds to .htm file
                    773:   name. <head> headers where missing.
                    774: 
                    775:   * imach.c (Module): Weights can have a decimal point as for
                    776:   English (a comma might work with a correct LC_NUMERIC environment,
                    777:   otherwise the weight is truncated).
                    778:   Modification of warning when the covariates values are not 0 or
                    779:   1.
                    780:   Version 0.98g
                    781: 
                    782:   Revision 1.122  2006/03/20 09:45:41  brouard
                    783:   (Module): Weights can have a decimal point as for
                    784:   English (a comma might work with a correct LC_NUMERIC environment,
                    785:   otherwise the weight is truncated).
                    786:   Modification of warning when the covariates values are not 0 or
                    787:   1.
                    788:   Version 0.98g
                    789: 
                    790:   Revision 1.121  2006/03/16 17:45:01  lievre
                    791:   * imach.c (Module): Comments concerning covariates added
                    792: 
                    793:   * imach.c (Module): refinements in the computation of lli if
                    794:   status=-2 in order to have more reliable computation if stepm is
                    795:   not 1 month. Version 0.98f
                    796: 
                    797:   Revision 1.120  2006/03/16 15:10:38  lievre
                    798:   (Module): refinements in the computation of lli if
                    799:   status=-2 in order to have more reliable computation if stepm is
                    800:   not 1 month. Version 0.98f
                    801: 
                    802:   Revision 1.119  2006/03/15 17:42:26  brouard
                    803:   (Module): Bug if status = -2, the loglikelihood was
                    804:   computed as likelihood omitting the logarithm. Version O.98e
                    805: 
                    806:   Revision 1.118  2006/03/14 18:20:07  brouard
                    807:   (Module): varevsij Comments added explaining the second
                    808:   table of variances if popbased=1 .
                    809:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    810:   (Module): Function pstamp added
                    811:   (Module): Version 0.98d
                    812: 
                    813:   Revision 1.117  2006/03/14 17:16:22  brouard
                    814:   (Module): varevsij Comments added explaining the second
                    815:   table of variances if popbased=1 .
                    816:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    817:   (Module): Function pstamp added
                    818:   (Module): Version 0.98d
                    819: 
                    820:   Revision 1.116  2006/03/06 10:29:27  brouard
                    821:   (Module): Variance-covariance wrong links and
                    822:   varian-covariance of ej. is needed (Saito).
                    823: 
                    824:   Revision 1.115  2006/02/27 12:17:45  brouard
                    825:   (Module): One freematrix added in mlikeli! 0.98c
                    826: 
                    827:   Revision 1.114  2006/02/26 12:57:58  brouard
                    828:   (Module): Some improvements in processing parameter
                    829:   filename with strsep.
                    830: 
                    831:   Revision 1.113  2006/02/24 14:20:24  brouard
                    832:   (Module): Memory leaks checks with valgrind and:
                    833:   datafile was not closed, some imatrix were not freed and on matrix
                    834:   allocation too.
                    835: 
                    836:   Revision 1.112  2006/01/30 09:55:26  brouard
                    837:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    838: 
                    839:   Revision 1.111  2006/01/25 20:38:18  brouard
                    840:   (Module): Lots of cleaning and bugs added (Gompertz)
                    841:   (Module): Comments can be added in data file. Missing date values
                    842:   can be a simple dot '.'.
                    843: 
                    844:   Revision 1.110  2006/01/25 00:51:50  brouard
                    845:   (Module): Lots of cleaning and bugs added (Gompertz)
                    846: 
                    847:   Revision 1.109  2006/01/24 19:37:15  brouard
                    848:   (Module): Comments (lines starting with a #) are allowed in data.
                    849: 
                    850:   Revision 1.108  2006/01/19 18:05:42  lievre
                    851:   Gnuplot problem appeared...
                    852:   To be fixed
                    853: 
                    854:   Revision 1.107  2006/01/19 16:20:37  brouard
                    855:   Test existence of gnuplot in imach path
                    856: 
                    857:   Revision 1.106  2006/01/19 13:24:36  brouard
                    858:   Some cleaning and links added in html output
                    859: 
                    860:   Revision 1.105  2006/01/05 20:23:19  lievre
                    861:   *** empty log message ***
                    862: 
                    863:   Revision 1.104  2005/09/30 16:11:43  lievre
                    864:   (Module): sump fixed, loop imx fixed, and simplifications.
                    865:   (Module): If the status is missing at the last wave but we know
                    866:   that the person is alive, then we can code his/her status as -2
                    867:   (instead of missing=-1 in earlier versions) and his/her
                    868:   contributions to the likelihood is 1 - Prob of dying from last
                    869:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    870:   the healthy state at last known wave). Version is 0.98
                    871: 
                    872:   Revision 1.103  2005/09/30 15:54:49  lievre
                    873:   (Module): sump fixed, loop imx fixed, and simplifications.
                    874: 
                    875:   Revision 1.102  2004/09/15 17:31:30  brouard
                    876:   Add the possibility to read data file including tab characters.
                    877: 
                    878:   Revision 1.101  2004/09/15 10:38:38  brouard
                    879:   Fix on curr_time
                    880: 
                    881:   Revision 1.100  2004/07/12 18:29:06  brouard
                    882:   Add version for Mac OS X. Just define UNIX in Makefile
                    883: 
                    884:   Revision 1.99  2004/06/05 08:57:40  brouard
                    885:   *** empty log message ***
                    886: 
                    887:   Revision 1.98  2004/05/16 15:05:56  brouard
                    888:   New version 0.97 . First attempt to estimate force of mortality
                    889:   directly from the data i.e. without the need of knowing the health
                    890:   state at each age, but using a Gompertz model: log u =a + b*age .
                    891:   This is the basic analysis of mortality and should be done before any
                    892:   other analysis, in order to test if the mortality estimated from the
                    893:   cross-longitudinal survey is different from the mortality estimated
                    894:   from other sources like vital statistic data.
                    895: 
                    896:   The same imach parameter file can be used but the option for mle should be -3.
                    897: 
1.324     brouard   898:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   899:   former routines in order to include the new code within the former code.
                    900: 
                    901:   The output is very simple: only an estimate of the intercept and of
                    902:   the slope with 95% confident intervals.
                    903: 
                    904:   Current limitations:
                    905:   A) Even if you enter covariates, i.e. with the
                    906:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    907:   B) There is no computation of Life Expectancy nor Life Table.
                    908: 
                    909:   Revision 1.97  2004/02/20 13:25:42  lievre
                    910:   Version 0.96d. Population forecasting command line is (temporarily)
                    911:   suppressed.
                    912: 
                    913:   Revision 1.96  2003/07/15 15:38:55  brouard
                    914:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    915:   rewritten within the same printf. Workaround: many printfs.
                    916: 
                    917:   Revision 1.95  2003/07/08 07:54:34  brouard
                    918:   * imach.c (Repository):
                    919:   (Repository): Using imachwizard code to output a more meaningful covariance
                    920:   matrix (cov(a12,c31) instead of numbers.
                    921: 
                    922:   Revision 1.94  2003/06/27 13:00:02  brouard
                    923:   Just cleaning
                    924: 
                    925:   Revision 1.93  2003/06/25 16:33:55  brouard
                    926:   (Module): On windows (cygwin) function asctime_r doesn't
                    927:   exist so I changed back to asctime which exists.
                    928:   (Module): Version 0.96b
                    929: 
                    930:   Revision 1.92  2003/06/25 16:30:45  brouard
                    931:   (Module): On windows (cygwin) function asctime_r doesn't
                    932:   exist so I changed back to asctime which exists.
                    933: 
                    934:   Revision 1.91  2003/06/25 15:30:29  brouard
                    935:   * imach.c (Repository): Duplicated warning errors corrected.
                    936:   (Repository): Elapsed time after each iteration is now output. It
                    937:   helps to forecast when convergence will be reached. Elapsed time
                    938:   is stamped in powell.  We created a new html file for the graphs
                    939:   concerning matrix of covariance. It has extension -cov.htm.
                    940: 
                    941:   Revision 1.90  2003/06/24 12:34:15  brouard
                    942:   (Module): Some bugs corrected for windows. Also, when
                    943:   mle=-1 a template is output in file "or"mypar.txt with the design
                    944:   of the covariance matrix to be input.
                    945: 
                    946:   Revision 1.89  2003/06/24 12:30:52  brouard
                    947:   (Module): Some bugs corrected for windows. Also, when
                    948:   mle=-1 a template is output in file "or"mypar.txt with the design
                    949:   of the covariance matrix to be input.
                    950: 
                    951:   Revision 1.88  2003/06/23 17:54:56  brouard
                    952:   * 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.
                    953: 
                    954:   Revision 1.87  2003/06/18 12:26:01  brouard
                    955:   Version 0.96
                    956: 
                    957:   Revision 1.86  2003/06/17 20:04:08  brouard
                    958:   (Module): Change position of html and gnuplot routines and added
                    959:   routine fileappend.
                    960: 
                    961:   Revision 1.85  2003/06/17 13:12:43  brouard
                    962:   * imach.c (Repository): Check when date of death was earlier that
                    963:   current date of interview. It may happen when the death was just
                    964:   prior to the death. In this case, dh was negative and likelihood
                    965:   was wrong (infinity). We still send an "Error" but patch by
                    966:   assuming that the date of death was just one stepm after the
                    967:   interview.
                    968:   (Repository): Because some people have very long ID (first column)
                    969:   we changed int to long in num[] and we added a new lvector for
                    970:   memory allocation. But we also truncated to 8 characters (left
                    971:   truncation)
                    972:   (Repository): No more line truncation errors.
                    973: 
                    974:   Revision 1.84  2003/06/13 21:44:43  brouard
                    975:   * imach.c (Repository): Replace "freqsummary" at a correct
                    976:   place. It differs from routine "prevalence" which may be called
                    977:   many times. Probs is memory consuming and must be used with
                    978:   parcimony.
                    979:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    980: 
                    981:   Revision 1.83  2003/06/10 13:39:11  lievre
                    982:   *** empty log message ***
                    983: 
                    984:   Revision 1.82  2003/06/05 15:57:20  brouard
                    985:   Add log in  imach.c and  fullversion number is now printed.
                    986: 
                    987: */
                    988: /*
                    989:    Interpolated Markov Chain
                    990: 
                    991:   Short summary of the programme:
                    992:   
1.227     brouard   993:   This program computes Healthy Life Expectancies or State-specific
                    994:   (if states aren't health statuses) Expectancies from
                    995:   cross-longitudinal data. Cross-longitudinal data consist in: 
                    996: 
                    997:   -1- a first survey ("cross") where individuals from different ages
                    998:   are interviewed on their health status or degree of disability (in
                    999:   the case of a health survey which is our main interest)
                   1000: 
                   1001:   -2- at least a second wave of interviews ("longitudinal") which
                   1002:   measure each change (if any) in individual health status.  Health
                   1003:   expectancies are computed from the time spent in each health state
                   1004:   according to a model. More health states you consider, more time is
                   1005:   necessary to reach the Maximum Likelihood of the parameters involved
                   1006:   in the model.  The simplest model is the multinomial logistic model
                   1007:   where pij is the probability to be observed in state j at the second
                   1008:   wave conditional to be observed in state i at the first
                   1009:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                   1010:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                   1011:   have a more complex model than "constant and age", you should modify
                   1012:   the program where the markup *Covariates have to be included here
                   1013:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard  1014:   convergence.
                   1015: 
                   1016:   The advantage of this computer programme, compared to a simple
                   1017:   multinomial logistic model, is clear when the delay between waves is not
                   1018:   identical for each individual. Also, if a individual missed an
                   1019:   intermediate interview, the information is lost, but taken into
                   1020:   account using an interpolation or extrapolation.  
                   1021: 
                   1022:   hPijx is the probability to be observed in state i at age x+h
                   1023:   conditional to the observed state i at age x. The delay 'h' can be
                   1024:   split into an exact number (nh*stepm) of unobserved intermediate
                   1025:   states. This elementary transition (by month, quarter,
                   1026:   semester or year) is modelled as a multinomial logistic.  The hPx
                   1027:   matrix is simply the matrix product of nh*stepm elementary matrices
                   1028:   and the contribution of each individual to the likelihood is simply
                   1029:   hPijx.
                   1030: 
                   1031:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard  1032:   of the life expectancies. It also computes the period (stable) prevalence.
                   1033: 
                   1034: Back prevalence and projections:
1.227     brouard  1035: 
                   1036:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                   1037:    double agemaxpar, double ftolpl, int *ncvyearp, double
                   1038:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                   1039:    mobilavproj)
                   1040: 
                   1041:     Computes the back prevalence limit for any combination of
                   1042:     covariate values k at any age between ageminpar and agemaxpar and
                   1043:     returns it in **bprlim. In the loops,
                   1044: 
                   1045:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                   1046:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                   1047: 
                   1048:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard  1049:    Computes for any combination of covariates k and any age between bage and fage 
                   1050:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1051:                        oldm=oldms;savm=savms;
1.227     brouard  1052: 
1.267     brouard  1053:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard  1054:      Computes the transition matrix starting at age 'age' over
                   1055:      'nhstepm*hstepm*stepm' months (i.e. until
                   1056:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard  1057:      nhstepm*hstepm matrices. 
                   1058: 
                   1059:      Returns p3mat[i][j][h] after calling
                   1060:      p3mat[i][j][h]=matprod2(newm,
                   1061:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                   1062:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                   1063:      oldm);
1.226     brouard  1064: 
                   1065: Important routines
                   1066: 
                   1067: - func (or funcone), computes logit (pij) distinguishing
                   1068:   o fixed variables (single or product dummies or quantitative);
                   1069:   o varying variables by:
                   1070:    (1) wave (single, product dummies, quantitative), 
                   1071:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                   1072:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                   1073:        % varying dummy (not done) or quantitative (not done);
                   1074: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                   1075:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                   1076: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
1.325     brouard  1077:   o There are 2**cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
1.226     brouard  1078:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard  1079: 
1.226     brouard  1080: 
                   1081:   
1.324     brouard  1082:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                   1083:            Institut national d'études démographiques, Paris.
1.126     brouard  1084:   This software have been partly granted by Euro-REVES, a concerted action
                   1085:   from the European Union.
                   1086:   It is copyrighted identically to a GNU software product, ie programme and
                   1087:   software can be distributed freely for non commercial use. Latest version
                   1088:   can be accessed at http://euroreves.ined.fr/imach .
                   1089: 
                   1090:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                   1091:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                   1092:   
                   1093:   **********************************************************************/
                   1094: /*
                   1095:   main
                   1096:   read parameterfile
                   1097:   read datafile
                   1098:   concatwav
                   1099:   freqsummary
                   1100:   if (mle >= 1)
                   1101:     mlikeli
                   1102:   print results files
                   1103:   if mle==1 
                   1104:      computes hessian
                   1105:   read end of parameter file: agemin, agemax, bage, fage, estepm
                   1106:       begin-prev-date,...
                   1107:   open gnuplot file
                   1108:   open html file
1.145     brouard  1109:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1110:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1111:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1112:     freexexit2 possible for memory heap.
                   1113: 
                   1114:   h Pij x                         | pij_nom  ficrestpij
                   1115:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1116:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1117:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1118: 
                   1119:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1120:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1121:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1122:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1123:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1124: 
1.126     brouard  1125:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1126:   health expectancies
                   1127:   Variance-covariance of DFLE
                   1128:   prevalence()
                   1129:    movingaverage()
                   1130:   varevsij() 
                   1131:   if popbased==1 varevsij(,popbased)
                   1132:   total life expectancies
                   1133:   Variance of period (stable) prevalence
                   1134:  end
                   1135: */
                   1136: 
1.187     brouard  1137: /* #define DEBUG */
                   1138: /* #define DEBUGBRENT */
1.203     brouard  1139: /* #define DEBUGLINMIN */
                   1140: /* #define DEBUGHESS */
                   1141: #define DEBUGHESSIJ
1.224     brouard  1142: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1143: #define POWELL /* Instead of NLOPT */
1.224     brouard  1144: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1145: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1146: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.319     brouard  1147: /* #define FLATSUP  *//* Suppresses directions where likelihood is flat */
1.126     brouard  1148: 
                   1149: #include <math.h>
                   1150: #include <stdio.h>
                   1151: #include <stdlib.h>
                   1152: #include <string.h>
1.226     brouard  1153: #include <ctype.h>
1.159     brouard  1154: 
                   1155: #ifdef _WIN32
                   1156: #include <io.h>
1.172     brouard  1157: #include <windows.h>
                   1158: #include <tchar.h>
1.159     brouard  1159: #else
1.126     brouard  1160: #include <unistd.h>
1.159     brouard  1161: #endif
1.126     brouard  1162: 
                   1163: #include <limits.h>
                   1164: #include <sys/types.h>
1.171     brouard  1165: 
                   1166: #if defined(__GNUC__)
                   1167: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1168: #endif
                   1169: 
1.126     brouard  1170: #include <sys/stat.h>
                   1171: #include <errno.h>
1.159     brouard  1172: /* extern int errno; */
1.126     brouard  1173: 
1.157     brouard  1174: /* #ifdef LINUX */
                   1175: /* #include <time.h> */
                   1176: /* #include "timeval.h" */
                   1177: /* #else */
                   1178: /* #include <sys/time.h> */
                   1179: /* #endif */
                   1180: 
1.126     brouard  1181: #include <time.h>
                   1182: 
1.136     brouard  1183: #ifdef GSL
                   1184: #include <gsl/gsl_errno.h>
                   1185: #include <gsl/gsl_multimin.h>
                   1186: #endif
                   1187: 
1.167     brouard  1188: 
1.162     brouard  1189: #ifdef NLOPT
                   1190: #include <nlopt.h>
                   1191: typedef struct {
                   1192:   double (* function)(double [] );
                   1193: } myfunc_data ;
                   1194: #endif
                   1195: 
1.126     brouard  1196: /* #include <libintl.h> */
                   1197: /* #define _(String) gettext (String) */
                   1198: 
1.251     brouard  1199: #define MAXLINE 2048 /* Was 256 and 1024. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1200: 
                   1201: #define GNUPLOTPROGRAM "gnuplot"
                   1202: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
1.329     brouard  1203: #define FILENAMELENGTH 256
1.126     brouard  1204: 
                   1205: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1206: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1207: 
1.144     brouard  1208: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                   1209: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1210: 
                   1211: #define NINTERVMAX 8
1.144     brouard  1212: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1213: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.325     brouard  1214: #define NCOVMAX 30  /**< Maximum number of covariates used in the model, including generated covariates V1*V2 or V1*age */
1.197     brouard  1215: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1216: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1217: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1218: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1219: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1220: /* #define AGESUP 130 */
1.288     brouard  1221: /* #define AGESUP 150 */
                   1222: #define AGESUP 200
1.268     brouard  1223: #define AGEINF 0
1.218     brouard  1224: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1225: #define AGEBASE 40
1.194     brouard  1226: #define AGEOVERFLOW 1.e20
1.164     brouard  1227: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1228: #ifdef _WIN32
                   1229: #define DIRSEPARATOR '\\'
                   1230: #define CHARSEPARATOR "\\"
                   1231: #define ODIRSEPARATOR '/'
                   1232: #else
1.126     brouard  1233: #define DIRSEPARATOR '/'
                   1234: #define CHARSEPARATOR "/"
                   1235: #define ODIRSEPARATOR '\\'
                   1236: #endif
                   1237: 
1.331   ! brouard  1238: /* $Id: imach.c,v 1.330 2022/08/06 07:18:25 brouard Exp $ */
1.126     brouard  1239: /* $State: Exp $ */
1.196     brouard  1240: #include "version.h"
                   1241: char version[]=__IMACH_VERSION__;
1.323     brouard  1242: char copyright[]="July 2022,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015-2020, Nihon University 2021-202, INED 2000-2022";
1.331   ! brouard  1243: char fullversion[]="$Revision: 1.330 $ $Date: 2022/08/06 07:18:25 $"; 
1.126     brouard  1244: char strstart[80];
                   1245: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1246: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard  1247: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.330     brouard  1248: /* Number of covariates model (1)=V2+V1+ V3*age+V2*V4 */
                   1249: /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   1250: int cptcovn=0; /**< cptcovn decodemodel: number of covariates k of the models excluding age*products =6 and age*age */
                   1251: int cptcovt=0; /**< cptcovt: total number of covariates of the model (2) nbocc(+)+1 = 8 excepting constant and age and age*age */
                   1252: int cptcovs=0; /**< cptcovs number of simple covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
1.225     brouard  1253: int cptcovsnq=0; /**< cptcovsnq number of simple covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1254: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                   1255: int cptcovprodnoage=0; /**< Number of covariate products without age */   
1.330     brouard  1256: int cptcoveff=0; /* Total number of covariates to vary for printing results (2**cptcoveff combinations of dummies)(computed in tricode as cptcov) */
1.233     brouard  1257: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1258: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.232     brouard  1259: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
1.234     brouard  1260: int nsd=0; /**< Total number of single dummy variables (output) */
                   1261: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1262: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1263: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1264: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1265: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1266: int cptcov=0; /* Working variable */
1.290     brouard  1267: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1268: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.302     brouard  1269: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
1.126     brouard  1270: int nlstate=2; /* Number of live states */
                   1271: int ndeath=1; /* Number of dead states */
1.130     brouard  1272: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.223     brouard  1273: int  nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable */ 
1.126     brouard  1274: int popbased=0;
                   1275: 
                   1276: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1277: int maxwav=0; /* Maxim number of waves */
                   1278: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1279: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1280: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard  1281:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1282: int mle=1, weightopt=0;
1.126     brouard  1283: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1284: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1285: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1286:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1287: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1288: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1289: 
1.130     brouard  1290: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1291: double **matprod2(); /* test */
1.126     brouard  1292: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1293: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1294: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1295: 
1.136     brouard  1296: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1297: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1298: FILE *ficlog, *ficrespow;
1.130     brouard  1299: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1300: double fretone; /* Only one call to likelihood */
1.130     brouard  1301: long ipmx=0; /* Number of contributions */
1.126     brouard  1302: double sw; /* Sum of weights */
                   1303: char filerespow[FILENAMELENGTH];
                   1304: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1305: FILE *ficresilk;
                   1306: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1307: FILE *ficresprobmorprev;
                   1308: FILE *fichtm, *fichtmcov; /* Html File */
                   1309: FILE *ficreseij;
                   1310: char filerese[FILENAMELENGTH];
                   1311: FILE *ficresstdeij;
                   1312: char fileresstde[FILENAMELENGTH];
                   1313: FILE *ficrescveij;
                   1314: char filerescve[FILENAMELENGTH];
                   1315: FILE  *ficresvij;
                   1316: char fileresv[FILENAMELENGTH];
1.269     brouard  1317: 
1.126     brouard  1318: char title[MAXLINE];
1.234     brouard  1319: char model[MAXLINE]; /**< The model line */
1.217     brouard  1320: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1321: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1322: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1323: char command[FILENAMELENGTH];
                   1324: int  outcmd=0;
                   1325: 
1.217     brouard  1326: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1327: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1328: char filelog[FILENAMELENGTH]; /* Log file */
                   1329: char filerest[FILENAMELENGTH];
                   1330: char fileregp[FILENAMELENGTH];
                   1331: char popfile[FILENAMELENGTH];
                   1332: 
                   1333: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1334: 
1.157     brouard  1335: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1336: /* struct timezone tzp; */
                   1337: /* extern int gettimeofday(); */
                   1338: struct tm tml, *gmtime(), *localtime();
                   1339: 
                   1340: extern time_t time();
                   1341: 
                   1342: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1343: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                   1344: struct tm tm;
                   1345: 
1.126     brouard  1346: char strcurr[80], strfor[80];
                   1347: 
                   1348: char *endptr;
                   1349: long lval;
                   1350: double dval;
                   1351: 
                   1352: #define NR_END 1
                   1353: #define FREE_ARG char*
                   1354: #define FTOL 1.0e-10
                   1355: 
                   1356: #define NRANSI 
1.240     brouard  1357: #define ITMAX 200
                   1358: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1359: 
                   1360: #define TOL 2.0e-4 
                   1361: 
                   1362: #define CGOLD 0.3819660 
                   1363: #define ZEPS 1.0e-10 
                   1364: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1365: 
                   1366: #define GOLD 1.618034 
                   1367: #define GLIMIT 100.0 
                   1368: #define TINY 1.0e-20 
                   1369: 
                   1370: static double maxarg1,maxarg2;
                   1371: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1372: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1373:   
                   1374: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1375: #define rint(a) floor(a+0.5)
1.166     brouard  1376: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1377: #define mytinydouble 1.0e-16
1.166     brouard  1378: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1379: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1380: /* static double dsqrarg; */
                   1381: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1382: static double sqrarg;
                   1383: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1384: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1385: int agegomp= AGEGOMP;
                   1386: 
                   1387: int imx; 
                   1388: int stepm=1;
                   1389: /* Stepm, step in month: minimum step interpolation*/
                   1390: 
                   1391: int estepm;
                   1392: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1393: 
                   1394: int m,nb;
                   1395: long *num;
1.197     brouard  1396: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1397: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1398:                   covariate for which somebody answered excluding 
                   1399:                   undefined. Usually 2: 0 and 1. */
                   1400: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1401:                             covariate for which somebody answered including 
                   1402:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1403: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1404: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1405: double ***mobaverage, ***mobaverages; /* New global variable */
1.126     brouard  1406: double *ageexmed,*agecens;
                   1407: double dateintmean=0;
1.296     brouard  1408:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1409:   double anprojf, mprojf, jprojf;
1.126     brouard  1410: 
1.296     brouard  1411:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1412:   double anbackf, mbackf, jbackf;
                   1413:   double jintmean,mintmean,aintmean;  
1.126     brouard  1414: double *weight;
                   1415: int **s; /* Status */
1.141     brouard  1416: double *agedc;
1.145     brouard  1417: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1418:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1419:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1420: double **coqvar; /* Fixed quantitative covariate nqv */
                   1421: double ***cotvar; /* Time varying covariate ntv */
1.225     brouard  1422: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1423: double  idx; 
                   1424: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.319     brouard  1425: /* Some documentation */
                   1426:       /*   Design original data
                   1427:        *  V1   V2   V3   V4  V5  V6  V7  V8  Weight ddb ddth d1st s1 V9 V10 V11 V12 s2 V9 V10 V11 V12 
                   1428:        *  <          ncovcol=6   >   nqv=2 (V7 V8)                   dv dv  dv  qtv    dv dv  dvv qtv
                   1429:        *                                                             ntv=3     nqtv=1
1.330     brouard  1430:        *  cptcovn number of covariates (not including constant and age or age*age) = number of plus sign + 1 = 10+1=11
1.319     brouard  1431:        * For time varying covariate, quanti or dummies
                   1432:        *       cotqvar[wav][iv(1 to nqtv)][i]= [1][12][i]=(V12) quanti
                   1433:        *       cotvar[wav][ntv+iv][i]= [3+(1 to nqtv)][i]=(V12) quanti
                   1434:        *       cotvar[wav][iv(1 to ntv)][i]= [1][1][i]=(V9) dummies at wav 1
                   1435:        *       cotvar[wav][iv(1 to ntv)][i]= [1][2][i]=(V10) dummies at wav 1
                   1436:        *       covar[k,i], value of kth fixed covariate dummy or quanti :
                   1437:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   1438:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 + V9 + V9*age + V10
                   1439:        *   k=  1    2      3       4     5       6      7        8   9     10       11 
                   1440:        */
                   1441: /* According to the model, more columns can be added to covar by the product of covariates */
1.318     brouard  1442: /* 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
                   1443:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1444:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1445: */
1.319     brouard  1446: /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1447: /*    k        1  2   3   4     5    6    7     8    9 */
                   1448: /*Typevar[k]=  0  0   0   2     1    0    2     1    0 *//*0 for simple covariate (dummy, quantitative,*/
                   1449:                                                          /* fixed or varying), 1 for age product, 2 for*/
                   1450:                                                          /* product */
                   1451: /*Dummy[k]=    1  0   0   1     3    1    1     2    0 *//*Dummy[k] 0=dummy (0 1), 1 quantitative */
                   1452:                                                          /*(single or product without age), 2 dummy*/
                   1453:                                                          /* with age product, 3 quant with age product*/
                   1454: /*Tvar[k]=     5  4   3   6     5    2    7     1    1 */
                   1455: /*    nsd         1   2                              3 */ /* Counting single dummies covar fixed or tv */
1.330     brouard  1456: /*TnsdVar[Tvar]   1   2                              3 */ 
1.319     brouard  1457: /*TvarsD[nsd]     4   3                              1 */ /* ID of single dummy cova fixed or timevary*/
                   1458: /*TvarsDind[k]    2   3                              9 */ /* position K of single dummy cova */
                   1459: /*    nsq      1                     2                 */ /* Counting single quantit tv */
                   1460: /* TvarsQ[k]   5                     2                 */ /* Number of single quantitative cova */
                   1461: /* TvarsQind   1                     6                 */ /* position K of single quantitative cova */
                   1462: /* Tprod[i]=k             1               2            */ /* Position in model of the ith prod without age */
                   1463: /* cptcovage                    1               2      */ /* Counting cov*age in the model equation */
                   1464: /* Tage[cptcovage]=k            5               8      */ /* Position in the model of ith cov*age */
                   1465: /* Tvard[1][1]@4={4,3,1,2}    V4*V3 V1*V2              */ /* Position in model of the ith prod without age */
1.330     brouard  1466: /* 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  1467: /* 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  1468: /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.234     brouard  1469: /* Type                    */
                   1470: /* V         1  2  3  4  5 */
                   1471: /*           F  F  V  V  V */
                   1472: /*           D  Q  D  D  Q */
                   1473: /*                         */
                   1474: int *TvarsD;
1.330     brouard  1475: int *TnsdVar;
1.234     brouard  1476: int *TvarsDind;
                   1477: int *TvarsQ;
                   1478: int *TvarsQind;
                   1479: 
1.318     brouard  1480: #define MAXRESULTLINESPONE 10+1
1.235     brouard  1481: int nresult=0;
1.258     brouard  1482: int parameterline=0; /* # of the parameter (type) line */
1.318     brouard  1483: int TKresult[MAXRESULTLINESPONE];
1.330     brouard  1484: int resultmodel[MAXRESULTLINESPONE][NCOVMAX];/* resultmodel[k1]=k3: k1th position in the model correspond to the k3 position in the resultline */
1.318     brouard  1485: int Tresult[MAXRESULTLINESPONE][NCOVMAX];/* For dummy variable , value (output) */
                   1486: int Tinvresult[MAXRESULTLINESPONE][NCOVMAX];/* For dummy variable , value (output) */
1.330     brouard  1487: int TinvDoQresult[MAXRESULTLINESPONE][NCOVMAX];/* For dummy variable or quanti value (output) */
1.318     brouard  1488: int Tvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For dummy variable , variable # (output) */
                   1489: double Tqresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
                   1490: double Tqinvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
                   1491: int Tvqresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , variable # (output) */
                   1492: 
                   1493: /* 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
                   1494:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1495:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1496: */
1.234     brouard  1497: /* 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  1498: 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 */
                   1499: 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 */
                   1500: 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 */
                   1501: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1502: 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 */
                   1503: 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  1504: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1505: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1506: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1507: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1508: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1509: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1510: 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 */
                   1511: 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 */
                   1512: 
1.230     brouard  1513: int *Tvarsel; /**< Selected covariates for output */
                   1514: double *Tvalsel; /**< Selected modality value of covariate for output */
1.226     brouard  1515: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.227     brouard  1516: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1517: 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  1518: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1519: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1520: int *Tage;
1.227     brouard  1521: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1522: 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  1523: 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*/ 
                   1524: 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  1525: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1526: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1527: int **Tvard;
1.330     brouard  1528: int **Tvardk;
1.227     brouard  1529: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1530: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1531: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1532:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1533:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1534: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1535: double *lsurv, *lpop, *tpop;
                   1536: 
1.231     brouard  1537: #define FD 1; /* Fixed dummy covariate */
                   1538: #define FQ 2; /* Fixed quantitative covariate */
                   1539: #define FP 3; /* Fixed product covariate */
                   1540: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1541: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1542: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1543: #define VD 10; /* Varying dummy covariate */
                   1544: #define VQ 11; /* Varying quantitative covariate */
                   1545: #define VP 12; /* Varying product covariate */
                   1546: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1547: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1548: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1549: #define APFD 16; /* Age product * fixed dummy covariate */
                   1550: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1551: #define APVD 18; /* Age product * varying dummy covariate */
                   1552: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1553: 
                   1554: #define FTYPE 1; /* Fixed covariate */
                   1555: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1556: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1557: 
                   1558: struct kmodel{
                   1559:        int maintype; /* main type */
                   1560:        int subtype; /* subtype */
                   1561: };
                   1562: struct kmodel modell[NCOVMAX];
                   1563: 
1.143     brouard  1564: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1565: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1566: 
                   1567: /**************** split *************************/
                   1568: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1569: {
                   1570:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1571:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1572:   */ 
                   1573:   char *ss;                            /* pointer */
1.186     brouard  1574:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1575: 
                   1576:   l1 = strlen(path );                  /* length of path */
                   1577:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1578:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1579:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1580:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1581:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1582:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1583:     /* get current working directory */
                   1584:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1585: #ifdef WIN32
                   1586:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1587: #else
                   1588:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1589: #endif
1.126     brouard  1590:       return( GLOCK_ERROR_GETCWD );
                   1591:     }
                   1592:     /* got dirc from getcwd*/
                   1593:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1594:   } else {                             /* strip directory from path */
1.126     brouard  1595:     ss++;                              /* after this, the filename */
                   1596:     l2 = strlen( ss );                 /* length of filename */
                   1597:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1598:     strcpy( name, ss );                /* save file name */
                   1599:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1600:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1601:     printf(" DIRC2 = %s \n",dirc);
                   1602:   }
                   1603:   /* We add a separator at the end of dirc if not exists */
                   1604:   l1 = strlen( dirc );                 /* length of directory */
                   1605:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1606:     dirc[l1] =  DIRSEPARATOR;
                   1607:     dirc[l1+1] = 0; 
                   1608:     printf(" DIRC3 = %s \n",dirc);
                   1609:   }
                   1610:   ss = strrchr( name, '.' );           /* find last / */
                   1611:   if (ss >0){
                   1612:     ss++;
                   1613:     strcpy(ext,ss);                    /* save extension */
                   1614:     l1= strlen( name);
                   1615:     l2= strlen(ss)+1;
                   1616:     strncpy( finame, name, l1-l2);
                   1617:     finame[l1-l2]= 0;
                   1618:   }
                   1619: 
                   1620:   return( 0 );                         /* we're done */
                   1621: }
                   1622: 
                   1623: 
                   1624: /******************************************/
                   1625: 
                   1626: void replace_back_to_slash(char *s, char*t)
                   1627: {
                   1628:   int i;
                   1629:   int lg=0;
                   1630:   i=0;
                   1631:   lg=strlen(t);
                   1632:   for(i=0; i<= lg; i++) {
                   1633:     (s[i] = t[i]);
                   1634:     if (t[i]== '\\') s[i]='/';
                   1635:   }
                   1636: }
                   1637: 
1.132     brouard  1638: char *trimbb(char *out, char *in)
1.137     brouard  1639: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1640:   char *s;
                   1641:   s=out;
                   1642:   while (*in != '\0'){
1.137     brouard  1643:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1644:       in++;
                   1645:     }
                   1646:     *out++ = *in++;
                   1647:   }
                   1648:   *out='\0';
                   1649:   return s;
                   1650: }
                   1651: 
1.187     brouard  1652: /* char *substrchaine(char *out, char *in, char *chain) */
                   1653: /* { */
                   1654: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1655: /*   char *s, *t; */
                   1656: /*   t=in;s=out; */
                   1657: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1658: /*     *out++ = *in++; */
                   1659: /*   } */
                   1660: 
                   1661: /*   /\* *in matches *chain *\/ */
                   1662: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1663: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1664: /*   } */
                   1665: /*   in--; chain--; */
                   1666: /*   while ( (*in != '\0')){ */
                   1667: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1668: /*     *out++ = *in++; */
                   1669: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1670: /*   } */
                   1671: /*   *out='\0'; */
                   1672: /*   out=s; */
                   1673: /*   return out; */
                   1674: /* } */
                   1675: char *substrchaine(char *out, char *in, char *chain)
                   1676: {
                   1677:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1678:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1679: 
                   1680:   char *strloc;
                   1681: 
                   1682:   strcpy (out, in); 
                   1683:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1684:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1685:   if(strloc != NULL){ 
                   1686:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1687:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1688:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1689:   }
                   1690:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1691:   return out;
                   1692: }
                   1693: 
                   1694: 
1.145     brouard  1695: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1696: {
1.187     brouard  1697:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1698:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.310     brouard  1699:      gives alocc="abcdef" and blocc="ghi2j".
1.145     brouard  1700:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1701:   */
1.160     brouard  1702:   char *s, *t;
1.145     brouard  1703:   t=in;s=in;
                   1704:   while ((*in != occ) && (*in != '\0')){
                   1705:     *alocc++ = *in++;
                   1706:   }
                   1707:   if( *in == occ){
                   1708:     *(alocc)='\0';
                   1709:     s=++in;
                   1710:   }
                   1711:  
                   1712:   if (s == t) {/* occ not found */
                   1713:     *(alocc-(in-s))='\0';
                   1714:     in=s;
                   1715:   }
                   1716:   while ( *in != '\0'){
                   1717:     *blocc++ = *in++;
                   1718:   }
                   1719: 
                   1720:   *blocc='\0';
                   1721:   return t;
                   1722: }
1.137     brouard  1723: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1724: {
1.187     brouard  1725:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1726:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1727:      gives blocc="abcdef2ghi" and alocc="j".
                   1728:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1729:   */
                   1730:   char *s, *t;
                   1731:   t=in;s=in;
                   1732:   while (*in != '\0'){
                   1733:     while( *in == occ){
                   1734:       *blocc++ = *in++;
                   1735:       s=in;
                   1736:     }
                   1737:     *blocc++ = *in++;
                   1738:   }
                   1739:   if (s == t) /* occ not found */
                   1740:     *(blocc-(in-s))='\0';
                   1741:   else
                   1742:     *(blocc-(in-s)-1)='\0';
                   1743:   in=s;
                   1744:   while ( *in != '\0'){
                   1745:     *alocc++ = *in++;
                   1746:   }
                   1747: 
                   1748:   *alocc='\0';
                   1749:   return s;
                   1750: }
                   1751: 
1.126     brouard  1752: int nbocc(char *s, char occ)
                   1753: {
                   1754:   int i,j=0;
                   1755:   int lg=20;
                   1756:   i=0;
                   1757:   lg=strlen(s);
                   1758:   for(i=0; i<= lg; i++) {
1.234     brouard  1759:     if  (s[i] == occ ) j++;
1.126     brouard  1760:   }
                   1761:   return j;
                   1762: }
                   1763: 
1.137     brouard  1764: /* void cutv(char *u,char *v, char*t, char occ) */
                   1765: /* { */
                   1766: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1767: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1768: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1769: /*   int i,lg,j,p=0; */
                   1770: /*   i=0; */
                   1771: /*   lg=strlen(t); */
                   1772: /*   for(j=0; j<=lg-1; j++) { */
                   1773: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1774: /*   } */
1.126     brouard  1775: 
1.137     brouard  1776: /*   for(j=0; j<p; j++) { */
                   1777: /*     (u[j] = t[j]); */
                   1778: /*   } */
                   1779: /*      u[p]='\0'; */
1.126     brouard  1780: 
1.137     brouard  1781: /*    for(j=0; j<= lg; j++) { */
                   1782: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1783: /*   } */
                   1784: /* } */
1.126     brouard  1785: 
1.160     brouard  1786: #ifdef _WIN32
                   1787: char * strsep(char **pp, const char *delim)
                   1788: {
                   1789:   char *p, *q;
                   1790:          
                   1791:   if ((p = *pp) == NULL)
                   1792:     return 0;
                   1793:   if ((q = strpbrk (p, delim)) != NULL)
                   1794:   {
                   1795:     *pp = q + 1;
                   1796:     *q = '\0';
                   1797:   }
                   1798:   else
                   1799:     *pp = 0;
                   1800:   return p;
                   1801: }
                   1802: #endif
                   1803: 
1.126     brouard  1804: /********************** nrerror ********************/
                   1805: 
                   1806: void nrerror(char error_text[])
                   1807: {
                   1808:   fprintf(stderr,"ERREUR ...\n");
                   1809:   fprintf(stderr,"%s\n",error_text);
                   1810:   exit(EXIT_FAILURE);
                   1811: }
                   1812: /*********************** vector *******************/
                   1813: double *vector(int nl, int nh)
                   1814: {
                   1815:   double *v;
                   1816:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1817:   if (!v) nrerror("allocation failure in vector");
                   1818:   return v-nl+NR_END;
                   1819: }
                   1820: 
                   1821: /************************ free vector ******************/
                   1822: void free_vector(double*v, int nl, int nh)
                   1823: {
                   1824:   free((FREE_ARG)(v+nl-NR_END));
                   1825: }
                   1826: 
                   1827: /************************ivector *******************************/
                   1828: int *ivector(long nl,long nh)
                   1829: {
                   1830:   int *v;
                   1831:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1832:   if (!v) nrerror("allocation failure in ivector");
                   1833:   return v-nl+NR_END;
                   1834: }
                   1835: 
                   1836: /******************free ivector **************************/
                   1837: void free_ivector(int *v, long nl, long nh)
                   1838: {
                   1839:   free((FREE_ARG)(v+nl-NR_END));
                   1840: }
                   1841: 
                   1842: /************************lvector *******************************/
                   1843: long *lvector(long nl,long nh)
                   1844: {
                   1845:   long *v;
                   1846:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1847:   if (!v) nrerror("allocation failure in ivector");
                   1848:   return v-nl+NR_END;
                   1849: }
                   1850: 
                   1851: /******************free lvector **************************/
                   1852: void free_lvector(long *v, long nl, long nh)
                   1853: {
                   1854:   free((FREE_ARG)(v+nl-NR_END));
                   1855: }
                   1856: 
                   1857: /******************* imatrix *******************************/
                   1858: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1859:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1860: { 
                   1861:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1862:   int **m; 
                   1863:   
                   1864:   /* allocate pointers to rows */ 
                   1865:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1866:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1867:   m += NR_END; 
                   1868:   m -= nrl; 
                   1869:   
                   1870:   
                   1871:   /* allocate rows and set pointers to them */ 
                   1872:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1873:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1874:   m[nrl] += NR_END; 
                   1875:   m[nrl] -= ncl; 
                   1876:   
                   1877:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1878:   
                   1879:   /* return pointer to array of pointers to rows */ 
                   1880:   return m; 
                   1881: } 
                   1882: 
                   1883: /****************** free_imatrix *************************/
                   1884: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1885:       int **m;
                   1886:       long nch,ncl,nrh,nrl; 
                   1887:      /* free an int matrix allocated by imatrix() */ 
                   1888: { 
                   1889:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1890:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1891: } 
                   1892: 
                   1893: /******************* matrix *******************************/
                   1894: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1895: {
                   1896:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1897:   double **m;
                   1898: 
                   1899:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1900:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1901:   m += NR_END;
                   1902:   m -= nrl;
                   1903: 
                   1904:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1905:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1906:   m[nrl] += NR_END;
                   1907:   m[nrl] -= ncl;
                   1908: 
                   1909:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1910:   return m;
1.145     brouard  1911:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1912: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1913: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1914:    */
                   1915: }
                   1916: 
                   1917: /*************************free matrix ************************/
                   1918: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1919: {
                   1920:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1921:   free((FREE_ARG)(m+nrl-NR_END));
                   1922: }
                   1923: 
                   1924: /******************* ma3x *******************************/
                   1925: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1926: {
                   1927:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1928:   double ***m;
                   1929: 
                   1930:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1931:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1932:   m += NR_END;
                   1933:   m -= nrl;
                   1934: 
                   1935:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1936:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1937:   m[nrl] += NR_END;
                   1938:   m[nrl] -= ncl;
                   1939: 
                   1940:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1941: 
                   1942:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1943:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1944:   m[nrl][ncl] += NR_END;
                   1945:   m[nrl][ncl] -= nll;
                   1946:   for (j=ncl+1; j<=nch; j++) 
                   1947:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1948:   
                   1949:   for (i=nrl+1; i<=nrh; i++) {
                   1950:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1951:     for (j=ncl+1; j<=nch; j++) 
                   1952:       m[i][j]=m[i][j-1]+nlay;
                   1953:   }
                   1954:   return m; 
                   1955:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1956:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1957:   */
                   1958: }
                   1959: 
                   1960: /*************************free ma3x ************************/
                   1961: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1962: {
                   1963:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1964:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1965:   free((FREE_ARG)(m+nrl-NR_END));
                   1966: }
                   1967: 
                   1968: /*************** function subdirf ***********/
                   1969: char *subdirf(char fileres[])
                   1970: {
                   1971:   /* Caution optionfilefiname is hidden */
                   1972:   strcpy(tmpout,optionfilefiname);
                   1973:   strcat(tmpout,"/"); /* Add to the right */
                   1974:   strcat(tmpout,fileres);
                   1975:   return tmpout;
                   1976: }
                   1977: 
                   1978: /*************** function subdirf2 ***********/
                   1979: char *subdirf2(char fileres[], char *preop)
                   1980: {
1.314     brouard  1981:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
                   1982:  Errors in subdirf, 2, 3 while printing tmpout is
1.315     brouard  1983:  rewritten within the same printf. Workaround: many printfs */
1.126     brouard  1984:   /* Caution optionfilefiname is hidden */
                   1985:   strcpy(tmpout,optionfilefiname);
                   1986:   strcat(tmpout,"/");
                   1987:   strcat(tmpout,preop);
                   1988:   strcat(tmpout,fileres);
                   1989:   return tmpout;
                   1990: }
                   1991: 
                   1992: /*************** function subdirf3 ***********/
                   1993: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1994: {
                   1995:   
                   1996:   /* Caution optionfilefiname is hidden */
                   1997:   strcpy(tmpout,optionfilefiname);
                   1998:   strcat(tmpout,"/");
                   1999:   strcat(tmpout,preop);
                   2000:   strcat(tmpout,preop2);
                   2001:   strcat(tmpout,fileres);
                   2002:   return tmpout;
                   2003: }
1.213     brouard  2004:  
                   2005: /*************** function subdirfext ***********/
                   2006: char *subdirfext(char fileres[], char *preop, char *postop)
                   2007: {
                   2008:   
                   2009:   strcpy(tmpout,preop);
                   2010:   strcat(tmpout,fileres);
                   2011:   strcat(tmpout,postop);
                   2012:   return tmpout;
                   2013: }
1.126     brouard  2014: 
1.213     brouard  2015: /*************** function subdirfext3 ***********/
                   2016: char *subdirfext3(char fileres[], char *preop, char *postop)
                   2017: {
                   2018:   
                   2019:   /* Caution optionfilefiname is hidden */
                   2020:   strcpy(tmpout,optionfilefiname);
                   2021:   strcat(tmpout,"/");
                   2022:   strcat(tmpout,preop);
                   2023:   strcat(tmpout,fileres);
                   2024:   strcat(tmpout,postop);
                   2025:   return tmpout;
                   2026: }
                   2027:  
1.162     brouard  2028: char *asc_diff_time(long time_sec, char ascdiff[])
                   2029: {
                   2030:   long sec_left, days, hours, minutes;
                   2031:   days = (time_sec) / (60*60*24);
                   2032:   sec_left = (time_sec) % (60*60*24);
                   2033:   hours = (sec_left) / (60*60) ;
                   2034:   sec_left = (sec_left) %(60*60);
                   2035:   minutes = (sec_left) /60;
                   2036:   sec_left = (sec_left) % (60);
                   2037:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   2038:   return ascdiff;
                   2039: }
                   2040: 
1.126     brouard  2041: /***************** f1dim *************************/
                   2042: extern int ncom; 
                   2043: extern double *pcom,*xicom;
                   2044: extern double (*nrfunc)(double []); 
                   2045:  
                   2046: double f1dim(double x) 
                   2047: { 
                   2048:   int j; 
                   2049:   double f;
                   2050:   double *xt; 
                   2051:  
                   2052:   xt=vector(1,ncom); 
                   2053:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   2054:   f=(*nrfunc)(xt); 
                   2055:   free_vector(xt,1,ncom); 
                   2056:   return f; 
                   2057: } 
                   2058: 
                   2059: /*****************brent *************************/
                   2060: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  2061: {
                   2062:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   2063:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   2064:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   2065:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   2066:    * returned function value. 
                   2067:   */
1.126     brouard  2068:   int iter; 
                   2069:   double a,b,d,etemp;
1.159     brouard  2070:   double fu=0,fv,fw,fx;
1.164     brouard  2071:   double ftemp=0.;
1.126     brouard  2072:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   2073:   double e=0.0; 
                   2074:  
                   2075:   a=(ax < cx ? ax : cx); 
                   2076:   b=(ax > cx ? ax : cx); 
                   2077:   x=w=v=bx; 
                   2078:   fw=fv=fx=(*f)(x); 
                   2079:   for (iter=1;iter<=ITMAX;iter++) { 
                   2080:     xm=0.5*(a+b); 
                   2081:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   2082:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   2083:     printf(".");fflush(stdout);
                   2084:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  2085: #ifdef DEBUGBRENT
1.126     brouard  2086:     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);
                   2087:     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);
                   2088:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   2089: #endif
                   2090:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   2091:       *xmin=x; 
                   2092:       return fx; 
                   2093:     } 
                   2094:     ftemp=fu;
                   2095:     if (fabs(e) > tol1) { 
                   2096:       r=(x-w)*(fx-fv); 
                   2097:       q=(x-v)*(fx-fw); 
                   2098:       p=(x-v)*q-(x-w)*r; 
                   2099:       q=2.0*(q-r); 
                   2100:       if (q > 0.0) p = -p; 
                   2101:       q=fabs(q); 
                   2102:       etemp=e; 
                   2103:       e=d; 
                   2104:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  2105:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  2106:       else { 
1.224     brouard  2107:                                d=p/q; 
                   2108:                                u=x+d; 
                   2109:                                if (u-a < tol2 || b-u < tol2) 
                   2110:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  2111:       } 
                   2112:     } else { 
                   2113:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2114:     } 
                   2115:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   2116:     fu=(*f)(u); 
                   2117:     if (fu <= fx) { 
                   2118:       if (u >= x) a=x; else b=x; 
                   2119:       SHFT(v,w,x,u) 
1.183     brouard  2120:       SHFT(fv,fw,fx,fu) 
                   2121:     } else { 
                   2122:       if (u < x) a=u; else b=u; 
                   2123:       if (fu <= fw || w == x) { 
1.224     brouard  2124:                                v=w; 
                   2125:                                w=u; 
                   2126:                                fv=fw; 
                   2127:                                fw=fu; 
1.183     brouard  2128:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  2129:                                v=u; 
                   2130:                                fv=fu; 
1.183     brouard  2131:       } 
                   2132:     } 
1.126     brouard  2133:   } 
                   2134:   nrerror("Too many iterations in brent"); 
                   2135:   *xmin=x; 
                   2136:   return fx; 
                   2137: } 
                   2138: 
                   2139: /****************** mnbrak ***********************/
                   2140: 
                   2141: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2142:            double (*func)(double)) 
1.183     brouard  2143: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2144: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2145: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2146: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2147:    */
1.126     brouard  2148:   double ulim,u,r,q, dum;
                   2149:   double fu; 
1.187     brouard  2150: 
                   2151:   double scale=10.;
                   2152:   int iterscale=0;
                   2153: 
                   2154:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2155:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2156: 
                   2157: 
                   2158:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2159:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2160:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2161:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2162:   /* } */
                   2163: 
1.126     brouard  2164:   if (*fb > *fa) { 
                   2165:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2166:     SHFT(dum,*fb,*fa,dum) 
                   2167:   } 
1.126     brouard  2168:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2169:   *fc=(*func)(*cx); 
1.183     brouard  2170: #ifdef DEBUG
1.224     brouard  2171:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2172:   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  2173: #endif
1.224     brouard  2174:   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  2175:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2176:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2177:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2178:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2179:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2180:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2181:       fu=(*func)(u); 
1.163     brouard  2182: #ifdef DEBUG
                   2183:       /* f(x)=A(x-u)**2+f(u) */
                   2184:       double A, fparabu; 
                   2185:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2186:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2187:       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);
                   2188:       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  2189:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2190:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2191:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2192:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2193: #endif 
1.184     brouard  2194: #ifdef MNBRAKORIGINAL
1.183     brouard  2195: #else
1.191     brouard  2196: /*       if (fu > *fc) { */
                   2197: /* #ifdef DEBUG */
                   2198: /*       printf("mnbrak4  fu > fc \n"); */
                   2199: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2200: /* #endif */
                   2201: /*     /\* 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 *\\/  *\/ */
                   2202: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2203: /*     dum=u; /\* Shifting c and u *\/ */
                   2204: /*     u = *cx; */
                   2205: /*     *cx = dum; */
                   2206: /*     dum = fu; */
                   2207: /*     fu = *fc; */
                   2208: /*     *fc =dum; */
                   2209: /*       } else { /\* end *\/ */
                   2210: /* #ifdef DEBUG */
                   2211: /*       printf("mnbrak3  fu < fc \n"); */
                   2212: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2213: /* #endif */
                   2214: /*     dum=u; /\* Shifting c and u *\/ */
                   2215: /*     u = *cx; */
                   2216: /*     *cx = dum; */
                   2217: /*     dum = fu; */
                   2218: /*     fu = *fc; */
                   2219: /*     *fc =dum; */
                   2220: /*       } */
1.224     brouard  2221: #ifdef DEBUGMNBRAK
                   2222:                 double A, fparabu; 
                   2223:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2224:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2225:      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);
                   2226:      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  2227: #endif
1.191     brouard  2228:       dum=u; /* Shifting c and u */
                   2229:       u = *cx;
                   2230:       *cx = dum;
                   2231:       dum = fu;
                   2232:       fu = *fc;
                   2233:       *fc =dum;
1.183     brouard  2234: #endif
1.162     brouard  2235:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2236: #ifdef DEBUG
1.224     brouard  2237:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2238:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2239: #endif
1.126     brouard  2240:       fu=(*func)(u); 
                   2241:       if (fu < *fc) { 
1.183     brouard  2242: #ifdef DEBUG
1.224     brouard  2243:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2244:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2245: #endif
                   2246:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2247:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2248: #ifdef DEBUG
                   2249:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2250: #endif
                   2251:       } 
1.162     brouard  2252:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2253: #ifdef DEBUG
1.224     brouard  2254:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2255:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2256: #endif
1.126     brouard  2257:       u=ulim; 
                   2258:       fu=(*func)(u); 
1.183     brouard  2259:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2260: #ifdef DEBUG
1.224     brouard  2261:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2262:       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  2263: #endif
1.126     brouard  2264:       u=(*cx)+GOLD*(*cx-*bx); 
                   2265:       fu=(*func)(u); 
1.224     brouard  2266: #ifdef DEBUG
                   2267:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2268:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2269: #endif
1.183     brouard  2270:     } /* end tests */
1.126     brouard  2271:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2272:     SHFT(*fa,*fb,*fc,fu) 
                   2273: #ifdef DEBUG
1.224     brouard  2274:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2275:       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  2276: #endif
                   2277:   } /* 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  2278: } 
                   2279: 
                   2280: /*************** linmin ************************/
1.162     brouard  2281: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2282: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2283: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2284: the value of func at the returned location p . This is actually all accomplished by calling the
                   2285: routines mnbrak and brent .*/
1.126     brouard  2286: int ncom; 
                   2287: double *pcom,*xicom;
                   2288: double (*nrfunc)(double []); 
                   2289:  
1.224     brouard  2290: #ifdef LINMINORIGINAL
1.126     brouard  2291: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2292: #else
                   2293: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2294: #endif
1.126     brouard  2295: { 
                   2296:   double brent(double ax, double bx, double cx, 
                   2297:               double (*f)(double), double tol, double *xmin); 
                   2298:   double f1dim(double x); 
                   2299:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2300:              double *fc, double (*func)(double)); 
                   2301:   int j; 
                   2302:   double xx,xmin,bx,ax; 
                   2303:   double fx,fb,fa;
1.187     brouard  2304: 
1.203     brouard  2305: #ifdef LINMINORIGINAL
                   2306: #else
                   2307:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2308: #endif
                   2309:   
1.126     brouard  2310:   ncom=n; 
                   2311:   pcom=vector(1,n); 
                   2312:   xicom=vector(1,n); 
                   2313:   nrfunc=func; 
                   2314:   for (j=1;j<=n;j++) { 
                   2315:     pcom[j]=p[j]; 
1.202     brouard  2316:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2317:   } 
1.187     brouard  2318: 
1.203     brouard  2319: #ifdef LINMINORIGINAL
                   2320:   xx=1.;
                   2321: #else
                   2322:   axs=0.0;
                   2323:   xxs=1.;
                   2324:   do{
                   2325:     xx= xxs;
                   2326: #endif
1.187     brouard  2327:     ax=0.;
                   2328:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2329:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2330:     /* 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))   */
                   2331:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2332:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2333:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2334:     /* 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  2335: #ifdef LINMINORIGINAL
                   2336: #else
                   2337:     if (fx != fx){
1.224     brouard  2338:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2339:                        printf("|");
                   2340:                        fprintf(ficlog,"|");
1.203     brouard  2341: #ifdef DEBUGLINMIN
1.224     brouard  2342:                        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  2343: #endif
                   2344:     }
1.224     brouard  2345:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2346: #endif
                   2347:   
1.191     brouard  2348: #ifdef DEBUGLINMIN
                   2349:   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  2350:   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  2351: #endif
1.224     brouard  2352: #ifdef LINMINORIGINAL
                   2353: #else
1.317     brouard  2354:   if(fb == fx){ /* Flat function in the direction */
                   2355:     xmin=xx;
1.224     brouard  2356:     *flat=1;
1.317     brouard  2357:   }else{
1.224     brouard  2358:     *flat=0;
                   2359: #endif
                   2360:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2361:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2362:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2363:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2364:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2365:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2366: #ifdef DEBUG
1.224     brouard  2367:   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);
                   2368:   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);
                   2369: #endif
                   2370: #ifdef LINMINORIGINAL
                   2371: #else
                   2372:                        }
1.126     brouard  2373: #endif
1.191     brouard  2374: #ifdef DEBUGLINMIN
                   2375:   printf("linmin end ");
1.202     brouard  2376:   fprintf(ficlog,"linmin end ");
1.191     brouard  2377: #endif
1.126     brouard  2378:   for (j=1;j<=n;j++) { 
1.203     brouard  2379: #ifdef LINMINORIGINAL
                   2380:     xi[j] *= xmin; 
                   2381: #else
                   2382: #ifdef DEBUGLINMIN
                   2383:     if(xxs <1.0)
                   2384:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2385: #endif
                   2386:     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) */
                   2387: #ifdef DEBUGLINMIN
                   2388:     if(xxs <1.0)
                   2389:       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 );
                   2390: #endif
                   2391: #endif
1.187     brouard  2392:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2393:   } 
1.191     brouard  2394: #ifdef DEBUGLINMIN
1.203     brouard  2395:   printf("\n");
1.191     brouard  2396:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2397:   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  2398:   for (j=1;j<=n;j++) { 
1.202     brouard  2399:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2400:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2401:     if(j % ncovmodel == 0){
1.191     brouard  2402:       printf("\n");
1.202     brouard  2403:       fprintf(ficlog,"\n");
                   2404:     }
1.191     brouard  2405:   }
1.203     brouard  2406: #else
1.191     brouard  2407: #endif
1.126     brouard  2408:   free_vector(xicom,1,n); 
                   2409:   free_vector(pcom,1,n); 
                   2410: } 
                   2411: 
                   2412: 
                   2413: /*************** powell ************************/
1.162     brouard  2414: /*
1.317     brouard  2415: Minimization of a function func of n variables. Input consists in an initial starting point
                   2416: p[1..n] ; an initial matrix xi[1..n][1..n]  whose columns contain the initial set of di-
                   2417: rections (usually the n unit vectors); and ftol, the fractional tolerance in the function value
                   2418: such that failure to decrease by more than this amount in one iteration signals doneness. On
1.162     brouard  2419: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2420: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2421:  */
1.224     brouard  2422: #ifdef LINMINORIGINAL
                   2423: #else
                   2424:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2425:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2426: #endif
1.126     brouard  2427: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2428:            double (*func)(double [])) 
                   2429: { 
1.224     brouard  2430: #ifdef LINMINORIGINAL
                   2431:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2432:              double (*func)(double [])); 
1.224     brouard  2433: #else 
1.241     brouard  2434:  void linmin(double p[], double xi[], int n, double *fret,
                   2435:             double (*func)(double []),int *flat); 
1.224     brouard  2436: #endif
1.239     brouard  2437:  int i,ibig,j,jk,k; 
1.126     brouard  2438:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2439:   double directest;
1.126     brouard  2440:   double fp,fptt;
                   2441:   double *xits;
                   2442:   int niterf, itmp;
                   2443: 
                   2444:   pt=vector(1,n); 
                   2445:   ptt=vector(1,n); 
                   2446:   xit=vector(1,n); 
                   2447:   xits=vector(1,n); 
                   2448:   *fret=(*func)(p); 
                   2449:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  2450:   rcurr_time = time(NULL);  
1.126     brouard  2451:   for (*iter=1;;++(*iter)) { 
                   2452:     ibig=0; 
                   2453:     del=0.0; 
1.157     brouard  2454:     rlast_time=rcurr_time;
                   2455:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2456:     rcurr_time = time(NULL);  
                   2457:     curr_time = *localtime(&rcurr_time);
1.324     brouard  2458:     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);
                   2459:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f gain=%.12f=%.3g %ld sec. %ld sec.",*iter,*fret, fp-*fret,fp-*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1.157     brouard  2460: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.324     brouard  2461:     fp=(*fret); /* From former iteration or initial value */
1.192     brouard  2462:     for (i=1;i<=n;i++) {
1.126     brouard  2463:       fprintf(ficrespow," %.12lf", p[i]);
                   2464:     }
1.239     brouard  2465:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2466:     printf("\n#model=  1      +     age ");
                   2467:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2468:     if(nagesqr==1){
1.241     brouard  2469:        printf("  + age*age  ");
                   2470:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2471:     }
                   2472:     for(j=1;j <=ncovmodel-2;j++){
                   2473:       if(Typevar[j]==0) {
                   2474:        printf("  +      V%d  ",Tvar[j]);
                   2475:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2476:       }else if(Typevar[j]==1) {
                   2477:        printf("  +    V%d*age ",Tvar[j]);
                   2478:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2479:       }else if(Typevar[j]==2) {
                   2480:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2481:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2482:       }
                   2483:     }
1.126     brouard  2484:     printf("\n");
1.239     brouard  2485: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2486: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2487:     fprintf(ficlog,"\n");
1.239     brouard  2488:     for(i=1,jk=1; i <=nlstate; i++){
                   2489:       for(k=1; k <=(nlstate+ndeath); k++){
                   2490:        if (k != i) {
                   2491:          printf("%d%d ",i,k);
                   2492:          fprintf(ficlog,"%d%d ",i,k);
                   2493:          for(j=1; j <=ncovmodel; j++){
                   2494:            printf("%12.7f ",p[jk]);
                   2495:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2496:            jk++; 
                   2497:          }
                   2498:          printf("\n");
                   2499:          fprintf(ficlog,"\n");
                   2500:        }
                   2501:       }
                   2502:     }
1.241     brouard  2503:     if(*iter <=3 && *iter >1){
1.157     brouard  2504:       tml = *localtime(&rcurr_time);
                   2505:       strcpy(strcurr,asctime(&tml));
                   2506:       rforecast_time=rcurr_time; 
1.126     brouard  2507:       itmp = strlen(strcurr);
                   2508:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2509:        strcurr[itmp-1]='\0';
1.162     brouard  2510:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2511:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  2512:       for(niterf=10;niterf<=30;niterf+=10){
1.241     brouard  2513:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2514:        forecast_time = *localtime(&rforecast_time);
                   2515:        strcpy(strfor,asctime(&forecast_time));
                   2516:        itmp = strlen(strfor);
                   2517:        if(strfor[itmp-1]=='\n')
                   2518:          strfor[itmp-1]='\0';
                   2519:        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);
                   2520:        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  2521:       }
                   2522:     }
1.187     brouard  2523:     for (i=1;i<=n;i++) { /* For each direction i */
                   2524:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2525:       fptt=(*fret); 
                   2526: #ifdef DEBUG
1.203     brouard  2527:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2528:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2529: #endif
1.203     brouard  2530:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2531:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2532: #ifdef LINMINORIGINAL
1.188     brouard  2533:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2534: #else
                   2535:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2536:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2537: #endif
                   2538:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2539:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2540:                                /* because that direction will be replaced unless the gain del is small */
                   2541:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2542:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2543:                                /* with the new direction. */
                   2544:                                del=fabs(fptt-(*fret)); 
                   2545:                                ibig=i; 
1.126     brouard  2546:       } 
                   2547: #ifdef DEBUG
                   2548:       printf("%d %.12e",i,(*fret));
                   2549:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2550:       for (j=1;j<=n;j++) {
1.224     brouard  2551:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2552:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2553:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2554:       }
                   2555:       for(j=1;j<=n;j++) {
1.225     brouard  2556:                                printf(" p(%d)=%.12e",j,p[j]);
                   2557:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2558:       }
                   2559:       printf("\n");
                   2560:       fprintf(ficlog,"\n");
                   2561: #endif
1.187     brouard  2562:     } /* end loop on each direction i */
                   2563:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2564:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2565:     /* New value of last point Pn is not computed, P(n-1) */
1.319     brouard  2566:     for(j=1;j<=n;j++) {
                   2567:       if(flatdir[j] >0){
                   2568:         printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2569:         fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
1.302     brouard  2570:       }
1.319     brouard  2571:       /* printf("\n"); */
                   2572:       /* fprintf(ficlog,"\n"); */
                   2573:     }
1.243     brouard  2574:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2575:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2576:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2577:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2578:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2579:       /* decreased of more than 3.84  */
                   2580:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2581:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2582:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2583:                        
1.188     brouard  2584:       /* Starting the program with initial values given by a former maximization will simply change */
                   2585:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2586:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2587:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2588: #ifdef DEBUG
                   2589:       int k[2],l;
                   2590:       k[0]=1;
                   2591:       k[1]=-1;
                   2592:       printf("Max: %.12e",(*func)(p));
                   2593:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2594:       for (j=1;j<=n;j++) {
                   2595:        printf(" %.12e",p[j]);
                   2596:        fprintf(ficlog," %.12e",p[j]);
                   2597:       }
                   2598:       printf("\n");
                   2599:       fprintf(ficlog,"\n");
                   2600:       for(l=0;l<=1;l++) {
                   2601:        for (j=1;j<=n;j++) {
                   2602:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2603:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2604:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2605:        }
                   2606:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2607:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2608:       }
                   2609: #endif
                   2610: 
                   2611:       free_vector(xit,1,n); 
                   2612:       free_vector(xits,1,n); 
                   2613:       free_vector(ptt,1,n); 
                   2614:       free_vector(pt,1,n); 
                   2615:       return; 
1.192     brouard  2616:     } /* enough precision */ 
1.240     brouard  2617:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2618:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2619:       ptt[j]=2.0*p[j]-pt[j]; 
                   2620:       xit[j]=p[j]-pt[j]; 
                   2621:       pt[j]=p[j]; 
                   2622:     } 
1.181     brouard  2623:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2624: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2625:                if (*iter <=4) {
1.225     brouard  2626: #else
                   2627: #endif
1.224     brouard  2628: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2629: #else
1.161     brouard  2630:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2631: #endif
1.162     brouard  2632:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2633:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2634:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2635:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2636:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2637:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2638:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2639:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2640:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2641:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2642:       /* mu² and del² are equal when f3=f1 */
                   2643:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2644:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2645:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2646:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2647: #ifdef NRCORIGINAL
                   2648:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2649: #else
                   2650:       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  2651:       t= t- del*SQR(fp-fptt);
1.183     brouard  2652: #endif
1.202     brouard  2653:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2654: #ifdef DEBUG
1.181     brouard  2655:       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);
                   2656:       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  2657:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2658:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2659:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2660:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2661:       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);
                   2662:       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);
                   2663: #endif
1.183     brouard  2664: #ifdef POWELLORIGINAL
                   2665:       if (t < 0.0) { /* Then we use it for new direction */
                   2666: #else
1.182     brouard  2667:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2668:                                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  2669:         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  2670:         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  2671:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2672:       } 
1.181     brouard  2673:       if (directest < 0.0) { /* Then we use it for new direction */
                   2674: #endif
1.191     brouard  2675: #ifdef DEBUGLINMIN
1.234     brouard  2676:        printf("Before linmin in direction P%d-P0\n",n);
                   2677:        for (j=1;j<=n;j++) {
                   2678:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2679:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2680:          if(j % ncovmodel == 0){
                   2681:            printf("\n");
                   2682:            fprintf(ficlog,"\n");
                   2683:          }
                   2684:        }
1.224     brouard  2685: #endif
                   2686: #ifdef LINMINORIGINAL
1.234     brouard  2687:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2688: #else
1.234     brouard  2689:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2690:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2691: #endif
1.234     brouard  2692:        
1.191     brouard  2693: #ifdef DEBUGLINMIN
1.234     brouard  2694:        for (j=1;j<=n;j++) { 
                   2695:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2696:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2697:          if(j % ncovmodel == 0){
                   2698:            printf("\n");
                   2699:            fprintf(ficlog,"\n");
                   2700:          }
                   2701:        }
1.224     brouard  2702: #endif
1.234     brouard  2703:        for (j=1;j<=n;j++) { 
                   2704:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2705:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2706:        }
1.224     brouard  2707: #ifdef LINMINORIGINAL
                   2708: #else
1.234     brouard  2709:        for (j=1, flatd=0;j<=n;j++) {
                   2710:          if(flatdir[j]>0)
                   2711:            flatd++;
                   2712:        }
                   2713:        if(flatd >0){
1.255     brouard  2714:          printf("%d flat directions: ",flatd);
                   2715:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  2716:          for (j=1;j<=n;j++) { 
                   2717:            if(flatdir[j]>0){
                   2718:              printf("%d ",j);
                   2719:              fprintf(ficlog,"%d ",j);
                   2720:            }
                   2721:          }
                   2722:          printf("\n");
                   2723:          fprintf(ficlog,"\n");
1.319     brouard  2724: #ifdef FLATSUP
                   2725:           free_vector(xit,1,n); 
                   2726:           free_vector(xits,1,n); 
                   2727:           free_vector(ptt,1,n); 
                   2728:           free_vector(pt,1,n); 
                   2729:           return;
                   2730: #endif
1.234     brouard  2731:        }
1.191     brouard  2732: #endif
1.234     brouard  2733:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2734:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2735:        
1.126     brouard  2736: #ifdef DEBUG
1.234     brouard  2737:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2738:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2739:        for(j=1;j<=n;j++){
                   2740:          printf(" %lf",xit[j]);
                   2741:          fprintf(ficlog," %lf",xit[j]);
                   2742:        }
                   2743:        printf("\n");
                   2744:        fprintf(ficlog,"\n");
1.126     brouard  2745: #endif
1.192     brouard  2746:       } /* end of t or directest negative */
1.224     brouard  2747: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2748: #else
1.234     brouard  2749:       } /* end if (fptt < fp)  */
1.192     brouard  2750: #endif
1.225     brouard  2751: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2752:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2753: #else
1.224     brouard  2754: #endif
1.234     brouard  2755:                } /* loop iteration */ 
1.126     brouard  2756: } 
1.234     brouard  2757:   
1.126     brouard  2758: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2759:   
1.235     brouard  2760:   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  2761:   {
1.279     brouard  2762:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij 
                   2763:      *   (and selected quantitative values in nres)
                   2764:      *  by left multiplying the unit
                   2765:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   2766:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   2767:      * Wx is row vector: population in state 1, population in state 2, population dead
                   2768:      * or prevalence in state 1, prevalence in state 2, 0
                   2769:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   2770:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   2771:      * Output is prlim.
                   2772:      * Initial matrix pimij 
                   2773:      */
1.206     brouard  2774:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2775:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2776:   /*  0,                   0                  , 1} */
                   2777:   /*
                   2778:    * and after some iteration: */
                   2779:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2780:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2781:   /*  0,                   0                  , 1} */
                   2782:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2783:   /* {0.51571254859325999, 0.4842874514067399, */
                   2784:   /*  0.51326036147820708, 0.48673963852179264} */
                   2785:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2786:     
1.126     brouard  2787:   int i, ii,j,k;
1.209     brouard  2788:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2789:   /* double **matprod2(); */ /* test */
1.218     brouard  2790:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2791:   double **newm;
1.209     brouard  2792:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2793:   int ncvloop=0;
1.288     brouard  2794:   int first=0;
1.169     brouard  2795:   
1.209     brouard  2796:   min=vector(1,nlstate);
                   2797:   max=vector(1,nlstate);
                   2798:   meandiff=vector(1,nlstate);
                   2799: 
1.218     brouard  2800:        /* Starting with matrix unity */
1.126     brouard  2801:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2802:     for (j=1;j<=nlstate+ndeath;j++){
                   2803:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2804:     }
1.169     brouard  2805:   
                   2806:   cov[1]=1.;
                   2807:   
                   2808:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2809:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2810:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2811:     ncvloop++;
1.126     brouard  2812:     newm=savm;
                   2813:     /* Covariates have to be included here again */
1.138     brouard  2814:     cov[2]=agefin;
1.319     brouard  2815:      if(nagesqr==1){
                   2816:       cov[3]= agefin*agefin;
                   2817:      }
1.234     brouard  2818:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2819:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
1.330     brouard  2820:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])];
1.319     brouard  2821:       /* cov[++k1]=nbcode[TvarsD[k]][codtabm(ij,k)]; */
1.235     brouard  2822:       /* 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)); */
1.234     brouard  2823:     }
                   2824:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2825:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
1.319     brouard  2826:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];
                   2827:       /* cov[++k1]=Tqresult[nres][k];  */
1.235     brouard  2828:       /* 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]); */
1.138     brouard  2829:     }
1.237     brouard  2830:     for (k=1; k<=cptcovage;k++){  /* For product with age */
1.319     brouard  2831:       if(Dummy[Tage[k]]==2){ /* dummy with age */
1.330     brouard  2832:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2];
1.319     brouard  2833:        /* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   2834:       } else if(Dummy[Tage[k]]==3){ /* quantitative with age */
                   2835:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];
                   2836:        /* cov[++k1]=Tqresult[nres][k];  */
1.234     brouard  2837:       }
1.235     brouard  2838:       /* 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]); */
1.234     brouard  2839:     }
1.237     brouard  2840:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
1.235     brouard  2841:       /* 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]); */
1.329     brouard  2842:       if(Dummy[Tvard[k][1]]==0){
                   2843:        if(Dummy[Tvard[k][2]]==0){
1.330     brouard  2844:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])];
1.319     brouard  2845:          /* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.237     brouard  2846:        }else{
1.330     brouard  2847:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k];
1.319     brouard  2848:          /* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; */
1.237     brouard  2849:        }
                   2850:       }else{
1.329     brouard  2851:        if(Dummy[Tvard[k][2]]==0){
1.330     brouard  2852:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]];
1.319     brouard  2853:          /* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; */
1.237     brouard  2854:        }else{
                   2855:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
1.319     brouard  2856:          /* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
1.237     brouard  2857:        }
                   2858:       }
1.234     brouard  2859:     }
1.138     brouard  2860:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2861:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2862:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2863:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2864:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.319     brouard  2865:     /* age and covariate values of ij are in 'cov' */
1.142     brouard  2866:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2867:     
1.126     brouard  2868:     savm=oldm;
                   2869:     oldm=newm;
1.209     brouard  2870: 
                   2871:     for(j=1; j<=nlstate; j++){
                   2872:       max[j]=0.;
                   2873:       min[j]=1.;
                   2874:     }
                   2875:     for(i=1;i<=nlstate;i++){
                   2876:       sumnew=0;
                   2877:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2878:       for(j=1; j<=nlstate; j++){ 
                   2879:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2880:        max[j]=FMAX(max[j],prlim[i][j]);
                   2881:        min[j]=FMIN(min[j],prlim[i][j]);
                   2882:       }
                   2883:     }
                   2884: 
1.126     brouard  2885:     maxmax=0.;
1.209     brouard  2886:     for(j=1; j<=nlstate; j++){
                   2887:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2888:       maxmax=FMAX(maxmax,meandiff[j]);
                   2889:       /* 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  2890:     } /* j loop */
1.203     brouard  2891:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2892:     /* 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  2893:     if(maxmax < ftolpl){
1.209     brouard  2894:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2895:       free_vector(min,1,nlstate);
                   2896:       free_vector(max,1,nlstate);
                   2897:       free_vector(meandiff,1,nlstate);
1.126     brouard  2898:       return prlim;
                   2899:     }
1.288     brouard  2900:   } /* agefin loop */
1.208     brouard  2901:     /* After some age loop it doesn't converge */
1.288     brouard  2902:   if(!first){
                   2903:     first=1;
                   2904:     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  2905:     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);
                   2906:   }else if (first >=1 && first <10){
                   2907:     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);
                   2908:     first++;
                   2909:   }else if (first ==10){
                   2910:     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);
                   2911:     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");
                   2912:     fprintf(ficlog,"Warning: the stable prevalence no convergence; too many cases, giving up noticing, even in log file\n");
                   2913:     first++;
1.288     brouard  2914:   }
                   2915: 
1.209     brouard  2916:   /* 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); */
                   2917:   free_vector(min,1,nlstate);
                   2918:   free_vector(max,1,nlstate);
                   2919:   free_vector(meandiff,1,nlstate);
1.208     brouard  2920:   
1.169     brouard  2921:   return prlim; /* should not reach here */
1.126     brouard  2922: }
                   2923: 
1.217     brouard  2924: 
                   2925:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   2926: 
1.218     brouard  2927:  /* 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) */
                   2928:  /* 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  2929:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  2930: {
1.264     brouard  2931:   /* 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  2932:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   2933:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2934:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2935:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2936:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2937:   /* Initial matrix pimij */
                   2938:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2939:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2940:   /*  0,                   0                  , 1} */
                   2941:   /*
                   2942:    * and after some iteration: */
                   2943:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2944:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2945:   /*  0,                   0                  , 1} */
                   2946:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2947:   /* {0.51571254859325999, 0.4842874514067399, */
                   2948:   /*  0.51326036147820708, 0.48673963852179264} */
                   2949:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2950: 
                   2951:   int i, ii,j,k;
1.247     brouard  2952:   int first=0;
1.217     brouard  2953:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   2954:   /* double **matprod2(); */ /* test */
                   2955:   double **out, cov[NCOVMAX+1], **bmij();
                   2956:   double **newm;
1.218     brouard  2957:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   2958:   double        **oldm, **savm;  /* for use */
                   2959: 
1.217     brouard  2960:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   2961:   int ncvloop=0;
                   2962:   
                   2963:   min=vector(1,nlstate);
                   2964:   max=vector(1,nlstate);
                   2965:   meandiff=vector(1,nlstate);
                   2966: 
1.266     brouard  2967:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   2968:   oldm=oldms; savm=savms;
                   2969:   
                   2970:   /* Starting with matrix unity */
                   2971:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2972:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  2973:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2974:     }
                   2975:   
                   2976:   cov[1]=1.;
                   2977:   
                   2978:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2979:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  2980:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  2981:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   2982:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  2983:     ncvloop++;
1.218     brouard  2984:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   2985:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  2986:     /* Covariates have to be included here again */
                   2987:     cov[2]=agefin;
1.319     brouard  2988:     if(nagesqr==1){
1.217     brouard  2989:       cov[3]= agefin*agefin;;
1.319     brouard  2990:     }
1.242     brouard  2991:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2992:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
1.330     brouard  2993:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])];
1.264     brouard  2994:       /* 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)); */
1.242     brouard  2995:     }
                   2996:     /* for (k=1; k<=cptcovn;k++) { */
                   2997:     /*   /\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\/ */
                   2998:     /*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   2999:     /*   /\* 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])]); *\/ */
                   3000:     /* } */
                   3001:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   3002:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   3003:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   3004:       /* 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]); */
                   3005:     }
                   3006:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; */
                   3007:     /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
                   3008:     /*   /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\/ */
                   3009:     /*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; */
                   3010:     for (k=1; k<=cptcovage;k++){  /* For product with age */
1.319     brouard  3011:       /* if(Dummy[Tvar[Tage[k]]]== 2){ /\* dummy with age *\/ ERROR ???*/
                   3012:       if(Dummy[Tage[k]]== 2){ /* dummy with age */
1.330     brouard  3013:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2];
1.319     brouard  3014:       } else if(Dummy[Tage[k]]== 3){ /* quantitative with age */
                   3015:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];
1.242     brouard  3016:       }
                   3017:       /* 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]); */
                   3018:     }
                   3019:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
                   3020:       /* 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]); */
1.329     brouard  3021:       if(Dummy[Tvard[k][1]]==0){
                   3022:        if(Dummy[Tvard[k][2]]==0){
1.330     brouard  3023:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])];
1.242     brouard  3024:        }else{
1.330     brouard  3025:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k];
1.242     brouard  3026:        }
                   3027:       }else{
1.329     brouard  3028:        if(Dummy[Tvard[k][2]]==0){
1.330     brouard  3029:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]];
1.242     brouard  3030:        }else{
                   3031:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   3032:        }
                   3033:       }
1.217     brouard  3034:     }
                   3035:     
                   3036:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3037:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3038:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   3039:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3040:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  3041:                /* ij should be linked to the correct index of cov */
                   3042:                /* age and covariate values ij are in 'cov', but we need to pass
                   3043:                 * ij for the observed prevalence at age and status and covariate
                   3044:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   3045:                 */
                   3046:     /* 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 *\/ */
                   3047:     /* 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 *\/ */
                   3048:     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  3049:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  3050:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   3051:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   3052:     /*         printf("%d newm= ",i); */
                   3053:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3054:     /*           printf("%f ",newm[i][j]); */
                   3055:     /*         } */
                   3056:     /*         printf("oldm * "); */
                   3057:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3058:     /*           printf("%f ",oldm[i][j]); */
                   3059:     /*         } */
1.268     brouard  3060:     /*         printf(" bmmij "); */
1.266     brouard  3061:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3062:     /*           printf("%f ",pmmij[i][j]); */
                   3063:     /*         } */
                   3064:     /*         printf("\n"); */
                   3065:     /*   } */
                   3066:     /* } */
1.217     brouard  3067:     savm=oldm;
                   3068:     oldm=newm;
1.266     brouard  3069: 
1.217     brouard  3070:     for(j=1; j<=nlstate; j++){
                   3071:       max[j]=0.;
                   3072:       min[j]=1.;
                   3073:     }
                   3074:     for(j=1; j<=nlstate; j++){ 
                   3075:       for(i=1;i<=nlstate;i++){
1.234     brouard  3076:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   3077:        bprlim[i][j]= newm[i][j];
                   3078:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   3079:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  3080:       }
                   3081:     }
1.218     brouard  3082:                
1.217     brouard  3083:     maxmax=0.;
                   3084:     for(i=1; i<=nlstate; i++){
1.318     brouard  3085:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column, could be nan! */
1.217     brouard  3086:       maxmax=FMAX(maxmax,meandiff[i]);
                   3087:       /* 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  3088:     } /* i loop */
1.217     brouard  3089:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  3090:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3091:     if(maxmax < ftolpl){
1.220     brouard  3092:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3093:       free_vector(min,1,nlstate);
                   3094:       free_vector(max,1,nlstate);
                   3095:       free_vector(meandiff,1,nlstate);
                   3096:       return bprlim;
                   3097:     }
1.288     brouard  3098:   } /* agefin loop */
1.217     brouard  3099:     /* After some age loop it doesn't converge */
1.288     brouard  3100:   if(!first){
1.247     brouard  3101:     first=1;
                   3102:     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\
                   3103: 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);
                   3104:   }
                   3105:   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  3106: 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);
                   3107:   /* 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); */
                   3108:   free_vector(min,1,nlstate);
                   3109:   free_vector(max,1,nlstate);
                   3110:   free_vector(meandiff,1,nlstate);
                   3111:   
                   3112:   return bprlim; /* should not reach here */
                   3113: }
                   3114: 
1.126     brouard  3115: /*************** transition probabilities ***************/ 
                   3116: 
                   3117: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   3118: {
1.138     brouard  3119:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  3120:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  3121:      model to the ncovmodel covariates (including constant and age).
                   3122:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3123:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3124:      ncth covariate in the global vector x is given by the formula:
                   3125:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3126:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3127:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3128:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  3129:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  3130:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  3131:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  3132:   */
                   3133:   double s1, lnpijopii;
1.126     brouard  3134:   /*double t34;*/
1.164     brouard  3135:   int i,j, nc, ii, jj;
1.126     brouard  3136: 
1.223     brouard  3137:   for(i=1; i<= nlstate; i++){
                   3138:     for(j=1; j<i;j++){
                   3139:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3140:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3141:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3142:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3143:       }
                   3144:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3145:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3146:     }
                   3147:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3148:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3149:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3150:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3151:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3152:       }
                   3153:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3154:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3155:     }
                   3156:   }
1.218     brouard  3157:   
1.223     brouard  3158:   for(i=1; i<= nlstate; i++){
                   3159:     s1=0;
                   3160:     for(j=1; j<i; j++){
                   3161:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.330     brouard  3162:       /* 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  3163:     }
                   3164:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3165:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.330     brouard  3166:       /* 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  3167:     }
                   3168:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3169:     ps[i][i]=1./(s1+1.);
                   3170:     /* Computing other pijs */
                   3171:     for(j=1; j<i; j++)
1.325     brouard  3172:       ps[i][j]= exp(ps[i][j])*ps[i][i];/* Bug valgrind */
1.223     brouard  3173:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3174:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3175:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3176:   } /* end i */
1.218     brouard  3177:   
1.223     brouard  3178:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3179:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3180:       ps[ii][jj]=0;
                   3181:       ps[ii][ii]=1;
                   3182:     }
                   3183:   }
1.294     brouard  3184: 
                   3185: 
1.223     brouard  3186:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3187:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3188:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3189:   /*   } */
                   3190:   /*   printf("\n "); */
                   3191:   /* } */
                   3192:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3193:   /*
                   3194:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  3195:                goto end;*/
1.266     brouard  3196:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  3197: }
                   3198: 
1.218     brouard  3199: /*************** backward transition probabilities ***************/ 
                   3200: 
                   3201:  /* 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 ) */
                   3202: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   3203:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   3204: {
1.302     brouard  3205:   /* 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  3206:    * 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  3207:    */
1.218     brouard  3208:   int i, ii, j,k;
1.222     brouard  3209:   
                   3210:   double **out, **pmij();
                   3211:   double sumnew=0.;
1.218     brouard  3212:   double agefin;
1.292     brouard  3213:   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  3214:   double **dnewm, **dsavm, **doldm;
                   3215:   double **bbmij;
                   3216:   
1.218     brouard  3217:   doldm=ddoldms; /* global pointers */
1.222     brouard  3218:   dnewm=ddnewms;
                   3219:   dsavm=ddsavms;
1.318     brouard  3220: 
                   3221:   /* Debug */
                   3222:   /* printf("Bmij ij=%d, cov[2}=%f\n", ij, cov[2]); */
1.222     brouard  3223:   agefin=cov[2];
1.268     brouard  3224:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  3225:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  3226:      the observed prevalence (with this covariate ij) at beginning of transition */
                   3227:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  3228: 
                   3229:   /* P_x */
1.325     brouard  3230:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm *//* Bug valgrind */
1.268     brouard  3231:   /* outputs pmmij which is a stochastic matrix in row */
                   3232: 
                   3233:   /* Diag(w_x) */
1.292     brouard  3234:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  3235:   sumnew=0.;
1.269     brouard  3236:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  3237:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  3238:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  3239:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   3240:   }
                   3241:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   3242:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3243:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  3244:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  3245:     }
                   3246:   }else{
                   3247:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3248:       for (j=1;j<=nlstate+ndeath;j++)
                   3249:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   3250:     }
                   3251:     /* if(sumnew <0.9){ */
                   3252:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   3253:     /* } */
                   3254:   }
                   3255:   k3=0.0;  /* We put the last diagonal to 0 */
                   3256:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   3257:       doldm[ii][ii]= k3;
                   3258:   }
                   3259:   /* End doldm, At the end doldm is diag[(w_i)] */
                   3260:   
1.292     brouard  3261:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   3262:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  3263: 
1.292     brouard  3264:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  3265:   /* 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  3266:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  3267:     sumnew=0.;
1.222     brouard  3268:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  3269:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  3270:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  3271:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  3272:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  3273:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  3274:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3275:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  3276:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3277:        /* }else */
1.268     brouard  3278:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   3279:     } /*End ii */
                   3280:   } /* 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 */
                   3281: 
1.292     brouard  3282:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  3283:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  3284:   /* end bmij */
1.266     brouard  3285:   return ps; /*pointer is unchanged */
1.218     brouard  3286: }
1.217     brouard  3287: /*************** transition probabilities ***************/ 
                   3288: 
1.218     brouard  3289: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  3290: {
                   3291:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3292:      computes the probability to be observed in state j being in state i by appying the
                   3293:      model to the ncovmodel covariates (including constant and age).
                   3294:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3295:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3296:      ncth covariate in the global vector x is given by the formula:
                   3297:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3298:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3299:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3300:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3301:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   3302:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3303:   */
                   3304:   double s1, lnpijopii;
                   3305:   /*double t34;*/
                   3306:   int i,j, nc, ii, jj;
                   3307: 
1.234     brouard  3308:   for(i=1; i<= nlstate; i++){
                   3309:     for(j=1; j<i;j++){
                   3310:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3311:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3312:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3313:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3314:       }
                   3315:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3316:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3317:     }
                   3318:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3319:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3320:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3321:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3322:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3323:       }
                   3324:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3325:     }
                   3326:   }
                   3327:   
                   3328:   for(i=1; i<= nlstate; i++){
                   3329:     s1=0;
                   3330:     for(j=1; j<i; j++){
                   3331:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3332:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3333:     }
                   3334:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3335:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3336:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3337:     }
                   3338:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3339:     ps[i][i]=1./(s1+1.);
                   3340:     /* Computing other pijs */
                   3341:     for(j=1; j<i; j++)
                   3342:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3343:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3344:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3345:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3346:   } /* end i */
                   3347:   
                   3348:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3349:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3350:       ps[ii][jj]=0;
                   3351:       ps[ii][ii]=1;
                   3352:     }
                   3353:   }
1.296     brouard  3354:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  3355:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3356:     s1=0.;
                   3357:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   3358:       s1+=ps[ii][jj];
                   3359:     }
                   3360:     for(ii=1; ii<= nlstate; ii++){
                   3361:       ps[ii][jj]=ps[ii][jj]/s1;
                   3362:     }
                   3363:   }
                   3364:   /* Transposition */
                   3365:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3366:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   3367:       s1=ps[ii][jj];
                   3368:       ps[ii][jj]=ps[jj][ii];
                   3369:       ps[jj][ii]=s1;
                   3370:     }
                   3371:   }
                   3372:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3373:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3374:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3375:   /*   } */
                   3376:   /*   printf("\n "); */
                   3377:   /* } */
                   3378:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3379:   /*
                   3380:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3381:     goto end;*/
                   3382:   return ps;
1.217     brouard  3383: }
                   3384: 
                   3385: 
1.126     brouard  3386: /**************** Product of 2 matrices ******************/
                   3387: 
1.145     brouard  3388: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  3389: {
                   3390:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3391:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3392:   /* in, b, out are matrice of pointers which should have been initialized 
                   3393:      before: only the contents of out is modified. The function returns
                   3394:      a pointer to pointers identical to out */
1.145     brouard  3395:   int i, j, k;
1.126     brouard  3396:   for(i=nrl; i<= nrh; i++)
1.145     brouard  3397:     for(k=ncolol; k<=ncoloh; k++){
                   3398:       out[i][k]=0.;
                   3399:       for(j=ncl; j<=nch; j++)
                   3400:        out[i][k] +=in[i][j]*b[j][k];
                   3401:     }
1.126     brouard  3402:   return out;
                   3403: }
                   3404: 
                   3405: 
                   3406: /************* Higher Matrix Product ***************/
                   3407: 
1.235     brouard  3408: 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  3409: {
1.218     brouard  3410:   /* Computes the transition matrix starting at age 'age' and combination of covariate values corresponding to ij over 
1.126     brouard  3411:      'nhstepm*hstepm*stepm' months (i.e. until
                   3412:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3413:      nhstepm*hstepm matrices. 
                   3414:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3415:      (typically every 2 years instead of every month which is too big 
                   3416:      for the memory).
                   3417:      Model is determined by parameters x and covariates have to be 
                   3418:      included manually here. 
                   3419: 
                   3420:      */
                   3421: 
1.330     brouard  3422:   int i, j, d, h, k, k1;
1.131     brouard  3423:   double **out, cov[NCOVMAX+1];
1.126     brouard  3424:   double **newm;
1.187     brouard  3425:   double agexact;
1.214     brouard  3426:   double agebegin, ageend;
1.126     brouard  3427: 
                   3428:   /* Hstepm could be zero and should return the unit matrix */
                   3429:   for (i=1;i<=nlstate+ndeath;i++)
                   3430:     for (j=1;j<=nlstate+ndeath;j++){
                   3431:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3432:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3433:     }
                   3434:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3435:   for(h=1; h <=nhstepm; h++){
                   3436:     for(d=1; d <=hstepm; d++){
                   3437:       newm=savm;
                   3438:       /* Covariates have to be included here again */
                   3439:       cov[1]=1.;
1.214     brouard  3440:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3441:       cov[2]=agexact;
1.319     brouard  3442:       if(nagesqr==1){
1.227     brouard  3443:        cov[3]= agexact*agexact;
1.319     brouard  3444:       }
1.330     brouard  3445:       /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   3446:       /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   3447:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   3448:        if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Single dummy  */
                   3449: /*        V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) */
                   3450: /*       for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   3451: /* /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
1.319     brouard  3452:        /* codtabm(ij,k)  (1 & (ij-1) >> (k-1))+1 */
                   3453: /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   3454: /*    k        1  2   3   4     5    6    7     8    9 */
                   3455: /*Tvar[k]=     5  4   3   6     5    2    7     1    1 */
                   3456: /*    nsd         1   2                              3 */ /* Counting single dummies covar fixed or tv */
                   3457: /*TvarsD[nsd]     4   3                              1 */ /* ID of single dummy cova fixed or timevary*/
                   3458: /*TvarsDind[k]    2   3                              9 */ /* position K of single dummy cova */
1.330     brouard  3459:          /* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];or [codtabm(ij,TnsdVar[TvarsD[k]] */
                   3460:          cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];
                   3461:          /* 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]])); */
                   3462:          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);
                   3463:        }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Single quantitative variables  */
                   3464:          /* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline */
                   3465:          cov[2+nagesqr+k1]=Tqresult[nres][resultmodel[nres][k1]]; 
                   3466:          /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3467:          /*    /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3468:          /*    cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; */
                   3469:          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]]);
                   3470:        }else if( Dummy[k1]==2 ){ /* For dummy with age product */
                   3471:          /* Tvar[k1] Variable in the age product age*V1 is 1 */
                   3472:          /* [Tinvresult[nres][V1] is its value in the resultline nres */
                   3473:          cov[2+nagesqr+k1]=Tinvresult[nres][Tvar[k1]];
                   3474:          printf("DhPxij Dummy with age k1=%d Tvar[%d]=%d Tinvresult[nres][%d]=%d,cov[2+%d+%d]=%.3f\n",k1,k1,Tvar[k1],Tinvresult[nres][Tvar[k1]],nagesqr,k1,cov[2+nagesqr+k1]);
                   3475:          /* cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];     */
                   3476:          /* for (k=1; k<=cptcovage;k++){ /\* For product with age V1+V1*age +V4 +age*V3 *\/ */
                   3477:          /* 1+2 Tage[1]=2 TVar[2]=1 Dummy[2]=2, Tage[2]=4 TVar[4]=3 Dummy[4]=3 quant*/
                   3478:          /* */
                   3479: /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   3480: /*    k        1  2   3   4     5    6    7     8    9 */
                   3481: /*Tvar[k]=     5  4   3   6     5    2    7     1    1 */
                   3482: /*cptcovage=2                   1               2      */
                   3483: /*Tage[k]=                      5               8      */      
1.331   ! brouard  3484:        }else if( Dummy[k1]==3 ){ /* For quant with age product */
1.330     brouard  3485:          cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];       
                   3486:          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]]);
                   3487:          /* if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3488:          /* /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age *\\/ *\/ */
                   3489:          /*   /\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   3490:          /*   /\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\/ */
                   3491:          /*   cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; */
                   3492:          /*   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); */
                   3493:          /* } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3494:          /*   cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   3495:          /* } */
                   3496:          /* 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]); */
                   3497:        }else if(Typevar[k1]==2 ){ /* For product (not with age) */
                   3498: /*       for (k=1; k<=cptcovprod;k++){ /\*  For product without age *\/ */
                   3499: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3500: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3501: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
                   3502: /* /\*cptcovprod=1            1               2            *\/ */
                   3503: /* /\*Tprod[]=                4               7            *\/ */
                   3504: /* /\*Tvard[][1]             4               1             *\/ */
                   3505: /* /\*Tvard[][2]               3               2           *\/ */
                   3506:          
                   3507:          /* 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])]); */
                   3508:          /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; */
                   3509:          cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];    
                   3510:          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,Tvard[k1][1], k1,Tvard[k1][2], TinvDoQresult[nres][Tvardk[k1][1]], TinvDoQresult[nres][Tvardk[k1][2]]);
                   3511:          /* if(Dummy[Tvardk[k1][1]]==0){ */
                   3512:          /*   if(Dummy[Tvardk[k1][2]]==0){ /\* Product of dummies *\/ */
                   3513:              /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; */
                   3514:              /* cov[2+nagesqr+k1]=Tinvresult[nres][Tvardk[k1][1]] * Tinvresult[nres][Tvardk[k1][2]];    */
                   3515:              /* 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]])]; */
                   3516:            /* }else{ /\* Product of dummy by quantitative *\/ */
                   3517:              /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,TnsdVar[Tvard[k][1]])] * Tqresult[nres][k]; */
                   3518:              /* cov[2+nagesqr+k1]=Tresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]; */
                   3519:          /*   } */
                   3520:          /* }else{ /\* Product of quantitative by...*\/ */
                   3521:          /*   if(Dummy[Tvard[k][2]]==0){  /\* quant by dummy *\/ */
                   3522:          /*     /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   3523:          /*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; */
                   3524:          /*   }else{ /\* Product of two quant *\/ */
                   3525:          /*     /\* cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   3526:          /*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; */
                   3527:          /*   } */
                   3528:          /* }/\*end of products quantitative *\/ */
                   3529:        }/*end of products */
                   3530:       } /* End of loop on model equation */
1.235     brouard  3531:       /* for (k=1; k<=cptcovn;k++)  */
                   3532:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3533:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3534:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3535:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3536:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3537:       
                   3538:       
1.126     brouard  3539:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3540:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.319     brouard  3541:       /* right multiplication of oldm by the current matrix */
1.126     brouard  3542:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3543:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3544:       /* if((int)age == 70){ */
                   3545:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3546:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3547:       /*         printf("%d pmmij ",i); */
                   3548:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3549:       /*           printf("%f ",pmmij[i][j]); */
                   3550:       /*         } */
                   3551:       /*         printf(" oldm "); */
                   3552:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3553:       /*           printf("%f ",oldm[i][j]); */
                   3554:       /*         } */
                   3555:       /*         printf("\n"); */
                   3556:       /*       } */
                   3557:       /* } */
1.126     brouard  3558:       savm=oldm;
                   3559:       oldm=newm;
                   3560:     }
                   3561:     for(i=1; i<=nlstate+ndeath; i++)
                   3562:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  3563:        po[i][j][h]=newm[i][j];
                   3564:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3565:       }
1.128     brouard  3566:     /*printf("h=%d ",h);*/
1.126     brouard  3567:   } /* end h */
1.267     brouard  3568:   /*     printf("\n H=%d \n",h); */
1.126     brouard  3569:   return po;
                   3570: }
                   3571: 
1.217     brouard  3572: /************* Higher Back Matrix Product ***************/
1.218     brouard  3573: /* 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  3574: 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  3575: {
1.266     brouard  3576:   /* For a combination of dummy covariate ij, computes the transition matrix starting at age 'age' over
1.217     brouard  3577:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3578:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3579:      nhstepm*hstepm matrices.
                   3580:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3581:      (typically every 2 years instead of every month which is too big
1.217     brouard  3582:      for the memory).
1.218     brouard  3583:      Model is determined by parameters x and covariates have to be
1.266     brouard  3584:      included manually here. Then we use a call to bmij(x and cov)
                   3585:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  3586:   */
1.217     brouard  3587: 
                   3588:   int i, j, d, h, k;
1.266     brouard  3589:   double **out, cov[NCOVMAX+1], **bmij();
                   3590:   double **newm, ***newmm;
1.217     brouard  3591:   double agexact;
                   3592:   double agebegin, ageend;
1.222     brouard  3593:   double **oldm, **savm;
1.217     brouard  3594: 
1.266     brouard  3595:   newmm=po; /* To be saved */
                   3596:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  3597:   /* Hstepm could be zero and should return the unit matrix */
                   3598:   for (i=1;i<=nlstate+ndeath;i++)
                   3599:     for (j=1;j<=nlstate+ndeath;j++){
                   3600:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3601:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3602:     }
                   3603:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3604:   for(h=1; h <=nhstepm; h++){
                   3605:     for(d=1; d <=hstepm; d++){
                   3606:       newm=savm;
                   3607:       /* Covariates have to be included here again */
                   3608:       cov[1]=1.;
1.271     brouard  3609:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  3610:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
1.318     brouard  3611:         /* Debug */
                   3612:       /* printf("hBxij age=%lf, agexact=%lf\n", age, agexact); */
1.217     brouard  3613:       cov[2]=agexact;
                   3614:       if(nagesqr==1)
1.222     brouard  3615:        cov[3]= agexact*agexact;
1.325     brouard  3616:       for (k=1; k<=nsd;k++){ /* For single dummy covariates only *//* cptcovn error */
1.266     brouard  3617:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3618:       /* /\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\/ */
1.330     brouard  3619:        cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])];/* Bug valgrind */
1.266     brouard  3620:         /* 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)); */
                   3621:       }
1.267     brouard  3622:       for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   3623:        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   3624:        cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   3625:        /* 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]); */
                   3626:       }
1.319     brouard  3627:       for (k=1; k<=cptcovage;k++){ /* Should start at cptcovn+1 *//* For product with age */
                   3628:        /* if(Dummy[Tvar[Tage[k]]]== 2){ /\* dummy with age error!!!*\/ */
                   3629:        if(Dummy[Tage[k]]== 2){ /* dummy with age */
1.330     brouard  3630:          cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2];
1.319     brouard  3631:        } else if(Dummy[Tage[k]]== 3){ /* quantitative with age */
1.267     brouard  3632:          cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   3633:        }
                   3634:        /* 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]); */
                   3635:       }
                   3636:       for (k=1; k<=cptcovprod;k++){ /* Useless because included in cptcovn */
1.330     brouard  3637:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])];
1.329     brouard  3638:        if(Dummy[Tvard[k][1]]==0){
                   3639:          if(Dummy[Tvard[k][2]]==0){
1.330     brouard  3640:            cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][1])];
1.325     brouard  3641:          }else{
1.330     brouard  3642:            cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k];
1.325     brouard  3643:          }
                   3644:        }else{
1.329     brouard  3645:          if(Dummy[Tvard[k][2]]==0){
1.330     brouard  3646:            cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]];
1.325     brouard  3647:          }else{
                   3648:            cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   3649:          }
                   3650:        }
1.267     brouard  3651:       }                        
1.217     brouard  3652:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3653:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.267     brouard  3654: 
1.218     brouard  3655:       /* Careful transposed matrix */
1.266     brouard  3656:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  3657:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3658:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3659:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.325     brouard  3660:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);/* Bug valgrind */
1.217     brouard  3661:       /* if((int)age == 70){ */
                   3662:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3663:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3664:       /*         printf("%d pmmij ",i); */
                   3665:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3666:       /*           printf("%f ",pmmij[i][j]); */
                   3667:       /*         } */
                   3668:       /*         printf(" oldm "); */
                   3669:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3670:       /*           printf("%f ",oldm[i][j]); */
                   3671:       /*         } */
                   3672:       /*         printf("\n"); */
                   3673:       /*       } */
                   3674:       /* } */
                   3675:       savm=oldm;
                   3676:       oldm=newm;
                   3677:     }
                   3678:     for(i=1; i<=nlstate+ndeath; i++)
                   3679:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3680:        po[i][j][h]=newm[i][j];
1.268     brouard  3681:        /* if(h==nhstepm) */
                   3682:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  3683:       }
1.268     brouard  3684:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  3685:   } /* end h */
1.268     brouard  3686:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  3687:   return po;
                   3688: }
                   3689: 
                   3690: 
1.162     brouard  3691: #ifdef NLOPT
                   3692:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3693:   double fret;
                   3694:   double *xt;
                   3695:   int j;
                   3696:   myfunc_data *d2 = (myfunc_data *) pd;
                   3697: /* xt = (p1-1); */
                   3698:   xt=vector(1,n); 
                   3699:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3700: 
                   3701:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3702:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3703:   printf("Function = %.12lf ",fret);
                   3704:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3705:   printf("\n");
                   3706:  free_vector(xt,1,n);
                   3707:   return fret;
                   3708: }
                   3709: #endif
1.126     brouard  3710: 
                   3711: /*************** log-likelihood *************/
                   3712: double func( double *x)
                   3713: {
1.226     brouard  3714:   int i, ii, j, k, mi, d, kk;
                   3715:   int ioffset=0;
                   3716:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3717:   double **out;
                   3718:   double lli; /* Individual log likelihood */
                   3719:   int s1, s2;
1.228     brouard  3720:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
1.226     brouard  3721:   double bbh, survp;
                   3722:   long ipmx;
                   3723:   double agexact;
                   3724:   /*extern weight */
                   3725:   /* We are differentiating ll according to initial status */
                   3726:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3727:   /*for(i=1;i<imx;i++) 
                   3728:     printf(" %d\n",s[4][i]);
                   3729:   */
1.162     brouard  3730: 
1.226     brouard  3731:   ++countcallfunc;
1.162     brouard  3732: 
1.226     brouard  3733:   cov[1]=1.;
1.126     brouard  3734: 
1.226     brouard  3735:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3736:   ioffset=0;
1.226     brouard  3737:   if(mle==1){
                   3738:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3739:       /* Computes the values of the ncovmodel covariates of the model
                   3740:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3741:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   3742:         to be observed in j being in i according to the model.
                   3743:       */
1.243     brouard  3744:       ioffset=2+nagesqr ;
1.233     brouard  3745:    /* Fixed */
1.319     brouard  3746:       for (k=1; k<=ncovf;k++){ /* For each fixed covariate dummu or quant or prod */
                   3747:        /* # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi */
                   3748:         /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   3749:        /*  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  3750:         /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.319     brouard  3751:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, only V1 is fixed (TvarFind[1]=6)*/
                   3752:        /* V1*V2 (7)  TvarFind[2]=7, TvarFind[3]=9 */
1.234     brouard  3753:       }
1.226     brouard  3754:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.319     brouard  3755:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
1.226     brouard  3756:         has been calculated etc */
                   3757:       /* For an individual i, wav[i] gives the number of effective waves */
                   3758:       /* We compute the contribution to Likelihood of each effective transition
                   3759:         mw[mi][i] is real wave of the mi th effectve wave */
                   3760:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   3761:         s2=s[mw[mi+1][i]][i];
                   3762:         And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
                   3763:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   3764:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   3765:       */
                   3766:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  3767:        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*/
                   3768:          /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; but where is the crossproduct? */
1.242     brouard  3769:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
1.234     brouard  3770:        }
                   3771:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3772:          for (j=1;j<=nlstate+ndeath;j++){
                   3773:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3774:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3775:          }
                   3776:        for(d=0; d<dh[mi][i]; d++){
                   3777:          newm=savm;
                   3778:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3779:          cov[2]=agexact;
                   3780:          if(nagesqr==1)
                   3781:            cov[3]= agexact*agexact;  /* Should be changed here */
                   3782:          for (kk=1; kk<=cptcovage;kk++) {
1.318     brouard  3783:            if(!FixedV[Tvar[Tage[kk]]])
                   3784:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   3785:            else
                   3786:              cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
1.234     brouard  3787:          }
                   3788:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3789:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3790:          savm=oldm;
                   3791:          oldm=newm;
                   3792:        } /* end mult */
                   3793:        
                   3794:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   3795:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   3796:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   3797:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   3798:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   3799:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   3800:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   3801:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  3802:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   3803:                                 * -stepm/2 to stepm/2 .
                   3804:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   3805:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   3806:                                 */
1.234     brouard  3807:        s1=s[mw[mi][i]][i];
                   3808:        s2=s[mw[mi+1][i]][i];
                   3809:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3810:        /* bias bh is positive if real duration
                   3811:         * is higher than the multiple of stepm and negative otherwise.
                   3812:         */
                   3813:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   3814:        if( s2 > nlstate){ 
                   3815:          /* i.e. if s2 is a death state and if the date of death is known 
                   3816:             then the contribution to the likelihood is the probability to 
                   3817:             die between last step unit time and current  step unit time, 
                   3818:             which is also equal to probability to die before dh 
                   3819:             minus probability to die before dh-stepm . 
                   3820:             In version up to 0.92 likelihood was computed
                   3821:             as if date of death was unknown. Death was treated as any other
                   3822:             health state: the date of the interview describes the actual state
                   3823:             and not the date of a change in health state. The former idea was
                   3824:             to consider that at each interview the state was recorded
                   3825:             (healthy, disable or death) and IMaCh was corrected; but when we
                   3826:             introduced the exact date of death then we should have modified
                   3827:             the contribution of an exact death to the likelihood. This new
                   3828:             contribution is smaller and very dependent of the step unit
                   3829:             stepm. It is no more the probability to die between last interview
                   3830:             and month of death but the probability to survive from last
                   3831:             interview up to one month before death multiplied by the
                   3832:             probability to die within a month. Thanks to Chris
                   3833:             Jackson for correcting this bug.  Former versions increased
                   3834:             mortality artificially. The bad side is that we add another loop
                   3835:             which slows down the processing. The difference can be up to 10%
                   3836:             lower mortality.
                   3837:          */
                   3838:          /* If, at the beginning of the maximization mostly, the
                   3839:             cumulative probability or probability to be dead is
                   3840:             constant (ie = 1) over time d, the difference is equal to
                   3841:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   3842:             s1 at precedent wave, to be dead a month before current
                   3843:             wave is equal to probability, being at state s1 at
                   3844:             precedent wave, to be dead at mont of the current
                   3845:             wave. Then the observed probability (that this person died)
                   3846:             is null according to current estimated parameter. In fact,
                   3847:             it should be very low but not zero otherwise the log go to
                   3848:             infinity.
                   3849:          */
1.183     brouard  3850: /* #ifdef INFINITYORIGINAL */
                   3851: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3852: /* #else */
                   3853: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   3854: /*         lli=log(mytinydouble); */
                   3855: /*       else */
                   3856: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3857: /* #endif */
1.226     brouard  3858:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3859:          
1.226     brouard  3860:        } else if  ( s2==-1 ) { /* alive */
                   3861:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3862:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3863:          /*survp += out[s1][j]; */
                   3864:          lli= log(survp);
                   3865:        }
                   3866:        else if  (s2==-4) { 
                   3867:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   3868:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3869:          lli= log(survp); 
                   3870:        } 
                   3871:        else if  (s2==-5) { 
                   3872:          for (j=1,survp=0. ; j<=2; j++)  
                   3873:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3874:          lli= log(survp); 
                   3875:        } 
                   3876:        else{
                   3877:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3878:          /*  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 */
                   3879:        } 
                   3880:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   3881:        /*if(lli ==000.0)*/
                   3882:        /*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); */
                   3883:        ipmx +=1;
                   3884:        sw += weight[i];
                   3885:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3886:        /* if (lli < log(mytinydouble)){ */
                   3887:        /*   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); */
                   3888:        /*   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]); */
                   3889:        /* } */
                   3890:       } /* end of wave */
                   3891:     } /* end of individual */
                   3892:   }  else if(mle==2){
                   3893:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.319     brouard  3894:       ioffset=2+nagesqr ;
                   3895:       for (k=1; k<=ncovf;k++)
                   3896:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];
1.226     brouard  3897:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  3898:        for(k=1; k <= ncovv ; k++){
                   3899:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
                   3900:        }
1.226     brouard  3901:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3902:          for (j=1;j<=nlstate+ndeath;j++){
                   3903:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3904:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3905:          }
                   3906:        for(d=0; d<=dh[mi][i]; d++){
                   3907:          newm=savm;
                   3908:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3909:          cov[2]=agexact;
                   3910:          if(nagesqr==1)
                   3911:            cov[3]= agexact*agexact;
                   3912:          for (kk=1; kk<=cptcovage;kk++) {
                   3913:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3914:          }
                   3915:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3916:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3917:          savm=oldm;
                   3918:          oldm=newm;
                   3919:        } /* end mult */
                   3920:       
                   3921:        s1=s[mw[mi][i]][i];
                   3922:        s2=s[mw[mi+1][i]][i];
                   3923:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3924:        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 */
                   3925:        ipmx +=1;
                   3926:        sw += weight[i];
                   3927:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3928:       } /* end of wave */
                   3929:     } /* end of individual */
                   3930:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   3931:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3932:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3933:       for(mi=1; mi<= wav[i]-1; mi++){
                   3934:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3935:          for (j=1;j<=nlstate+ndeath;j++){
                   3936:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3937:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3938:          }
                   3939:        for(d=0; d<dh[mi][i]; d++){
                   3940:          newm=savm;
                   3941:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3942:          cov[2]=agexact;
                   3943:          if(nagesqr==1)
                   3944:            cov[3]= agexact*agexact;
                   3945:          for (kk=1; kk<=cptcovage;kk++) {
                   3946:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3947:          }
                   3948:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3949:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3950:          savm=oldm;
                   3951:          oldm=newm;
                   3952:        } /* end mult */
                   3953:       
                   3954:        s1=s[mw[mi][i]][i];
                   3955:        s2=s[mw[mi+1][i]][i];
                   3956:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3957:        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 */
                   3958:        ipmx +=1;
                   3959:        sw += weight[i];
                   3960:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3961:       } /* end of wave */
                   3962:     } /* end of individual */
                   3963:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   3964:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3965:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3966:       for(mi=1; mi<= wav[i]-1; mi++){
                   3967:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3968:          for (j=1;j<=nlstate+ndeath;j++){
                   3969:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3970:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3971:          }
                   3972:        for(d=0; d<dh[mi][i]; d++){
                   3973:          newm=savm;
                   3974:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3975:          cov[2]=agexact;
                   3976:          if(nagesqr==1)
                   3977:            cov[3]= agexact*agexact;
                   3978:          for (kk=1; kk<=cptcovage;kk++) {
                   3979:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3980:          }
1.126     brouard  3981:        
1.226     brouard  3982:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3983:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3984:          savm=oldm;
                   3985:          oldm=newm;
                   3986:        } /* end mult */
                   3987:       
                   3988:        s1=s[mw[mi][i]][i];
                   3989:        s2=s[mw[mi+1][i]][i];
                   3990:        if( s2 > nlstate){ 
                   3991:          lli=log(out[s1][s2] - savm[s1][s2]);
                   3992:        } else if  ( s2==-1 ) { /* alive */
                   3993:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3994:            survp += out[s1][j];
                   3995:          lli= log(survp);
                   3996:        }else{
                   3997:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3998:        }
                   3999:        ipmx +=1;
                   4000:        sw += weight[i];
                   4001:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.126     brouard  4002: /*     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  4003:       } /* end of wave */
                   4004:     } /* end of individual */
                   4005:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   4006:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4007:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4008:       for(mi=1; mi<= wav[i]-1; mi++){
                   4009:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4010:          for (j=1;j<=nlstate+ndeath;j++){
                   4011:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4012:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4013:          }
                   4014:        for(d=0; d<dh[mi][i]; d++){
                   4015:          newm=savm;
                   4016:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4017:          cov[2]=agexact;
                   4018:          if(nagesqr==1)
                   4019:            cov[3]= agexact*agexact;
                   4020:          for (kk=1; kk<=cptcovage;kk++) {
                   4021:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4022:          }
1.126     brouard  4023:        
1.226     brouard  4024:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4025:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4026:          savm=oldm;
                   4027:          oldm=newm;
                   4028:        } /* end mult */
                   4029:       
                   4030:        s1=s[mw[mi][i]][i];
                   4031:        s2=s[mw[mi+1][i]][i];
                   4032:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4033:        ipmx +=1;
                   4034:        sw += weight[i];
                   4035:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4036:        /*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]);*/
                   4037:       } /* end of wave */
                   4038:     } /* end of individual */
                   4039:   } /* End of if */
                   4040:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   4041:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   4042:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4043:   return -l;
1.126     brouard  4044: }
                   4045: 
                   4046: /*************** log-likelihood *************/
                   4047: double funcone( double *x)
                   4048: {
1.228     brouard  4049:   /* Same as func but slower because of a lot of printf and if */
1.126     brouard  4050:   int i, ii, j, k, mi, d, kk;
1.228     brouard  4051:   int ioffset=0;
1.131     brouard  4052:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  4053:   double **out;
                   4054:   double lli; /* Individual log likelihood */
                   4055:   double llt;
                   4056:   int s1, s2;
1.228     brouard  4057:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   4058: 
1.126     brouard  4059:   double bbh, survp;
1.187     brouard  4060:   double agexact;
1.214     brouard  4061:   double agebegin, ageend;
1.126     brouard  4062:   /*extern weight */
                   4063:   /* We are differentiating ll according to initial status */
                   4064:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   4065:   /*for(i=1;i<imx;i++) 
                   4066:     printf(" %d\n",s[4][i]);
                   4067:   */
                   4068:   cov[1]=1.;
                   4069: 
                   4070:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  4071:   ioffset=0;
                   4072:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.243     brouard  4073:     /* ioffset=2+nagesqr+cptcovage; */
                   4074:     ioffset=2+nagesqr;
1.232     brouard  4075:     /* Fixed */
1.224     brouard  4076:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  4077:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
1.311     brouard  4078:     for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
1.232     brouard  4079:       cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, only V1 is fixed (k=6)*/
                   4080: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   4081: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   4082: /*    cov[2+6]=covar[2][i]; V2  */
                   4083: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   4084: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   4085: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   4086: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   4087: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   4088: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  4089:     }
1.232     brouard  4090:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   4091:     /*   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?)*\/ */
                   4092:     /* } */
1.231     brouard  4093:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   4094:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   4095:     /* } */
1.225     brouard  4096:     
1.233     brouard  4097: 
                   4098:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.232     brouard  4099:     /* Wave varying (but not age varying) */
                   4100:       for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242     brouard  4101:        /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
                   4102:        cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
                   4103:       }
1.232     brouard  4104:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
1.242     brouard  4105:       /* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4106:       /* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
                   4107:       /* k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
                   4108:       /* cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
                   4109:       /* 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  4110:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  4111:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4112:       /*       /\* 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]); *\/ */
                   4113:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  4114:       /* } */
1.126     brouard  4115:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  4116:        for (j=1;j<=nlstate+ndeath;j++){
                   4117:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4118:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4119:        }
1.214     brouard  4120:       
                   4121:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4122:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   4123:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  4124:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  4125:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4126:          and mw[mi+1][i]. dh depends on stepm.*/
                   4127:        newm=savm;
1.247     brouard  4128:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  4129:        cov[2]=agexact;
                   4130:        if(nagesqr==1)
                   4131:          cov[3]= agexact*agexact;
                   4132:        for (kk=1; kk<=cptcovage;kk++) {
                   4133:          if(!FixedV[Tvar[Tage[kk]]])
                   4134:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4135:          else
                   4136:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
                   4137:        }
                   4138:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   4139:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4140:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4141:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4142:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   4143:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   4144:        savm=oldm;
                   4145:        oldm=newm;
1.126     brouard  4146:       } /* end mult */
                   4147:       
                   4148:       s1=s[mw[mi][i]][i];
                   4149:       s2=s[mw[mi+1][i]][i];
1.217     brouard  4150:       /* if(s2==-1){ */
1.268     brouard  4151:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  4152:       /*       /\* exit(1); *\/ */
                   4153:       /* } */
1.126     brouard  4154:       bbh=(double)bh[mi][i]/(double)stepm; 
                   4155:       /* bias is positive if real duration
                   4156:        * is higher than the multiple of stepm and negative otherwise.
                   4157:        */
                   4158:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  4159:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4160:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  4161:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   4162:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4163:        lli= log(survp);
1.126     brouard  4164:       }else if (mle==1){
1.242     brouard  4165:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  4166:       } else if(mle==2){
1.242     brouard  4167:        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  4168:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  4169:        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  4170:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  4171:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  4172:       } else{  /* mle=0 back to 1 */
1.242     brouard  4173:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4174:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  4175:       } /* End of if */
                   4176:       ipmx +=1;
                   4177:       sw += weight[i];
                   4178:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  4179:       /*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.126     brouard  4180:       if(globpr){
1.246     brouard  4181:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  4182:  %11.6f %11.6f %11.6f ", \
1.242     brouard  4183:                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  4184:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.242     brouard  4185:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   4186:          llt +=ll[k]*gipmx/gsw;
                   4187:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   4188:        }
                   4189:        fprintf(ficresilk," %10.6f\n", -llt);
1.126     brouard  4190:       }
1.232     brouard  4191:        } /* end of wave */
                   4192: } /* end of individual */
                   4193: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   4194: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   4195: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4196: if(globpr==0){ /* First time we count the contributions and weights */
                   4197:        gipmx=ipmx;
                   4198:        gsw=sw;
                   4199: }
                   4200: return -l;
1.126     brouard  4201: }
                   4202: 
                   4203: 
                   4204: /*************** function likelione ***********/
1.292     brouard  4205: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  4206: {
                   4207:   /* This routine should help understanding what is done with 
                   4208:      the selection of individuals/waves and
                   4209:      to check the exact contribution to the likelihood.
                   4210:      Plotting could be done.
                   4211:    */
                   4212:   int k;
                   4213: 
                   4214:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  4215:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  4216:     strcat(fileresilk,fileresu);
1.126     brouard  4217:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   4218:       printf("Problem with resultfile: %s\n", fileresilk);
                   4219:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   4220:     }
1.214     brouard  4221:     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");
                   4222:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  4223:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   4224:     for(k=1; k<=nlstate; k++) 
                   4225:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   4226:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   4227:   }
                   4228: 
1.292     brouard  4229:   *fretone=(*func)(p);
1.126     brouard  4230:   if(*globpri !=0){
                   4231:     fclose(ficresilk);
1.205     brouard  4232:     if (mle ==0)
                   4233:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   4234:     else if(mle >=1)
                   4235:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   4236:     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  4237:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  4238:       
                   4239:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  4240:       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  4241: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   4242:     }
1.207     brouard  4243:     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  4244: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4245:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  4246: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4247:     fflush(fichtm);
1.205     brouard  4248:   }
1.126     brouard  4249:   return;
                   4250: }
                   4251: 
                   4252: 
                   4253: /*********** Maximum Likelihood Estimation ***************/
                   4254: 
                   4255: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   4256: {
1.319     brouard  4257:   int i,j,k, jk, jkk=0, iter=0;
1.126     brouard  4258:   double **xi;
                   4259:   double fret;
                   4260:   double fretone; /* Only one call to likelihood */
                   4261:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  4262: 
                   4263: #ifdef NLOPT
                   4264:   int creturn;
                   4265:   nlopt_opt opt;
                   4266:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   4267:   double *lb;
                   4268:   double minf; /* the minimum objective value, upon return */
                   4269:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   4270:   myfunc_data dinst, *d = &dinst;
                   4271: #endif
                   4272: 
                   4273: 
1.126     brouard  4274:   xi=matrix(1,npar,1,npar);
                   4275:   for (i=1;i<=npar;i++)
                   4276:     for (j=1;j<=npar;j++)
                   4277:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   4278:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  4279:   strcpy(filerespow,"POW_"); 
1.126     brouard  4280:   strcat(filerespow,fileres);
                   4281:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   4282:     printf("Problem with resultfile: %s\n", filerespow);
                   4283:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   4284:   }
                   4285:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   4286:   for (i=1;i<=nlstate;i++)
                   4287:     for(j=1;j<=nlstate+ndeath;j++)
                   4288:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   4289:   fprintf(ficrespow,"\n");
1.162     brouard  4290: #ifdef POWELL
1.319     brouard  4291: #ifdef LINMINORIGINAL
                   4292: #else /* LINMINORIGINAL */
                   4293:   
                   4294:   flatdir=ivector(1,npar); 
                   4295:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   4296: #endif /*LINMINORIGINAL */
                   4297: 
                   4298: #ifdef FLATSUP
                   4299:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4300:   /* reorganizing p by suppressing flat directions */
                   4301:   for(i=1, jk=1; i <=nlstate; i++){
                   4302:     for(k=1; k <=(nlstate+ndeath); k++){
                   4303:       if (k != i) {
                   4304:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4305:         if(flatdir[jk]==1){
                   4306:           printf(" To be skipped %d%d flatdir[%d]=%d ",i,k,jk, flatdir[jk]);
                   4307:         }
                   4308:         for(j=1; j <=ncovmodel; j++){
                   4309:           printf("%12.7f ",p[jk]);
                   4310:           jk++; 
                   4311:         }
                   4312:         printf("\n");
                   4313:       }
                   4314:     }
                   4315:   }
                   4316: /* skipping */
                   4317:   /* for(i=1, jk=1, jkk=1;(flatdir[jk]==0)&& (i <=nlstate); i++){ */
                   4318:   for(i=1, jk=1, jkk=1;i <=nlstate; i++){
                   4319:     for(k=1; k <=(nlstate+ndeath); k++){
                   4320:       if (k != i) {
                   4321:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4322:         if(flatdir[jk]==1){
                   4323:           printf(" To be skipped %d%d flatdir[%d]=%d jk=%d p[%d] ",i,k,jk, flatdir[jk],jk, jk);
                   4324:           for(j=1; j <=ncovmodel;  jk++,j++){
                   4325:             printf(" p[%d]=%12.7f",jk, p[jk]);
                   4326:             /*q[jjk]=p[jk];*/
                   4327:           }
                   4328:         }else{
                   4329:           printf(" To be kept %d%d flatdir[%d]=%d jk=%d q[%d]=p[%d] ",i,k,jk, flatdir[jk],jk, jkk, jk);
                   4330:           for(j=1; j <=ncovmodel;  jk++,jkk++,j++){
                   4331:             printf(" p[%d]=%12.7f=q[%d]",jk, p[jk],jkk);
                   4332:             /*q[jjk]=p[jk];*/
                   4333:           }
                   4334:         }
                   4335:         printf("\n");
                   4336:       }
                   4337:       fflush(stdout);
                   4338:     }
                   4339:   }
                   4340:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4341: #else  /* FLATSUP */
1.126     brouard  4342:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.319     brouard  4343: #endif  /* FLATSUP */
                   4344: 
                   4345: #ifdef LINMINORIGINAL
                   4346: #else
                   4347:       free_ivector(flatdir,1,npar); 
                   4348: #endif  /* LINMINORIGINAL*/
                   4349: #endif /* POWELL */
1.126     brouard  4350: 
1.162     brouard  4351: #ifdef NLOPT
                   4352: #ifdef NEWUOA
                   4353:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   4354: #else
                   4355:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   4356: #endif
                   4357:   lb=vector(0,npar-1);
                   4358:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   4359:   nlopt_set_lower_bounds(opt, lb);
                   4360:   nlopt_set_initial_step1(opt, 0.1);
                   4361:   
                   4362:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   4363:   d->function = func;
                   4364:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   4365:   nlopt_set_min_objective(opt, myfunc, d);
                   4366:   nlopt_set_xtol_rel(opt, ftol);
                   4367:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   4368:     printf("nlopt failed! %d\n",creturn); 
                   4369:   }
                   4370:   else {
                   4371:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   4372:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   4373:     iter=1; /* not equal */
                   4374:   }
                   4375:   nlopt_destroy(opt);
                   4376: #endif
1.319     brouard  4377: #ifdef FLATSUP
                   4378:   /* npared = npar -flatd/ncovmodel; */
                   4379:   /* xired= matrix(1,npared,1,npared); */
                   4380:   /* paramred= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */
                   4381:   /* powell(pred,xired,npared,ftol,&iter,&fret,flatdir,func); */
                   4382:   /* free_matrix(xire,1,npared,1,npared); */
                   4383: #else  /* FLATSUP */
                   4384: #endif /* FLATSUP */
1.126     brouard  4385:   free_matrix(xi,1,npar,1,npar);
                   4386:   fclose(ficrespow);
1.203     brouard  4387:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   4388:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  4389:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  4390: 
                   4391: }
                   4392: 
                   4393: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  4394: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  4395: {
                   4396:   double  **a,**y,*x,pd;
1.203     brouard  4397:   /* double **hess; */
1.164     brouard  4398:   int i, j;
1.126     brouard  4399:   int *indx;
                   4400: 
                   4401:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  4402:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  4403:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   4404:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   4405:   double gompertz(double p[]);
1.203     brouard  4406:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  4407: 
                   4408:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   4409:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   4410:   for (i=1;i<=npar;i++){
1.203     brouard  4411:     printf("%d-",i);fflush(stdout);
                   4412:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  4413:    
                   4414:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   4415:     
                   4416:     /*  printf(" %f ",p[i]);
                   4417:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   4418:   }
                   4419:   
                   4420:   for (i=1;i<=npar;i++) {
                   4421:     for (j=1;j<=npar;j++)  {
                   4422:       if (j>i) { 
1.203     brouard  4423:        printf(".%d-%d",i,j);fflush(stdout);
                   4424:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   4425:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  4426:        
                   4427:        hess[j][i]=hess[i][j];    
                   4428:        /*printf(" %lf ",hess[i][j]);*/
                   4429:       }
                   4430:     }
                   4431:   }
                   4432:   printf("\n");
                   4433:   fprintf(ficlog,"\n");
                   4434: 
                   4435:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4436:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4437:   
                   4438:   a=matrix(1,npar,1,npar);
                   4439:   y=matrix(1,npar,1,npar);
                   4440:   x=vector(1,npar);
                   4441:   indx=ivector(1,npar);
                   4442:   for (i=1;i<=npar;i++)
                   4443:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   4444:   ludcmp(a,npar,indx,&pd);
                   4445: 
                   4446:   for (j=1;j<=npar;j++) {
                   4447:     for (i=1;i<=npar;i++) x[i]=0;
                   4448:     x[j]=1;
                   4449:     lubksb(a,npar,indx,x);
                   4450:     for (i=1;i<=npar;i++){ 
                   4451:       matcov[i][j]=x[i];
                   4452:     }
                   4453:   }
                   4454: 
                   4455:   printf("\n#Hessian matrix#\n");
                   4456:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   4457:   for (i=1;i<=npar;i++) { 
                   4458:     for (j=1;j<=npar;j++) { 
1.203     brouard  4459:       printf("%.6e ",hess[i][j]);
                   4460:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  4461:     }
                   4462:     printf("\n");
                   4463:     fprintf(ficlog,"\n");
                   4464:   }
                   4465: 
1.203     brouard  4466:   /* printf("\n#Covariance matrix#\n"); */
                   4467:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   4468:   /* for (i=1;i<=npar;i++) {  */
                   4469:   /*   for (j=1;j<=npar;j++) {  */
                   4470:   /*     printf("%.6e ",matcov[i][j]); */
                   4471:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   4472:   /*   } */
                   4473:   /*   printf("\n"); */
                   4474:   /*   fprintf(ficlog,"\n"); */
                   4475:   /* } */
                   4476: 
1.126     brouard  4477:   /* Recompute Inverse */
1.203     brouard  4478:   /* for (i=1;i<=npar;i++) */
                   4479:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   4480:   /* ludcmp(a,npar,indx,&pd); */
                   4481: 
                   4482:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   4483: 
                   4484:   /* for (j=1;j<=npar;j++) { */
                   4485:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   4486:   /*   x[j]=1; */
                   4487:   /*   lubksb(a,npar,indx,x); */
                   4488:   /*   for (i=1;i<=npar;i++){  */
                   4489:   /*     y[i][j]=x[i]; */
                   4490:   /*     printf("%.3e ",y[i][j]); */
                   4491:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   4492:   /*   } */
                   4493:   /*   printf("\n"); */
                   4494:   /*   fprintf(ficlog,"\n"); */
                   4495:   /* } */
                   4496: 
                   4497:   /* Verifying the inverse matrix */
                   4498: #ifdef DEBUGHESS
                   4499:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  4500: 
1.203     brouard  4501:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   4502:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  4503: 
                   4504:   for (j=1;j<=npar;j++) {
                   4505:     for (i=1;i<=npar;i++){ 
1.203     brouard  4506:       printf("%.2f ",y[i][j]);
                   4507:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  4508:     }
                   4509:     printf("\n");
                   4510:     fprintf(ficlog,"\n");
                   4511:   }
1.203     brouard  4512: #endif
1.126     brouard  4513: 
                   4514:   free_matrix(a,1,npar,1,npar);
                   4515:   free_matrix(y,1,npar,1,npar);
                   4516:   free_vector(x,1,npar);
                   4517:   free_ivector(indx,1,npar);
1.203     brouard  4518:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  4519: 
                   4520: 
                   4521: }
                   4522: 
                   4523: /*************** hessian matrix ****************/
                   4524: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  4525: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  4526:   int i;
                   4527:   int l=1, lmax=20;
1.203     brouard  4528:   double k1,k2, res, fx;
1.132     brouard  4529:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  4530:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   4531:   int k=0,kmax=10;
                   4532:   double l1;
                   4533: 
                   4534:   fx=func(x);
                   4535:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  4536:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  4537:     l1=pow(10,l);
                   4538:     delts=delt;
                   4539:     for(k=1 ; k <kmax; k=k+1){
                   4540:       delt = delta*(l1*k);
                   4541:       p2[theta]=x[theta] +delt;
1.145     brouard  4542:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  4543:       p2[theta]=x[theta]-delt;
                   4544:       k2=func(p2)-fx;
                   4545:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  4546:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  4547:       
1.203     brouard  4548: #ifdef DEBUGHESSII
1.126     brouard  4549:       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);
                   4550:       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);
                   4551: #endif
                   4552:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   4553:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   4554:        k=kmax;
                   4555:       }
                   4556:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  4557:        k=kmax; l=lmax*10;
1.126     brouard  4558:       }
                   4559:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   4560:        delts=delt;
                   4561:       }
1.203     brouard  4562:     } /* End loop k */
1.126     brouard  4563:   }
                   4564:   delti[theta]=delts;
                   4565:   return res; 
                   4566:   
                   4567: }
                   4568: 
1.203     brouard  4569: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  4570: {
                   4571:   int i;
1.164     brouard  4572:   int l=1, lmax=20;
1.126     brouard  4573:   double k1,k2,k3,k4,res,fx;
1.132     brouard  4574:   double p2[MAXPARM+1];
1.203     brouard  4575:   int k, kmax=1;
                   4576:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  4577: 
                   4578:   int firstime=0;
1.203     brouard  4579:   
1.126     brouard  4580:   fx=func(x);
1.203     brouard  4581:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  4582:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  4583:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4584:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4585:     k1=func(p2)-fx;
                   4586:   
1.203     brouard  4587:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4588:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4589:     k2=func(p2)-fx;
                   4590:   
1.203     brouard  4591:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4592:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4593:     k3=func(p2)-fx;
                   4594:   
1.203     brouard  4595:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4596:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4597:     k4=func(p2)-fx;
1.203     brouard  4598:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   4599:     if(k1*k2*k3*k4 <0.){
1.208     brouard  4600:       firstime=1;
1.203     brouard  4601:       kmax=kmax+10;
1.208     brouard  4602:     }
                   4603:     if(kmax >=10 || firstime ==1){
1.246     brouard  4604:       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);
                   4605:       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  4606:       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);
                   4607:       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);
                   4608:     }
                   4609: #ifdef DEBUGHESSIJ
                   4610:     v1=hess[thetai][thetai];
                   4611:     v2=hess[thetaj][thetaj];
                   4612:     cv12=res;
                   4613:     /* Computing eigen value of Hessian matrix */
                   4614:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4615:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4616:     if ((lc2 <0) || (lc1 <0) ){
                   4617:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4618:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4619:       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);
                   4620:       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);
                   4621:     }
1.126     brouard  4622: #endif
                   4623:   }
                   4624:   return res;
                   4625: }
                   4626: 
1.203     brouard  4627:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   4628: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   4629: /* { */
                   4630: /*   int i; */
                   4631: /*   int l=1, lmax=20; */
                   4632: /*   double k1,k2,k3,k4,res,fx; */
                   4633: /*   double p2[MAXPARM+1]; */
                   4634: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   4635: /*   int k=0,kmax=10; */
                   4636: /*   double l1; */
                   4637:   
                   4638: /*   fx=func(x); */
                   4639: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   4640: /*     l1=pow(10,l); */
                   4641: /*     delts=delt; */
                   4642: /*     for(k=1 ; k <kmax; k=k+1){ */
                   4643: /*       delt = delti*(l1*k); */
                   4644: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   4645: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4646: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4647: /*       k1=func(p2)-fx; */
                   4648:       
                   4649: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4650: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4651: /*       k2=func(p2)-fx; */
                   4652:       
                   4653: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4654: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4655: /*       k3=func(p2)-fx; */
                   4656:       
                   4657: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4658: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4659: /*       k4=func(p2)-fx; */
                   4660: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   4661: /* #ifdef DEBUGHESSIJ */
                   4662: /*       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); */
                   4663: /*       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); */
                   4664: /* #endif */
                   4665: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   4666: /*     k=kmax; */
                   4667: /*       } */
                   4668: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   4669: /*     k=kmax; l=lmax*10; */
                   4670: /*       } */
                   4671: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   4672: /*     delts=delt; */
                   4673: /*       } */
                   4674: /*     } /\* End loop k *\/ */
                   4675: /*   } */
                   4676: /*   delti[theta]=delts; */
                   4677: /*   return res;  */
                   4678: /* } */
                   4679: 
                   4680: 
1.126     brouard  4681: /************** Inverse of matrix **************/
                   4682: void ludcmp(double **a, int n, int *indx, double *d) 
                   4683: { 
                   4684:   int i,imax,j,k; 
                   4685:   double big,dum,sum,temp; 
                   4686:   double *vv; 
                   4687:  
                   4688:   vv=vector(1,n); 
                   4689:   *d=1.0; 
                   4690:   for (i=1;i<=n;i++) { 
                   4691:     big=0.0; 
                   4692:     for (j=1;j<=n;j++) 
                   4693:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  4694:     if (big == 0.0){
                   4695:       printf(" Singular Hessian matrix at row %d:\n",i);
                   4696:       for (j=1;j<=n;j++) {
                   4697:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   4698:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   4699:       }
                   4700:       fflush(ficlog);
                   4701:       fclose(ficlog);
                   4702:       nrerror("Singular matrix in routine ludcmp"); 
                   4703:     }
1.126     brouard  4704:     vv[i]=1.0/big; 
                   4705:   } 
                   4706:   for (j=1;j<=n;j++) { 
                   4707:     for (i=1;i<j;i++) { 
                   4708:       sum=a[i][j]; 
                   4709:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   4710:       a[i][j]=sum; 
                   4711:     } 
                   4712:     big=0.0; 
                   4713:     for (i=j;i<=n;i++) { 
                   4714:       sum=a[i][j]; 
                   4715:       for (k=1;k<j;k++) 
                   4716:        sum -= a[i][k]*a[k][j]; 
                   4717:       a[i][j]=sum; 
                   4718:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   4719:        big=dum; 
                   4720:        imax=i; 
                   4721:       } 
                   4722:     } 
                   4723:     if (j != imax) { 
                   4724:       for (k=1;k<=n;k++) { 
                   4725:        dum=a[imax][k]; 
                   4726:        a[imax][k]=a[j][k]; 
                   4727:        a[j][k]=dum; 
                   4728:       } 
                   4729:       *d = -(*d); 
                   4730:       vv[imax]=vv[j]; 
                   4731:     } 
                   4732:     indx[j]=imax; 
                   4733:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   4734:     if (j != n) { 
                   4735:       dum=1.0/(a[j][j]); 
                   4736:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   4737:     } 
                   4738:   } 
                   4739:   free_vector(vv,1,n);  /* Doesn't work */
                   4740: ;
                   4741: } 
                   4742: 
                   4743: void lubksb(double **a, int n, int *indx, double b[]) 
                   4744: { 
                   4745:   int i,ii=0,ip,j; 
                   4746:   double sum; 
                   4747:  
                   4748:   for (i=1;i<=n;i++) { 
                   4749:     ip=indx[i]; 
                   4750:     sum=b[ip]; 
                   4751:     b[ip]=b[i]; 
                   4752:     if (ii) 
                   4753:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   4754:     else if (sum) ii=i; 
                   4755:     b[i]=sum; 
                   4756:   } 
                   4757:   for (i=n;i>=1;i--) { 
                   4758:     sum=b[i]; 
                   4759:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   4760:     b[i]=sum/a[i][i]; 
                   4761:   } 
                   4762: } 
                   4763: 
                   4764: void pstamp(FILE *fichier)
                   4765: {
1.196     brouard  4766:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  4767: }
                   4768: 
1.297     brouard  4769: void date2dmy(double date,double *day, double *month, double *year){
                   4770:   double yp=0., yp1=0., yp2=0.;
                   4771:   
                   4772:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   4773:                        fractional in yp1 */
                   4774:   *year=yp;
                   4775:   yp2=modf((yp1*12),&yp);
                   4776:   *month=yp;
                   4777:   yp1=modf((yp2*30.5),&yp);
                   4778:   *day=yp;
                   4779:   if(*day==0) *day=1;
                   4780:   if(*month==0) *month=1;
                   4781: }
                   4782: 
1.253     brouard  4783: 
                   4784: 
1.126     brouard  4785: /************ Frequencies ********************/
1.251     brouard  4786: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  4787:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   4788:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  4789: {  /* Some frequencies as well as proposing some starting values */
1.226     brouard  4790:   
1.265     brouard  4791:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  4792:   int iind=0, iage=0;
                   4793:   int mi; /* Effective wave */
                   4794:   int first;
                   4795:   double ***freq; /* Frequencies */
1.268     brouard  4796:   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 */
                   4797:   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  4798:   double *meanq, *stdq, *idq;
1.226     brouard  4799:   double **meanqt;
                   4800:   double *pp, **prop, *posprop, *pospropt;
                   4801:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   4802:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   4803:   double agebegin, ageend;
                   4804:     
                   4805:   pp=vector(1,nlstate);
1.251     brouard  4806:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  4807:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   4808:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   4809:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   4810:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  4811:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  4812:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  4813:   meanqt=matrix(1,lastpass,1,nqtveff);
                   4814:   strcpy(fileresp,"P_");
                   4815:   strcat(fileresp,fileresu);
                   4816:   /*strcat(fileresphtm,fileresu);*/
                   4817:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   4818:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   4819:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   4820:     exit(0);
                   4821:   }
1.240     brouard  4822:   
1.226     brouard  4823:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   4824:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   4825:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4826:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4827:     fflush(ficlog);
                   4828:     exit(70); 
                   4829:   }
                   4830:   else{
                   4831:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  4832: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4833: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4834:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4835:   }
1.319     brouard  4836:   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  4837:   
1.226     brouard  4838:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   4839:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   4840:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4841:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4842:     fflush(ficlog);
                   4843:     exit(70); 
1.240     brouard  4844:   } else{
1.226     brouard  4845:     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  4846: ,<hr size=\"2\" color=\"#EC5E5E\"> \n                                  \
1.214     brouard  4847: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4848:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4849:   }
1.319     brouard  4850:   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  4851:   
1.253     brouard  4852:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   4853:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  4854:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  4855:   j1=0;
1.126     brouard  4856:   
1.227     brouard  4857:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
                   4858:   j=cptcoveff;  /* Only dummy covariates of the model */
1.330     brouard  4859:   /* j=cptcovn;  /\* Only dummy covariates of the model *\/ */
1.226     brouard  4860:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  4861:   
                   4862:   
1.226     brouard  4863:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   4864:      reference=low_education V1=0,V2=0
                   4865:      med_educ                V1=1 V2=0, 
                   4866:      high_educ               V1=0 V2=1
1.330     brouard  4867:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcovn 
1.226     brouard  4868:   */
1.249     brouard  4869:   dateintsum=0;
                   4870:   k2cpt=0;
                   4871: 
1.253     brouard  4872:   if(cptcoveff == 0 )
1.265     brouard  4873:     nl=1;  /* Constant and age model only */
1.253     brouard  4874:   else
                   4875:     nl=2;
1.265     brouard  4876: 
                   4877:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   4878:   /* Loop on nj=1 or 2 if dummy covariates j!=0
1.330     brouard  4879:    *   Loop on j1(1 to 2**cptcovn) covariate combination
1.265     brouard  4880:    *     freq[s1][s2][iage] =0.
                   4881:    *     Loop on iind
                   4882:    *       ++freq[s1][s2][iage] weighted
                   4883:    *     end iind
                   4884:    *     if covariate and j!0
                   4885:    *       headers Variable on one line
                   4886:    *     endif cov j!=0
                   4887:    *     header of frequency table by age
                   4888:    *     Loop on age
                   4889:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   4890:    *       pos+=freq[s1][s2][iage] weighted
                   4891:    *       Loop on s1 initial state
                   4892:    *         fprintf(ficresp
                   4893:    *       end s1
                   4894:    *     end age
                   4895:    *     if j!=0 computes starting values
                   4896:    *     end compute starting values
                   4897:    *   end j1
                   4898:    * end nl 
                   4899:    */
1.253     brouard  4900:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   4901:     if(nj==1)
                   4902:       j=0;  /* First pass for the constant */
1.265     brouard  4903:     else{
1.330     brouard  4904:       j=cptcovs; /* Other passes for the covariate values */
1.265     brouard  4905:     }
1.251     brouard  4906:     first=1;
1.265     brouard  4907:     for (j1 = 1; j1 <= (int) pow(2,j); j1++){ /* Loop on all covariates combination of the model, excluding quantitatives, V4=0, V3=0 for example, fixed or varying covariates */
1.251     brouard  4908:       posproptt=0.;
1.330     brouard  4909:       /*printf("cptcovn=%d Tvaraff=%d", cptcovn,Tvaraff[1]);
1.251     brouard  4910:        scanf("%d", i);*/
                   4911:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  4912:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  4913:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  4914:            freq[i][s2][m]=0;
1.251     brouard  4915:       
                   4916:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  4917:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  4918:          prop[i][m]=0;
                   4919:        posprop[i]=0;
                   4920:        pospropt[i]=0;
                   4921:       }
1.283     brouard  4922:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  4923:         idq[z1]=0.;
                   4924:         meanq[z1]=0.;
                   4925:         stdq[z1]=0.;
1.283     brouard  4926:       }
                   4927:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  4928:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  4929:       /*         meanqt[m][z1]=0.; */
                   4930:       /*       } */
                   4931:       /* }       */
1.251     brouard  4932:       /* dateintsum=0; */
                   4933:       /* k2cpt=0; */
                   4934:       
1.265     brouard  4935:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  4936:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   4937:        bool=1;
                   4938:        if(j !=0){
                   4939:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.330     brouard  4940:            if (cptcovn >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   4941:              for (z1=1; z1<=cptcovn; z1++) { /* loops on covariates in the model */
1.251     brouard  4942:                /* if(Tvaraff[z1] ==-20){ */
                   4943:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   4944:                /* }else  if(Tvaraff[z1] ==-10){ */
                   4945:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
1.330     brouard  4946:                /* }else  */ /* TODO TODO codtabm(j1,z1) or codtabm(j1,Tvaraff[z1]]z1)*/
                   4947:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,Tvaraff[z1])]){ /* for combination j1 of covariates */
1.265     brouard  4948:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  4949:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
                   4950:                  /* 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", 
                   4951:                     bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   4952:                     j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   4953:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   4954:                } /* Onlyf fixed */
                   4955:              } /* end z1 */
                   4956:            } /* cptcovn > 0 */
                   4957:          } /* end any */
                   4958:        }/* end j==0 */
1.265     brouard  4959:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  4960:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  4961:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  4962:            m=mw[mi][iind];
                   4963:            if(j!=0){
                   4964:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
1.330     brouard  4965:                for (z1=1; z1<=cptcovn; z1++) {
1.251     brouard  4966:                  if( Fixed[Tmodelind[z1]]==1){
                   4967:                    iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
1.330     brouard  4968:                    if (cotvar[m][iv][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,Tvaraff[z1])]) /* iv=1 to ntv, right modality. If covariate's 
1.251     brouard  4969:                                                                                      value is -1, we don't select. It differs from the 
                   4970:                                                                                      constant and age model which counts them. */
                   4971:                      bool=0; /* not selected */
                   4972:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
1.330     brouard  4973:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,Tvaraff[z1])]) {
1.251     brouard  4974:                      bool=0;
                   4975:                    }
                   4976:                  }
                   4977:                }
                   4978:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   4979:            } /* end j==0 */
                   4980:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  4981:            if(bool==1){ /*Selected */
1.251     brouard  4982:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   4983:                 and mw[mi+1][iind]. dh depends on stepm. */
                   4984:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   4985:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   4986:              if(m >=firstpass && m <=lastpass){
                   4987:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   4988:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   4989:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   4990:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   4991:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   4992:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   4993:                if (m<lastpass) {
                   4994:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   4995:                  /*   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]); */
                   4996:                  if(s[m][iind]==-1)
                   4997:                    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.));
                   4998:                  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  4999:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
                   5000:                    if(!isnan(covar[ncovcol+z1][iind])){
                   5001:                        idq[z1]=idq[z1]+weight[iind];
                   5002:                        meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   5003:                        /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
                   5004:                        stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
                   5005:                    }
1.284     brouard  5006:                  }
1.251     brouard  5007:                  /* if((int)agev[m][iind] == 55) */
                   5008:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   5009:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   5010:                  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  5011:                }
1.251     brouard  5012:              } /* end if between passes */  
                   5013:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   5014:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   5015:                k2cpt++;
                   5016:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  5017:              }
1.251     brouard  5018:            }else{
                   5019:              bool=1;
                   5020:            }/* end bool 2 */
                   5021:          } /* end m */
1.284     brouard  5022:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   5023:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   5024:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   5025:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   5026:          /* } */
1.251     brouard  5027:        } /* end bool */
                   5028:       } /* end iind = 1 to imx */
1.319     brouard  5029:       /* prop[s][age] is fed for any initial and valid live state as well as
1.251     brouard  5030:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   5031:       
                   5032:       
                   5033:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.330     brouard  5034:       if(cptcovn==0 && nj==1) /* no covariate and first pass */
1.265     brouard  5035:         pstamp(ficresp);
1.330     brouard  5036:       if  (cptcovn>0 && j!=0){
1.265     brouard  5037:         pstamp(ficresp);
1.251     brouard  5038:        printf( "\n#********** Variable "); 
                   5039:        fprintf(ficresp, "\n#********** Variable "); 
                   5040:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   5041:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   5042:        fprintf(ficlog, "\n#********** Variable "); 
1.330     brouard  5043:        for (z1=1; z1<=cptcovs; z1++){
1.251     brouard  5044:          if(!FixedV[Tvaraff[z1]]){
1.330     brouard  5045:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5046:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5047:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5048:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5049:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.250     brouard  5050:          }else{
1.330     brouard  5051:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5052:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5053:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5054:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5055:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.251     brouard  5056:          }
                   5057:        }
                   5058:        printf( "**********\n#");
                   5059:        fprintf(ficresp, "**********\n#");
                   5060:        fprintf(ficresphtm, "**********</h3>\n");
                   5061:        fprintf(ficresphtmfr, "**********</h3>\n");
                   5062:        fprintf(ficlog, "**********\n");
                   5063:       }
1.284     brouard  5064:       /*
                   5065:        Printing means of quantitative variables if any
                   5066:       */
                   5067:       for (z1=1; z1<= nqfveff; z1++) {
1.311     brouard  5068:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.312     brouard  5069:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
1.284     brouard  5070:        if(weightopt==1){
                   5071:          printf(" Weighted mean and standard deviation of");
                   5072:          fprintf(ficlog," Weighted mean and standard deviation of");
                   5073:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   5074:        }
1.311     brouard  5075:        /* mu = \frac{w x}{\sum w}
                   5076:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
                   5077:        */
                   5078:        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]));
                   5079:        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]));
                   5080:        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  5081:       }
                   5082:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   5083:       /*       for(m=1;m<=lastpass;m++){ */
                   5084:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   5085:       /*   } */
                   5086:       /* } */
1.283     brouard  5087: 
1.251     brouard  5088:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.330     brouard  5089:       if((cptcovn==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
1.265     brouard  5090:         fprintf(ficresp, " Age");
1.330     brouard  5091:       if(nj==2) for (z1=1; z1<=cptcovn; z1++) fprintf(ficresp, " V%d=%d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,Tvaraff[z1])]);
1.251     brouard  5092:       for(i=1; i<=nlstate;i++) {
1.330     brouard  5093:        if((cptcovn==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  5094:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   5095:       }
1.330     brouard  5096:       if((cptcovn==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  5097:       fprintf(ficresphtm, "\n");
                   5098:       
                   5099:       /* Header of frequency table by age */
                   5100:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   5101:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  5102:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  5103:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5104:          if(s2!=0 && m!=0)
                   5105:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  5106:        }
1.226     brouard  5107:       }
1.251     brouard  5108:       fprintf(ficresphtmfr, "\n");
                   5109:     
                   5110:       /* For each age */
                   5111:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   5112:        fprintf(ficresphtm,"<tr>");
                   5113:        if(iage==iagemax+1){
                   5114:          fprintf(ficlog,"1");
                   5115:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   5116:        }else if(iage==iagemax+2){
                   5117:          fprintf(ficlog,"0");
                   5118:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   5119:        }else if(iage==iagemax+3){
                   5120:          fprintf(ficlog,"Total");
                   5121:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   5122:        }else{
1.240     brouard  5123:          if(first==1){
1.251     brouard  5124:            first=0;
                   5125:            printf("See log file for details...\n");
                   5126:          }
                   5127:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   5128:          fprintf(ficlog,"Age %d", iage);
                   5129:        }
1.265     brouard  5130:        for(s1=1; s1 <=nlstate ; s1++){
                   5131:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   5132:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  5133:        }
1.265     brouard  5134:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5135:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  5136:            pos += freq[s1][m][iage];
                   5137:          if(pp[s1]>=1.e-10){
1.251     brouard  5138:            if(first==1){
1.265     brouard  5139:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5140:            }
1.265     brouard  5141:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5142:          }else{
                   5143:            if(first==1)
1.265     brouard  5144:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   5145:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  5146:          }
                   5147:        }
                   5148:       
1.265     brouard  5149:        for(s1=1; s1 <=nlstate ; s1++){ 
                   5150:          /* posprop[s1]=0; */
                   5151:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   5152:            pp[s1] += freq[s1][m][iage];
                   5153:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   5154:       
                   5155:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   5156:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   5157:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5158:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5159:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5160:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5161:        }
                   5162:        
                   5163:        /* Writing ficresp */
1.330     brouard  5164:        if(cptcovn==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5165:           if( iage <= iagemax){
                   5166:            fprintf(ficresp," %d",iage);
                   5167:           }
                   5168:         }else if( nj==2){
                   5169:           if( iage <= iagemax){
                   5170:            fprintf(ficresp," %d",iage);
1.330     brouard  5171:             for (z1=1; z1<=cptcovn; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,Tvaraff[z1])]);
1.265     brouard  5172:           }
1.240     brouard  5173:        }
1.265     brouard  5174:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  5175:          if(pos>=1.e-5){
1.251     brouard  5176:            if(first==1)
1.265     brouard  5177:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   5178:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  5179:          }else{
                   5180:            if(first==1)
1.265     brouard  5181:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   5182:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  5183:          }
                   5184:          if( iage <= iagemax){
                   5185:            if(pos>=1.e-5){
1.330     brouard  5186:              if(cptcovn==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5187:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5188:               }else if( nj==2){
                   5189:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5190:               }
                   5191:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5192:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   5193:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   5194:            } else{
1.330     brouard  5195:              if((cptcovn==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
1.265     brouard  5196:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  5197:            }
1.240     brouard  5198:          }
1.265     brouard  5199:          pospropt[s1] +=posprop[s1];
                   5200:        } /* end loop s1 */
1.251     brouard  5201:        /* pospropt=0.; */
1.265     brouard  5202:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  5203:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5204:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  5205:              if(first==1){
1.265     brouard  5206:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5207:              }
1.265     brouard  5208:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   5209:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5210:            }
1.265     brouard  5211:            if(s1!=0 && m!=0)
                   5212:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  5213:          }
1.265     brouard  5214:        } /* end loop s1 */
1.251     brouard  5215:        posproptt=0.; 
1.265     brouard  5216:        for(s1=1; s1 <=nlstate; s1++){
                   5217:          posproptt += pospropt[s1];
1.251     brouard  5218:        }
                   5219:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  5220:        fprintf(ficresphtm,"</tr>\n");
1.330     brouard  5221:        if((cptcovn==0 && nj==1)|| nj==2 ) {
1.265     brouard  5222:          if(iage <= iagemax)
                   5223:            fprintf(ficresp,"\n");
1.240     brouard  5224:        }
1.251     brouard  5225:        if(first==1)
                   5226:          printf("Others in log...\n");
                   5227:        fprintf(ficlog,"\n");
                   5228:       } /* end loop age iage */
1.265     brouard  5229:       
1.251     brouard  5230:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  5231:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5232:        if(posproptt < 1.e-5){
1.265     brouard  5233:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  5234:        }else{
1.265     brouard  5235:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  5236:        }
1.226     brouard  5237:       }
1.251     brouard  5238:       fprintf(ficresphtm,"</tr>\n");
                   5239:       fprintf(ficresphtm,"</table>\n");
                   5240:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  5241:       if(posproptt < 1.e-5){
1.251     brouard  5242:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   5243:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  5244:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   5245:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  5246:        invalidvarcomb[j1]=1;
1.226     brouard  5247:       }else{
1.251     brouard  5248:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
                   5249:        invalidvarcomb[j1]=0;
1.226     brouard  5250:       }
1.251     brouard  5251:       fprintf(ficresphtmfr,"</table>\n");
                   5252:       fprintf(ficlog,"\n");
                   5253:       if(j!=0){
                   5254:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  5255:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5256:          for(k=1; k <=(nlstate+ndeath); k++){
                   5257:            if (k != i) {
1.265     brouard  5258:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  5259:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  5260:                  if(j1==1){ /* All dummy covariates to zero */
                   5261:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   5262:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  5263:                    printf("%d%d ",i,k);
                   5264:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5265:                    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]));
                   5266:                    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]));
                   5267:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  5268:                  }
1.253     brouard  5269:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   5270:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   5271:                    x[iage]= (double)iage;
                   5272:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  5273:                    /* 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  5274:                  }
1.268     brouard  5275:                  /* Some are not finite, but linreg will ignore these ages */
                   5276:                  no=0;
1.253     brouard  5277:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  5278:                  pstart[s1]=b;
                   5279:                  pstart[s1-1]=a;
1.252     brouard  5280:                }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 */ 
                   5281:                  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]);
                   5282:                  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  5283:                  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  5284:                  printf("%d%d ",i,k);
                   5285:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5286:                  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  5287:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   5288:                  ;
                   5289:                }
                   5290:                /* printf("%12.7f )", param[i][jj][k]); */
                   5291:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5292:                s1++; 
1.251     brouard  5293:              } /* end jj */
                   5294:            } /* end k!= i */
                   5295:          } /* end k */
1.265     brouard  5296:        } /* end i, s1 */
1.251     brouard  5297:       } /* end j !=0 */
                   5298:     } /* end selected combination of covariate j1 */
                   5299:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   5300:       printf("#Freqsummary: Starting values for the constants:\n");
                   5301:       fprintf(ficlog,"\n");
1.265     brouard  5302:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5303:        for(k=1; k <=(nlstate+ndeath); k++){
                   5304:          if (k != i) {
                   5305:            printf("%d%d ",i,k);
                   5306:            fprintf(ficlog,"%d%d ",i,k);
                   5307:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  5308:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  5309:              if(jj==1){ /* Age has to be done */
1.265     brouard  5310:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   5311:                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]));
                   5312:                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  5313:              }
                   5314:              /* printf("%12.7f )", param[i][jj][k]); */
                   5315:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5316:              s1++; 
1.250     brouard  5317:            }
1.251     brouard  5318:            printf("\n");
                   5319:            fprintf(ficlog,"\n");
1.250     brouard  5320:          }
                   5321:        }
1.284     brouard  5322:       } /* end of state i */
1.251     brouard  5323:       printf("#Freqsummary\n");
                   5324:       fprintf(ficlog,"\n");
1.265     brouard  5325:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   5326:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   5327:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   5328:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5329:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5330:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   5331:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   5332:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  5333:          /* } */
                   5334:        }
1.265     brouard  5335:       } /* end loop s1 */
1.251     brouard  5336:       
                   5337:       printf("\n");
                   5338:       fprintf(ficlog,"\n");
                   5339:     } /* end j=0 */
1.249     brouard  5340:   } /* end j */
1.252     brouard  5341: 
1.253     brouard  5342:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  5343:     for(i=1, jk=1; i <=nlstate; i++){
                   5344:       for(j=1; j <=nlstate+ndeath; j++){
                   5345:        if(j!=i){
                   5346:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5347:          printf("%1d%1d",i,j);
                   5348:          fprintf(ficparo,"%1d%1d",i,j);
                   5349:          for(k=1; k<=ncovmodel;k++){
                   5350:            /*    printf(" %lf",param[i][j][k]); */
                   5351:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   5352:            p[jk]=pstart[jk];
                   5353:            printf(" %f ",pstart[jk]);
                   5354:            fprintf(ficparo," %f ",pstart[jk]);
                   5355:            jk++;
                   5356:          }
                   5357:          printf("\n");
                   5358:          fprintf(ficparo,"\n");
                   5359:        }
                   5360:       }
                   5361:     }
                   5362:   } /* end mle=-2 */
1.226     brouard  5363:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  5364:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  5365:   
1.226     brouard  5366:   fclose(ficresp);
                   5367:   fclose(ficresphtm);
                   5368:   fclose(ficresphtmfr);
1.283     brouard  5369:   free_vector(idq,1,nqfveff);
1.226     brouard  5370:   free_vector(meanq,1,nqfveff);
1.284     brouard  5371:   free_vector(stdq,1,nqfveff);
1.226     brouard  5372:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  5373:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   5374:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  5375:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5376:   free_vector(pospropt,1,nlstate);
                   5377:   free_vector(posprop,1,nlstate);
1.251     brouard  5378:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5379:   free_vector(pp,1,nlstate);
                   5380:   /* End of freqsummary */
                   5381: }
1.126     brouard  5382: 
1.268     brouard  5383: /* Simple linear regression */
                   5384: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   5385: 
                   5386:   /* y=a+bx regression */
                   5387:   double   sumx = 0.0;                        /* sum of x                      */
                   5388:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   5389:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   5390:   double   sumy = 0.0;                        /* sum of y                      */
                   5391:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   5392:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   5393:   double yhat;
                   5394:   
                   5395:   double denom=0;
                   5396:   int i;
                   5397:   int ne=*no;
                   5398:   
                   5399:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5400:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5401:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5402:       continue;
                   5403:     }
                   5404:     ne=ne+1;
                   5405:     sumx  += x[i];       
                   5406:     sumx2 += x[i]*x[i];  
                   5407:     sumxy += x[i] * y[i];
                   5408:     sumy  += y[i];      
                   5409:     sumy2 += y[i]*y[i]; 
                   5410:     denom = (ne * sumx2 - sumx*sumx);
                   5411:     /* 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); */
                   5412:   } 
                   5413:   
                   5414:   denom = (ne * sumx2 - sumx*sumx);
                   5415:   if (denom == 0) {
                   5416:     // vertical, slope m is infinity
                   5417:     *b = INFINITY;
                   5418:     *a = 0;
                   5419:     if (r) *r = 0;
                   5420:     return 1;
                   5421:   }
                   5422:   
                   5423:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   5424:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   5425:   if (r!=NULL) {
                   5426:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   5427:       sqrt((sumx2 - sumx*sumx/ne) *
                   5428:           (sumy2 - sumy*sumy/ne));
                   5429:   }
                   5430:   *no=ne;
                   5431:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5432:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5433:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5434:       continue;
                   5435:     }
                   5436:     ne=ne+1;
                   5437:     yhat = y[i] - *a -*b* x[i];
                   5438:     sume2  += yhat * yhat ;       
                   5439:     
                   5440:     denom = (ne * sumx2 - sumx*sumx);
                   5441:     /* 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); */
                   5442:   } 
                   5443:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   5444:   *sa= *sb * sqrt(sumx2/ne);
                   5445:   
                   5446:   return 0; 
                   5447: }
                   5448: 
1.126     brouard  5449: /************ Prevalence ********************/
1.227     brouard  5450: 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)
                   5451: {  
                   5452:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   5453:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   5454:      We still use firstpass and lastpass as another selection.
                   5455:   */
1.126     brouard  5456:  
1.227     brouard  5457:   int i, m, jk, j1, bool, z1,j, iv;
                   5458:   int mi; /* Effective wave */
                   5459:   int iage;
                   5460:   double agebegin, ageend;
                   5461: 
                   5462:   double **prop;
                   5463:   double posprop; 
                   5464:   double  y2; /* in fractional years */
                   5465:   int iagemin, iagemax;
                   5466:   int first; /** to stop verbosity which is redirected to log file */
                   5467: 
                   5468:   iagemin= (int) agemin;
                   5469:   iagemax= (int) agemax;
                   5470:   /*pp=vector(1,nlstate);*/
1.251     brouard  5471:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  5472:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   5473:   j1=0;
1.222     brouard  5474:   
1.227     brouard  5475:   /*j=cptcoveff;*/
                   5476:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  5477:   
1.288     brouard  5478:   first=0;
1.227     brouard  5479:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of covariate */
                   5480:     for (i=1; i<=nlstate; i++)  
1.251     brouard  5481:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  5482:        prop[i][iage]=0.0;
                   5483:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   5484:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   5485:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   5486:     
                   5487:     for (i=1; i<=imx; i++) { /* Each individual */
                   5488:       bool=1;
                   5489:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   5490:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   5491:        m=mw[mi][i];
                   5492:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   5493:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   5494:        for (z1=1; z1<=cptcoveff; z1++){
                   5495:          if( Fixed[Tmodelind[z1]]==1){
                   5496:            iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
1.330     brouard  5497:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,Tvaraff[z1])]) /* iv=1 to ntv, right modality */
1.227     brouard  5498:              bool=0;
                   5499:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
1.330     brouard  5500:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,Tvaraff[z1])]) {
1.227     brouard  5501:              bool=0;
                   5502:            }
                   5503:        }
                   5504:        if(bool==1){ /* Otherwise we skip that wave/person */
                   5505:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   5506:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   5507:          if(m >=firstpass && m <=lastpass){
                   5508:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   5509:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   5510:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   5511:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  5512:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  5513:                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); 
                   5514:                exit(1);
                   5515:              }
                   5516:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   5517:                /*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]]);*/
                   5518:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   5519:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   5520:              } /* end valid statuses */ 
                   5521:            } /* end selection of dates */
                   5522:          } /* end selection of waves */
                   5523:        } /* end bool */
                   5524:       } /* end wave */
                   5525:     } /* end individual */
                   5526:     for(i=iagemin; i <= iagemax+3; i++){  
                   5527:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   5528:        posprop += prop[jk][i]; 
                   5529:       } 
                   5530:       
                   5531:       for(jk=1; jk <=nlstate ; jk++){      
                   5532:        if( i <=  iagemax){ 
                   5533:          if(posprop>=1.e-5){ 
                   5534:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   5535:          } else{
1.288     brouard  5536:            if(!first){
                   5537:              first=1;
1.266     brouard  5538:              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]);
                   5539:            }else{
1.288     brouard  5540:              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  5541:            }
                   5542:          }
                   5543:        } 
                   5544:       }/* end jk */ 
                   5545:     }/* end i */ 
1.222     brouard  5546:      /*} *//* end i1 */
1.227     brouard  5547:   } /* end j1 */
1.222     brouard  5548:   
1.227     brouard  5549:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   5550:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  5551:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  5552: }  /* End of prevalence */
1.126     brouard  5553: 
                   5554: /************* Waves Concatenation ***************/
                   5555: 
                   5556: 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)
                   5557: {
1.298     brouard  5558:   /* 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  5559:      Death is a valid wave (if date is known).
                   5560:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   5561:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  5562:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  5563:   */
1.126     brouard  5564: 
1.224     brouard  5565:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  5566:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   5567:      double sum=0., jmean=0.;*/
1.224     brouard  5568:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  5569:   int j, k=0,jk, ju, jl;
                   5570:   double sum=0.;
                   5571:   first=0;
1.214     brouard  5572:   firstwo=0;
1.217     brouard  5573:   firsthree=0;
1.218     brouard  5574:   firstfour=0;
1.164     brouard  5575:   jmin=100000;
1.126     brouard  5576:   jmax=-1;
                   5577:   jmean=0.;
1.224     brouard  5578: 
                   5579: /* Treating live states */
1.214     brouard  5580:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  5581:     mi=0;  /* First valid wave */
1.227     brouard  5582:     mli=0; /* Last valid wave */
1.309     brouard  5583:     m=firstpass;  /* Loop on waves */
                   5584:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
1.227     brouard  5585:       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 */
                   5586:        mli=m-1;/* mw[++mi][i]=m-1; */
                   5587:       }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  5588:        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  5589:        mli=m;
1.224     brouard  5590:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   5591:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  5592:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  5593:       }
1.309     brouard  5594:       else{ /* m = lastpass, eventual special issue with warning */
1.224     brouard  5595: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  5596:        break;
1.224     brouard  5597: #else
1.317     brouard  5598:        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  5599:          if(firsthree == 0){
1.302     brouard  5600:            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  5601:            firsthree=1;
1.317     brouard  5602:          }else if(firsthree >=1 && firsthree < 10){
                   5603:            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);
                   5604:            firsthree++;
                   5605:          }else if(firsthree == 10){
                   5606:            printf("Information, too many Information flags: no more reported to log either\n");
                   5607:            fprintf(ficlog,"Information, too many Information flags: no more reported to log either\n");
                   5608:            firsthree++;
                   5609:          }else{
                   5610:            firsthree++;
1.227     brouard  5611:          }
1.309     brouard  5612:          mw[++mi][i]=m; /* Valid transition with unknown status */
1.227     brouard  5613:          mli=m;
                   5614:        }
                   5615:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   5616:          nbwarn++;
1.309     brouard  5617:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
1.227     brouard  5618:            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);
                   5619:            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);
                   5620:          }
                   5621:          break;
                   5622:        }
                   5623:        break;
1.224     brouard  5624: #endif
1.227     brouard  5625:       }/* End m >= lastpass */
1.126     brouard  5626:     }/* end while */
1.224     brouard  5627: 
1.227     brouard  5628:     /* 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  5629:     /* After last pass */
1.224     brouard  5630: /* Treating death states */
1.214     brouard  5631:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  5632:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   5633:       /* } */
1.126     brouard  5634:       mi++;    /* Death is another wave */
                   5635:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  5636:       /* Only death is a correct wave */
1.126     brouard  5637:       mw[mi][i]=m;
1.257     brouard  5638:     } /* else not in a death state */
1.224     brouard  5639: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  5640:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  5641:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.309     brouard  5642:        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  5643:          nbwarn++;
                   5644:          if(firstfiv==0){
1.309     brouard  5645:            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  5646:            firstfiv=1;
                   5647:          }else{
1.309     brouard  5648:            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  5649:          }
1.309     brouard  5650:            s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
                   5651:        }else{ /* Month of Death occured afer last wave month, potential bias */
1.227     brouard  5652:          nberr++;
                   5653:          if(firstwo==0){
1.309     brouard  5654:            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  5655:            firstwo=1;
                   5656:          }
1.309     brouard  5657:          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  5658:        }
1.257     brouard  5659:       }else{ /* if date of interview is unknown */
1.227     brouard  5660:        /* death is known but not confirmed by death status at any wave */
                   5661:        if(firstfour==0){
1.309     brouard  5662:          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  5663:          firstfour=1;
                   5664:        }
1.309     brouard  5665:        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  5666:       }
1.224     brouard  5667:     } /* end if date of death is known */
                   5668: #endif
1.309     brouard  5669:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
                   5670:     /* wav[i]=mw[mi][i];   */
1.126     brouard  5671:     if(mi==0){
                   5672:       nbwarn++;
                   5673:       if(first==0){
1.227     brouard  5674:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   5675:        first=1;
1.126     brouard  5676:       }
                   5677:       if(first==1){
1.227     brouard  5678:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  5679:       }
                   5680:     } /* end mi==0 */
                   5681:   } /* End individuals */
1.214     brouard  5682:   /* wav and mw are no more changed */
1.223     brouard  5683:        
1.317     brouard  5684:   printf("Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   5685:   fprintf(ficlog,"Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   5686: 
                   5687: 
1.126     brouard  5688:   for(i=1; i<=imx; i++){
                   5689:     for(mi=1; mi<wav[i];mi++){
                   5690:       if (stepm <=0)
1.227     brouard  5691:        dh[mi][i]=1;
1.126     brouard  5692:       else{
1.260     brouard  5693:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  5694:          if (agedc[i] < 2*AGESUP) {
                   5695:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   5696:            if(j==0) j=1;  /* Survives at least one month after exam */
                   5697:            else if(j<0){
                   5698:              nberr++;
                   5699:              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]);
                   5700:              j=1; /* Temporary Dangerous patch */
                   5701:              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);
                   5702:              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]);
                   5703:              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);
                   5704:            }
                   5705:            k=k+1;
                   5706:            if (j >= jmax){
                   5707:              jmax=j;
                   5708:              ijmax=i;
                   5709:            }
                   5710:            if (j <= jmin){
                   5711:              jmin=j;
                   5712:              ijmin=i;
                   5713:            }
                   5714:            sum=sum+j;
                   5715:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   5716:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   5717:          }
                   5718:        }
                   5719:        else{
                   5720:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  5721: /*       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  5722:                                        
1.227     brouard  5723:          k=k+1;
                   5724:          if (j >= jmax) {
                   5725:            jmax=j;
                   5726:            ijmax=i;
                   5727:          }
                   5728:          else if (j <= jmin){
                   5729:            jmin=j;
                   5730:            ijmin=i;
                   5731:          }
                   5732:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   5733:          /*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]);*/
                   5734:          if(j<0){
                   5735:            nberr++;
                   5736:            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]);
                   5737:            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]);
                   5738:          }
                   5739:          sum=sum+j;
                   5740:        }
                   5741:        jk= j/stepm;
                   5742:        jl= j -jk*stepm;
                   5743:        ju= j -(jk+1)*stepm;
                   5744:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   5745:          if(jl==0){
                   5746:            dh[mi][i]=jk;
                   5747:            bh[mi][i]=0;
                   5748:          }else{ /* We want a negative bias in order to only have interpolation ie
                   5749:                  * to avoid the price of an extra matrix product in likelihood */
                   5750:            dh[mi][i]=jk+1;
                   5751:            bh[mi][i]=ju;
                   5752:          }
                   5753:        }else{
                   5754:          if(jl <= -ju){
                   5755:            dh[mi][i]=jk;
                   5756:            bh[mi][i]=jl;       /* bias is positive if real duration
                   5757:                                 * is higher than the multiple of stepm and negative otherwise.
                   5758:                                 */
                   5759:          }
                   5760:          else{
                   5761:            dh[mi][i]=jk+1;
                   5762:            bh[mi][i]=ju;
                   5763:          }
                   5764:          if(dh[mi][i]==0){
                   5765:            dh[mi][i]=1; /* At least one step */
                   5766:            bh[mi][i]=ju; /* At least one step */
                   5767:            /*  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);*/
                   5768:          }
                   5769:        } /* end if mle */
1.126     brouard  5770:       }
                   5771:     } /* end wave */
                   5772:   }
                   5773:   jmean=sum/k;
                   5774:   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  5775:   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  5776: }
1.126     brouard  5777: 
                   5778: /*********** Tricode ****************************/
1.220     brouard  5779:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  5780:  {
                   5781:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   5782:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   5783:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   5784:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   5785:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   5786:     */
1.130     brouard  5787: 
1.242     brouard  5788:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   5789:    int modmaxcovj=0; /* Modality max of covariates j */
                   5790:    int cptcode=0; /* Modality max of covariates j */
                   5791:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  5792: 
                   5793: 
1.242     brouard  5794:    /* cptcoveff=0;  */
                   5795:    /* *cptcov=0; */
1.126     brouard  5796:  
1.242     brouard  5797:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  5798:    for (k=1; k <= maxncov; k++)
                   5799:      for(j=1; j<=2; j++)
                   5800:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  5801: 
1.242     brouard  5802:    /* Loop on covariates without age and products and no quantitative variable */
                   5803:    for (k=1; k<=cptcovt; k++) { /* From model V1 + V2*age + V3 + V3*V4 keeps V1 + V3 = 2 only */
                   5804:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
                   5805:      if(Dummy[k]==0 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
                   5806:        switch(Fixed[k]) {
                   5807:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.311     brouard  5808:         modmaxcovj=0;
                   5809:         modmincovj=0;
1.242     brouard  5810:         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*/
                   5811:           ij=(int)(covar[Tvar[k]][i]);
                   5812:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   5813:            * If product of Vn*Vm, still boolean *:
                   5814:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   5815:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   5816:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   5817:              modality of the nth covariate of individual i. */
                   5818:           if (ij > modmaxcovj)
                   5819:             modmaxcovj=ij; 
                   5820:           else if (ij < modmincovj) 
                   5821:             modmincovj=ij; 
1.287     brouard  5822:           if (ij <0 || ij >1 ){
1.311     brouard  5823:             printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   5824:             fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   5825:             fflush(ficlog);
                   5826:             exit(1);
1.287     brouard  5827:           }
                   5828:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  5829:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   5830:             exit(1);
                   5831:           }else
                   5832:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   5833:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   5834:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   5835:           /* getting the maximum value of the modality of the covariate
                   5836:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   5837:              female ies 1, then modmaxcovj=1.
                   5838:           */
                   5839:         } /* end for loop on individuals i */
                   5840:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   5841:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   5842:         cptcode=modmaxcovj;
                   5843:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   5844:         /*for (i=0; i<=cptcode; i++) {*/
                   5845:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   5846:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   5847:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   5848:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   5849:             if( j != -1){
                   5850:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   5851:                                  covariate for which somebody answered excluding 
                   5852:                                  undefined. Usually 2: 0 and 1. */
                   5853:             }
                   5854:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   5855:                                     covariate for which somebody answered including 
                   5856:                                     undefined. Usually 3: -1, 0 and 1. */
                   5857:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   5858:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   5859:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  5860:                        
1.242     brouard  5861:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   5862:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   5863:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   5864:         /* modmincovj=3; modmaxcovj = 7; */
                   5865:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   5866:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   5867:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   5868:         /* nbcode[Tvar[j]][ij]=k; */
                   5869:         /* nbcode[Tvar[j]][1]=0; */
                   5870:         /* nbcode[Tvar[j]][2]=1; */
                   5871:         /* nbcode[Tvar[j]][3]=2; */
                   5872:         /* To be continued (not working yet). */
                   5873:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  5874: 
                   5875:         /* 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*/
                   5876:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   5877:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   5878:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   5879:         /*, could be restored in the future */
                   5880:         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  5881:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   5882:             break;
                   5883:           }
                   5884:           ij++;
1.287     brouard  5885:           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  5886:           cptcode = ij; /* New max modality for covar j */
                   5887:         } /* end of loop on modality i=-1 to 1 or more */
                   5888:         break;
                   5889:        case 1: /* Testing on varying covariate, could be simple and
                   5890:                * should look at waves or product of fixed *
                   5891:                * varying. No time to test -1, assuming 0 and 1 only */
                   5892:         ij=0;
                   5893:         for(i=0; i<=1;i++){
                   5894:           nbcode[Tvar[k]][++ij]=i;
                   5895:         }
                   5896:         break;
                   5897:        default:
                   5898:         break;
                   5899:        } /* end switch */
                   5900:      } /* end dummy test */
1.311     brouard  5901:      if(Dummy[k]==1 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
                   5902:        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*/
                   5903:         if(isnan(covar[Tvar[k]][i])){
                   5904:           printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   5905:           fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   5906:           fflush(ficlog);
                   5907:           exit(1);
                   5908:          }
                   5909:        }
                   5910:      }
1.287     brouard  5911:    } /* 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  5912:   
                   5913:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   5914:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   5915:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   5916:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   5917:      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 */ 
                   5918:      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 */
                   5919:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   5920:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   5921:   
                   5922:    ij=0;
                   5923:    /* for (i=0; i<=  maxncov-1; i++) { /\* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) *\/ */
                   5924:    for (k=1; k<=  cptcovt; k++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   5925:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   5926:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
                   5927:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy and non empty in the model */
                   5928:        /* If product not in single variable we don't print results */
                   5929:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   5930:        ++ij;/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, */
                   5931:        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*/
                   5932:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   5933:        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 */
                   5934:        if(Fixed[k]!=0)
                   5935:         anyvaryingduminmodel=1;
                   5936:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   5937:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   5938:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   5939:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   5940:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   5941:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   5942:      } 
                   5943:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   5944:    /* ij--; */
                   5945:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
1.330     brouard  5946:    *cptcov=ij; /* cptcov= Number of total real effective covariates: effective (used as cptcoveff in other functions)
1.242     brouard  5947:                * because they can be excluded from the model and real
                   5948:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   5949:    for(j=ij+1; j<= cptcovt; j++){
                   5950:      Tvaraff[j]=0;
                   5951:      Tmodelind[j]=0;
                   5952:    }
                   5953:    for(j=ntveff+1; j<= cptcovt; j++){
                   5954:      TmodelInvind[j]=0;
                   5955:    }
                   5956:    /* To be sorted */
                   5957:    ;
                   5958:  }
1.126     brouard  5959: 
1.145     brouard  5960: 
1.126     brouard  5961: /*********** Health Expectancies ****************/
                   5962: 
1.235     brouard  5963:  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  5964: 
                   5965: {
                   5966:   /* Health expectancies, no variances */
1.329     brouard  5967:   /* cij is the combination in the list of combination of dummy covariates */
                   5968:   /* strstart is a string of time at start of computing */
1.164     brouard  5969:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  5970:   int nhstepma, nstepma; /* Decreasing with age */
                   5971:   double age, agelim, hf;
                   5972:   double ***p3mat;
                   5973:   double eip;
                   5974: 
1.238     brouard  5975:   /* pstamp(ficreseij); */
1.126     brouard  5976:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   5977:   fprintf(ficreseij,"# Age");
                   5978:   for(i=1; i<=nlstate;i++){
                   5979:     for(j=1; j<=nlstate;j++){
                   5980:       fprintf(ficreseij," e%1d%1d ",i,j);
                   5981:     }
                   5982:     fprintf(ficreseij," e%1d. ",i);
                   5983:   }
                   5984:   fprintf(ficreseij,"\n");
                   5985: 
                   5986:   
                   5987:   if(estepm < stepm){
                   5988:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5989:   }
                   5990:   else  hstepm=estepm;   
                   5991:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   5992:    * This is mainly to measure the difference between two models: for example
                   5993:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   5994:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   5995:    * progression in between and thus overestimating or underestimating according
                   5996:    * to the curvature of the survival function. If, for the same date, we 
                   5997:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   5998:    * to compare the new estimate of Life expectancy with the same linear 
                   5999:    * hypothesis. A more precise result, taking into account a more precise
                   6000:    * curvature will be obtained if estepm is as small as stepm. */
                   6001: 
                   6002:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6003:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6004:      nhstepm is the number of hstepm from age to agelim 
                   6005:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  6006:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  6007:      and note for a fixed period like estepm months */
                   6008:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6009:      survival function given by stepm (the optimization length). Unfortunately it
                   6010:      means that if the survival funtion is printed only each two years of age and if
                   6011:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6012:      results. So we changed our mind and took the option of the best precision.
                   6013:   */
                   6014:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6015: 
                   6016:   agelim=AGESUP;
                   6017:   /* If stepm=6 months */
                   6018:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   6019:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   6020:     
                   6021: /* nhstepm age range expressed in number of stepm */
                   6022:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6023:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6024:   /* if (stepm >= YEARM) hstepm=1;*/
                   6025:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6026:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6027: 
                   6028:   for (age=bage; age<=fage; age ++){ 
                   6029:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6030:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6031:     /* if (stepm >= YEARM) hstepm=1;*/
                   6032:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   6033: 
                   6034:     /* If stepm=6 months */
                   6035:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6036:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
1.330     brouard  6037:     /* 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  6038:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  6039:     
                   6040:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6041:     
                   6042:     printf("%d|",(int)age);fflush(stdout);
                   6043:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6044:     
                   6045:     /* Computing expectancies */
                   6046:     for(i=1; i<=nlstate;i++)
                   6047:       for(j=1; j<=nlstate;j++)
                   6048:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6049:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   6050:          
                   6051:          /* 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]);*/
                   6052: 
                   6053:        }
                   6054: 
                   6055:     fprintf(ficreseij,"%3.0f",age );
                   6056:     for(i=1; i<=nlstate;i++){
                   6057:       eip=0;
                   6058:       for(j=1; j<=nlstate;j++){
                   6059:        eip +=eij[i][j][(int)age];
                   6060:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   6061:       }
                   6062:       fprintf(ficreseij,"%9.4f", eip );
                   6063:     }
                   6064:     fprintf(ficreseij,"\n");
                   6065:     
                   6066:   }
                   6067:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6068:   printf("\n");
                   6069:   fprintf(ficlog,"\n");
                   6070:   
                   6071: }
                   6072: 
1.235     brouard  6073:  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  6074: 
                   6075: {
                   6076:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  6077:      to initial status i, ei. .
1.126     brouard  6078:   */
                   6079:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   6080:   int nhstepma, nstepma; /* Decreasing with age */
                   6081:   double age, agelim, hf;
                   6082:   double ***p3matp, ***p3matm, ***varhe;
                   6083:   double **dnewm,**doldm;
                   6084:   double *xp, *xm;
                   6085:   double **gp, **gm;
                   6086:   double ***gradg, ***trgradg;
                   6087:   int theta;
                   6088: 
                   6089:   double eip, vip;
                   6090: 
                   6091:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   6092:   xp=vector(1,npar);
                   6093:   xm=vector(1,npar);
                   6094:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   6095:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   6096:   
                   6097:   pstamp(ficresstdeij);
                   6098:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   6099:   fprintf(ficresstdeij,"# Age");
                   6100:   for(i=1; i<=nlstate;i++){
                   6101:     for(j=1; j<=nlstate;j++)
                   6102:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   6103:     fprintf(ficresstdeij," e%1d. ",i);
                   6104:   }
                   6105:   fprintf(ficresstdeij,"\n");
                   6106: 
                   6107:   pstamp(ficrescveij);
                   6108:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   6109:   fprintf(ficrescveij,"# Age");
                   6110:   for(i=1; i<=nlstate;i++)
                   6111:     for(j=1; j<=nlstate;j++){
                   6112:       cptj= (j-1)*nlstate+i;
                   6113:       for(i2=1; i2<=nlstate;i2++)
                   6114:        for(j2=1; j2<=nlstate;j2++){
                   6115:          cptj2= (j2-1)*nlstate+i2;
                   6116:          if(cptj2 <= cptj)
                   6117:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   6118:        }
                   6119:     }
                   6120:   fprintf(ficrescveij,"\n");
                   6121:   
                   6122:   if(estepm < stepm){
                   6123:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6124:   }
                   6125:   else  hstepm=estepm;   
                   6126:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6127:    * This is mainly to measure the difference between two models: for example
                   6128:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6129:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6130:    * progression in between and thus overestimating or underestimating according
                   6131:    * to the curvature of the survival function. If, for the same date, we 
                   6132:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6133:    * to compare the new estimate of Life expectancy with the same linear 
                   6134:    * hypothesis. A more precise result, taking into account a more precise
                   6135:    * curvature will be obtained if estepm is as small as stepm. */
                   6136: 
                   6137:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6138:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6139:      nhstepm is the number of hstepm from age to agelim 
                   6140:      nstepm is the number of stepm from age to agelin. 
                   6141:      Look at hpijx to understand the reason of that which relies in memory size
                   6142:      and note for a fixed period like estepm months */
                   6143:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6144:      survival function given by stepm (the optimization length). Unfortunately it
                   6145:      means that if the survival funtion is printed only each two years of age and if
                   6146:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6147:      results. So we changed our mind and took the option of the best precision.
                   6148:   */
                   6149:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6150: 
                   6151:   /* If stepm=6 months */
                   6152:   /* nhstepm age range expressed in number of stepm */
                   6153:   agelim=AGESUP;
                   6154:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   6155:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6156:   /* if (stepm >= YEARM) hstepm=1;*/
                   6157:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6158:   
                   6159:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6160:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6161:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   6162:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   6163:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   6164:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   6165: 
                   6166:   for (age=bage; age<=fage; age ++){ 
                   6167:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6168:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6169:     /* if (stepm >= YEARM) hstepm=1;*/
                   6170:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  6171:                
1.126     brouard  6172:     /* If stepm=6 months */
                   6173:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6174:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   6175:     
                   6176:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  6177:                
1.126     brouard  6178:     /* Computing  Variances of health expectancies */
                   6179:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   6180:        decrease memory allocation */
                   6181:     for(theta=1; theta <=npar; theta++){
                   6182:       for(i=1; i<=npar; i++){ 
1.222     brouard  6183:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6184:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  6185:       }
1.235     brouard  6186:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   6187:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  6188:                        
1.126     brouard  6189:       for(j=1; j<= nlstate; j++){
1.222     brouard  6190:        for(i=1; i<=nlstate; i++){
                   6191:          for(h=0; h<=nhstepm-1; h++){
                   6192:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   6193:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   6194:          }
                   6195:        }
1.126     brouard  6196:       }
1.218     brouard  6197:                        
1.126     brouard  6198:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  6199:        for(h=0; h<=nhstepm-1; h++){
                   6200:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   6201:        }
1.126     brouard  6202:     }/* End theta */
                   6203:     
                   6204:     
                   6205:     for(h=0; h<=nhstepm-1; h++)
                   6206:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  6207:        for(theta=1; theta <=npar; theta++)
                   6208:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  6209:     
1.218     brouard  6210:                
1.222     brouard  6211:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  6212:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  6213:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  6214:                
1.222     brouard  6215:     printf("%d|",(int)age);fflush(stdout);
                   6216:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6217:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  6218:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  6219:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   6220:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   6221:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   6222:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   6223:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  6224:       }
                   6225:     }
1.320     brouard  6226:     /* if((int)age ==50){ */
                   6227:     /*   printf(" age=%d cij=%d nres=%d varhe[%d][%d]=%f ",(int)age, cij, nres, 1,2,varhe[1][2]); */
                   6228:     /* } */
1.126     brouard  6229:     /* Computing expectancies */
1.235     brouard  6230:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  6231:     for(i=1; i<=nlstate;i++)
                   6232:       for(j=1; j<=nlstate;j++)
1.222     brouard  6233:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6234:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  6235:                                        
1.222     brouard  6236:          /* 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  6237:                                        
1.222     brouard  6238:        }
1.269     brouard  6239: 
                   6240:     /* Standard deviation of expectancies ij */                
1.126     brouard  6241:     fprintf(ficresstdeij,"%3.0f",age );
                   6242:     for(i=1; i<=nlstate;i++){
                   6243:       eip=0.;
                   6244:       vip=0.;
                   6245:       for(j=1; j<=nlstate;j++){
1.222     brouard  6246:        eip += eij[i][j][(int)age];
                   6247:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   6248:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   6249:        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  6250:       }
                   6251:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   6252:     }
                   6253:     fprintf(ficresstdeij,"\n");
1.218     brouard  6254:                
1.269     brouard  6255:     /* Variance of expectancies ij */          
1.126     brouard  6256:     fprintf(ficrescveij,"%3.0f",age );
                   6257:     for(i=1; i<=nlstate;i++)
                   6258:       for(j=1; j<=nlstate;j++){
1.222     brouard  6259:        cptj= (j-1)*nlstate+i;
                   6260:        for(i2=1; i2<=nlstate;i2++)
                   6261:          for(j2=1; j2<=nlstate;j2++){
                   6262:            cptj2= (j2-1)*nlstate+i2;
                   6263:            if(cptj2 <= cptj)
                   6264:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   6265:          }
1.126     brouard  6266:       }
                   6267:     fprintf(ficrescveij,"\n");
1.218     brouard  6268:                
1.126     brouard  6269:   }
                   6270:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   6271:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   6272:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   6273:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   6274:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6275:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6276:   printf("\n");
                   6277:   fprintf(ficlog,"\n");
1.218     brouard  6278:        
1.126     brouard  6279:   free_vector(xm,1,npar);
                   6280:   free_vector(xp,1,npar);
                   6281:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   6282:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   6283:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   6284: }
1.218     brouard  6285:  
1.126     brouard  6286: /************ Variance ******************/
1.235     brouard  6287:  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  6288:  {
1.279     brouard  6289:    /** Variance of health expectancies 
                   6290:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   6291:     * double **newm;
                   6292:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   6293:     */
1.218     brouard  6294:   
                   6295:    /* int movingaverage(); */
                   6296:    double **dnewm,**doldm;
                   6297:    double **dnewmp,**doldmp;
                   6298:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  6299:    int first=0;
1.218     brouard  6300:    int k;
                   6301:    double *xp;
1.279     brouard  6302:    double **gp, **gm;  /**< for var eij */
                   6303:    double ***gradg, ***trgradg; /**< for var eij */
                   6304:    double **gradgp, **trgradgp; /**< for var p point j */
                   6305:    double *gpp, *gmp; /**< for var p point j */
                   6306:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
1.218     brouard  6307:    double ***p3mat;
                   6308:    double age,agelim, hf;
                   6309:    /* double ***mobaverage; */
                   6310:    int theta;
                   6311:    char digit[4];
                   6312:    char digitp[25];
                   6313: 
                   6314:    char fileresprobmorprev[FILENAMELENGTH];
                   6315: 
                   6316:    if(popbased==1){
                   6317:      if(mobilav!=0)
                   6318:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   6319:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   6320:    }
                   6321:    else 
                   6322:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  6323: 
1.218     brouard  6324:    /* if (mobilav!=0) { */
                   6325:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6326:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   6327:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   6328:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   6329:    /*   } */
                   6330:    /* } */
                   6331: 
                   6332:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   6333:    sprintf(digit,"%-d",ij);
                   6334:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   6335:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   6336:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   6337:    strcat(fileresprobmorprev,fileresu);
                   6338:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   6339:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   6340:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   6341:    }
                   6342:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6343:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6344:    pstamp(ficresprobmorprev);
                   6345:    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  6346:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
                   6347:    for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   6348:      fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   6349:    }
                   6350:    for(j=1;j<=cptcoveff;j++) 
1.330     brouard  6351:      fprintf(ficresprobmorprev,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,Tvaraff[j])]);
1.238     brouard  6352:    fprintf(ficresprobmorprev,"\n");
                   6353: 
1.218     brouard  6354:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   6355:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6356:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   6357:      for(i=1; i<=nlstate;i++)
                   6358:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   6359:    }  
                   6360:    fprintf(ficresprobmorprev,"\n");
                   6361:   
                   6362:    fprintf(ficgp,"\n# Routine varevsij");
                   6363:    fprintf(ficgp,"\nunset title \n");
                   6364:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   6365:    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");
                   6366:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  6367: 
1.218     brouard  6368:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6369:    pstamp(ficresvij);
                   6370:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   6371:    if(popbased==1)
                   6372:      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);
                   6373:    else
                   6374:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   6375:    fprintf(ficresvij,"# Age");
                   6376:    for(i=1; i<=nlstate;i++)
                   6377:      for(j=1; j<=nlstate;j++)
                   6378:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   6379:    fprintf(ficresvij,"\n");
                   6380: 
                   6381:    xp=vector(1,npar);
                   6382:    dnewm=matrix(1,nlstate,1,npar);
                   6383:    doldm=matrix(1,nlstate,1,nlstate);
                   6384:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   6385:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6386: 
                   6387:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   6388:    gpp=vector(nlstate+1,nlstate+ndeath);
                   6389:    gmp=vector(nlstate+1,nlstate+ndeath);
                   6390:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  6391:   
1.218     brouard  6392:    if(estepm < stepm){
                   6393:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   6394:    }
                   6395:    else  hstepm=estepm;   
                   6396:    /* For example we decided to compute the life expectancy with the smallest unit */
                   6397:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6398:       nhstepm is the number of hstepm from age to agelim 
                   6399:       nstepm is the number of stepm from age to agelim. 
                   6400:       Look at function hpijx to understand why because of memory size limitations, 
                   6401:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   6402:       survival function given by stepm (the optimization length). Unfortunately it
                   6403:       means that if the survival funtion is printed every two years of age and if
                   6404:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6405:       results. So we changed our mind and took the option of the best precision.
                   6406:    */
                   6407:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6408:    agelim = AGESUP;
                   6409:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6410:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6411:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6412:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6413:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   6414:      gp=matrix(0,nhstepm,1,nlstate);
                   6415:      gm=matrix(0,nhstepm,1,nlstate);
                   6416:                
                   6417:                
                   6418:      for(theta=1; theta <=npar; theta++){
                   6419:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   6420:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6421:        }
1.279     brouard  6422:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   6423:        * returns into prlim .
1.288     brouard  6424:        */
1.242     brouard  6425:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  6426: 
                   6427:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  6428:        if (popbased==1) {
                   6429:         if(mobilav ==0){
                   6430:           for(i=1; i<=nlstate;i++)
                   6431:             prlim[i][i]=probs[(int)age][i][ij];
                   6432:         }else{ /* mobilav */ 
                   6433:           for(i=1; i<=nlstate;i++)
                   6434:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6435:         }
                   6436:        }
1.295     brouard  6437:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  6438:        */                      
                   6439:        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  6440:        /**< 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  6441:        * at horizon h in state j including mortality.
                   6442:        */
1.218     brouard  6443:        for(j=1; j<= nlstate; j++){
                   6444:         for(h=0; h<=nhstepm; h++){
                   6445:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   6446:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6447:         }
                   6448:        }
1.279     brouard  6449:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  6450:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  6451:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  6452:        */
                   6453:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6454:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   6455:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  6456:        }
                   6457:        
                   6458:        /* Again with minus shift */
1.218     brouard  6459:                        
                   6460:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   6461:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6462: 
1.242     brouard  6463:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  6464:                        
                   6465:        if (popbased==1) {
                   6466:         if(mobilav ==0){
                   6467:           for(i=1; i<=nlstate;i++)
                   6468:             prlim[i][i]=probs[(int)age][i][ij];
                   6469:         }else{ /* mobilav */ 
                   6470:           for(i=1; i<=nlstate;i++)
                   6471:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6472:         }
                   6473:        }
                   6474:                        
1.235     brouard  6475:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  6476:                        
                   6477:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   6478:         for(h=0; h<=nhstepm; h++){
                   6479:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   6480:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6481:         }
                   6482:        }
                   6483:        /* This for computing probability of death (h=1 means
                   6484:          computed over hstepm matrices product = hstepm*stepm months) 
                   6485:          as a weighted average of prlim.
                   6486:        */
                   6487:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6488:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   6489:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   6490:        }    
1.279     brouard  6491:        /* end shifting computations */
                   6492: 
                   6493:        /**< Computing gradient matrix at horizon h 
                   6494:        */
1.218     brouard  6495:        for(j=1; j<= nlstate; j++) /* vareij */
                   6496:         for(h=0; h<=nhstepm; h++){
                   6497:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   6498:         }
1.279     brouard  6499:        /**< Gradient of overall mortality p.3 (or p.j) 
                   6500:        */
                   6501:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
1.218     brouard  6502:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   6503:        }
                   6504:                        
                   6505:      } /* End theta */
1.279     brouard  6506:      
                   6507:      /* We got the gradient matrix for each theta and state j */               
1.218     brouard  6508:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   6509:                
                   6510:      for(h=0; h<=nhstepm; h++) /* veij */
                   6511:        for(j=1; j<=nlstate;j++)
                   6512:         for(theta=1; theta <=npar; theta++)
                   6513:           trgradg[h][j][theta]=gradg[h][theta][j];
                   6514:                
                   6515:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   6516:        for(theta=1; theta <=npar; theta++)
                   6517:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  6518:      /**< as well as its transposed matrix 
                   6519:       */               
1.218     brouard  6520:                
                   6521:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6522:      for(i=1;i<=nlstate;i++)
                   6523:        for(j=1;j<=nlstate;j++)
                   6524:         vareij[i][j][(int)age] =0.;
1.279     brouard  6525: 
                   6526:      /* Computing trgradg by matcov by gradg at age and summing over h
                   6527:       * and k (nhstepm) formula 15 of article
                   6528:       * Lievre-Brouard-Heathcote
                   6529:       */
                   6530:      
1.218     brouard  6531:      for(h=0;h<=nhstepm;h++){
                   6532:        for(k=0;k<=nhstepm;k++){
                   6533:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   6534:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   6535:         for(i=1;i<=nlstate;i++)
                   6536:           for(j=1;j<=nlstate;j++)
                   6537:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   6538:        }
                   6539:      }
                   6540:                
1.279     brouard  6541:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
                   6542:       * p.j overall mortality formula 49 but computed directly because
                   6543:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   6544:       * wix is independent of theta.
                   6545:       */
1.218     brouard  6546:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   6547:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   6548:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   6549:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   6550:         varppt[j][i]=doldmp[j][i];
                   6551:      /* end ppptj */
                   6552:      /*  x centered again */
                   6553:                
1.242     brouard  6554:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  6555:                
                   6556:      if (popbased==1) {
                   6557:        if(mobilav ==0){
                   6558:         for(i=1; i<=nlstate;i++)
                   6559:           prlim[i][i]=probs[(int)age][i][ij];
                   6560:        }else{ /* mobilav */ 
                   6561:         for(i=1; i<=nlstate;i++)
                   6562:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   6563:        }
                   6564:      }
                   6565:                
                   6566:      /* This for computing probability of death (h=1 means
                   6567:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   6568:        as a weighted average of prlim.
                   6569:      */
1.235     brouard  6570:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  6571:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6572:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   6573:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   6574:      }    
                   6575:      /* end probability of death */
                   6576:                
                   6577:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   6578:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6579:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   6580:        for(i=1; i<=nlstate;i++){
                   6581:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   6582:        }
                   6583:      } 
                   6584:      fprintf(ficresprobmorprev,"\n");
                   6585:                
                   6586:      fprintf(ficresvij,"%.0f ",age );
                   6587:      for(i=1; i<=nlstate;i++)
                   6588:        for(j=1; j<=nlstate;j++){
                   6589:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   6590:        }
                   6591:      fprintf(ficresvij,"\n");
                   6592:      free_matrix(gp,0,nhstepm,1,nlstate);
                   6593:      free_matrix(gm,0,nhstepm,1,nlstate);
                   6594:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   6595:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   6596:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6597:    } /* End age */
                   6598:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   6599:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   6600:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   6601:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   6602:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   6603:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   6604:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   6605:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   6606:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   6607:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   6608:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6609:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6610:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   6611:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   6612:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   6613:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   6614:    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);
                   6615:    /*  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  6616:     */
1.218     brouard  6617:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   6618:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  6619: 
1.218     brouard  6620:    free_vector(xp,1,npar);
                   6621:    free_matrix(doldm,1,nlstate,1,nlstate);
                   6622:    free_matrix(dnewm,1,nlstate,1,npar);
                   6623:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6624:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   6625:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6626:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6627:    fclose(ficresprobmorprev);
                   6628:    fflush(ficgp);
                   6629:    fflush(fichtm); 
                   6630:  }  /* end varevsij */
1.126     brouard  6631: 
                   6632: /************ Variance of prevlim ******************/
1.269     brouard  6633:  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  6634: {
1.205     brouard  6635:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  6636:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  6637: 
1.268     brouard  6638:   double **dnewmpar,**doldm;
1.126     brouard  6639:   int i, j, nhstepm, hstepm;
                   6640:   double *xp;
                   6641:   double *gp, *gm;
                   6642:   double **gradg, **trgradg;
1.208     brouard  6643:   double **mgm, **mgp;
1.126     brouard  6644:   double age,agelim;
                   6645:   int theta;
                   6646:   
                   6647:   pstamp(ficresvpl);
1.288     brouard  6648:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  6649:   fprintf(ficresvpl,"# Age ");
                   6650:   if(nresult >=1)
                   6651:     fprintf(ficresvpl," Result# ");
1.126     brouard  6652:   for(i=1; i<=nlstate;i++)
                   6653:       fprintf(ficresvpl," %1d-%1d",i,i);
                   6654:   fprintf(ficresvpl,"\n");
                   6655: 
                   6656:   xp=vector(1,npar);
1.268     brouard  6657:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  6658:   doldm=matrix(1,nlstate,1,nlstate);
                   6659:   
                   6660:   hstepm=1*YEARM; /* Every year of age */
                   6661:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   6662:   agelim = AGESUP;
                   6663:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6664:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6665:     if (stepm >= YEARM) hstepm=1;
                   6666:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6667:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  6668:     mgp=matrix(1,npar,1,nlstate);
                   6669:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  6670:     gp=vector(1,nlstate);
                   6671:     gm=vector(1,nlstate);
                   6672: 
                   6673:     for(theta=1; theta <=npar; theta++){
                   6674:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   6675:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6676:       }
1.288     brouard  6677:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6678:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6679:       /* else */
                   6680:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6681:       for(i=1;i<=nlstate;i++){
1.126     brouard  6682:        gp[i] = prlim[i][i];
1.208     brouard  6683:        mgp[theta][i] = prlim[i][i];
                   6684:       }
1.126     brouard  6685:       for(i=1; i<=npar; i++) /* Computes gradient */
                   6686:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6687:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6688:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6689:       /* else */
                   6690:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6691:       for(i=1;i<=nlstate;i++){
1.126     brouard  6692:        gm[i] = prlim[i][i];
1.208     brouard  6693:        mgm[theta][i] = prlim[i][i];
                   6694:       }
1.126     brouard  6695:       for(i=1;i<=nlstate;i++)
                   6696:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  6697:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  6698:     } /* End theta */
                   6699: 
                   6700:     trgradg =matrix(1,nlstate,1,npar);
                   6701: 
                   6702:     for(j=1; j<=nlstate;j++)
                   6703:       for(theta=1; theta <=npar; theta++)
                   6704:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  6705:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6706:     /*   printf("\nmgm mgp %d ",(int)age); */
                   6707:     /*   for(j=1; j<=nlstate;j++){ */
                   6708:     /*         printf(" %d ",j); */
                   6709:     /*         for(theta=1; theta <=npar; theta++) */
                   6710:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   6711:     /*         printf("\n "); */
                   6712:     /*   } */
                   6713:     /* } */
                   6714:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6715:     /*   printf("\n gradg %d ",(int)age); */
                   6716:     /*   for(j=1; j<=nlstate;j++){ */
                   6717:     /*         printf("%d ",j); */
                   6718:     /*         for(theta=1; theta <=npar; theta++) */
                   6719:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   6720:     /*         printf("\n "); */
                   6721:     /*   } */
                   6722:     /* } */
1.126     brouard  6723: 
                   6724:     for(i=1;i<=nlstate;i++)
                   6725:       varpl[i][(int)age] =0.;
1.209     brouard  6726:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  6727:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6728:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6729:     }else{
1.268     brouard  6730:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6731:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6732:     }
1.126     brouard  6733:     for(i=1;i<=nlstate;i++)
                   6734:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   6735: 
                   6736:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  6737:     if(nresult >=1)
                   6738:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  6739:     for(i=1; i<=nlstate;i++){
1.126     brouard  6740:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  6741:       /* for(j=1;j<=nlstate;j++) */
                   6742:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   6743:     }
1.126     brouard  6744:     fprintf(ficresvpl,"\n");
                   6745:     free_vector(gp,1,nlstate);
                   6746:     free_vector(gm,1,nlstate);
1.208     brouard  6747:     free_matrix(mgm,1,npar,1,nlstate);
                   6748:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  6749:     free_matrix(gradg,1,npar,1,nlstate);
                   6750:     free_matrix(trgradg,1,nlstate,1,npar);
                   6751:   } /* End age */
                   6752: 
                   6753:   free_vector(xp,1,npar);
                   6754:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  6755:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   6756: 
                   6757: }
                   6758: 
                   6759: 
                   6760: /************ Variance of backprevalence limit ******************/
1.269     brouard  6761:  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  6762: {
                   6763:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   6764:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   6765: 
                   6766:   double **dnewmpar,**doldm;
                   6767:   int i, j, nhstepm, hstepm;
                   6768:   double *xp;
                   6769:   double *gp, *gm;
                   6770:   double **gradg, **trgradg;
                   6771:   double **mgm, **mgp;
                   6772:   double age,agelim;
                   6773:   int theta;
                   6774:   
                   6775:   pstamp(ficresvbl);
                   6776:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   6777:   fprintf(ficresvbl,"# Age ");
                   6778:   if(nresult >=1)
                   6779:     fprintf(ficresvbl," Result# ");
                   6780:   for(i=1; i<=nlstate;i++)
                   6781:       fprintf(ficresvbl," %1d-%1d",i,i);
                   6782:   fprintf(ficresvbl,"\n");
                   6783: 
                   6784:   xp=vector(1,npar);
                   6785:   dnewmpar=matrix(1,nlstate,1,npar);
                   6786:   doldm=matrix(1,nlstate,1,nlstate);
                   6787:   
                   6788:   hstepm=1*YEARM; /* Every year of age */
                   6789:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   6790:   agelim = AGEINF;
                   6791:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   6792:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6793:     if (stepm >= YEARM) hstepm=1;
                   6794:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6795:     gradg=matrix(1,npar,1,nlstate);
                   6796:     mgp=matrix(1,npar,1,nlstate);
                   6797:     mgm=matrix(1,npar,1,nlstate);
                   6798:     gp=vector(1,nlstate);
                   6799:     gm=vector(1,nlstate);
                   6800: 
                   6801:     for(theta=1; theta <=npar; theta++){
                   6802:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   6803:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6804:       }
                   6805:       if(mobilavproj > 0 )
                   6806:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6807:       else
                   6808:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6809:       for(i=1;i<=nlstate;i++){
                   6810:        gp[i] = bprlim[i][i];
                   6811:        mgp[theta][i] = bprlim[i][i];
                   6812:       }
                   6813:      for(i=1; i<=npar; i++) /* Computes gradient */
                   6814:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   6815:        if(mobilavproj > 0 )
                   6816:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6817:        else
                   6818:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6819:       for(i=1;i<=nlstate;i++){
                   6820:        gm[i] = bprlim[i][i];
                   6821:        mgm[theta][i] = bprlim[i][i];
                   6822:       }
                   6823:       for(i=1;i<=nlstate;i++)
                   6824:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   6825:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   6826:     } /* End theta */
                   6827: 
                   6828:     trgradg =matrix(1,nlstate,1,npar);
                   6829: 
                   6830:     for(j=1; j<=nlstate;j++)
                   6831:       for(theta=1; theta <=npar; theta++)
                   6832:        trgradg[j][theta]=gradg[theta][j];
                   6833:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6834:     /*   printf("\nmgm mgp %d ",(int)age); */
                   6835:     /*   for(j=1; j<=nlstate;j++){ */
                   6836:     /*         printf(" %d ",j); */
                   6837:     /*         for(theta=1; theta <=npar; theta++) */
                   6838:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   6839:     /*         printf("\n "); */
                   6840:     /*   } */
                   6841:     /* } */
                   6842:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6843:     /*   printf("\n gradg %d ",(int)age); */
                   6844:     /*   for(j=1; j<=nlstate;j++){ */
                   6845:     /*         printf("%d ",j); */
                   6846:     /*         for(theta=1; theta <=npar; theta++) */
                   6847:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   6848:     /*         printf("\n "); */
                   6849:     /*   } */
                   6850:     /* } */
                   6851: 
                   6852:     for(i=1;i<=nlstate;i++)
                   6853:       varbpl[i][(int)age] =0.;
                   6854:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   6855:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6856:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   6857:     }else{
                   6858:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6859:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   6860:     }
                   6861:     for(i=1;i<=nlstate;i++)
                   6862:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   6863: 
                   6864:     fprintf(ficresvbl,"%.0f ",age );
                   6865:     if(nresult >=1)
                   6866:       fprintf(ficresvbl,"%d ",nres );
                   6867:     for(i=1; i<=nlstate;i++)
                   6868:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   6869:     fprintf(ficresvbl,"\n");
                   6870:     free_vector(gp,1,nlstate);
                   6871:     free_vector(gm,1,nlstate);
                   6872:     free_matrix(mgm,1,npar,1,nlstate);
                   6873:     free_matrix(mgp,1,npar,1,nlstate);
                   6874:     free_matrix(gradg,1,npar,1,nlstate);
                   6875:     free_matrix(trgradg,1,nlstate,1,npar);
                   6876:   } /* End age */
                   6877: 
                   6878:   free_vector(xp,1,npar);
                   6879:   free_matrix(doldm,1,nlstate,1,npar);
                   6880:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  6881: 
                   6882: }
                   6883: 
                   6884: /************ Variance of one-step probabilities  ******************/
                   6885: 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  6886:  {
                   6887:    int i, j=0,  k1, l1, tj;
                   6888:    int k2, l2, j1,  z1;
                   6889:    int k=0, l;
                   6890:    int first=1, first1, first2;
1.326     brouard  6891:    int nres=0; /* New */
1.222     brouard  6892:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   6893:    double **dnewm,**doldm;
                   6894:    double *xp;
                   6895:    double *gp, *gm;
                   6896:    double **gradg, **trgradg;
                   6897:    double **mu;
                   6898:    double age, cov[NCOVMAX+1];
                   6899:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   6900:    int theta;
                   6901:    char fileresprob[FILENAMELENGTH];
                   6902:    char fileresprobcov[FILENAMELENGTH];
                   6903:    char fileresprobcor[FILENAMELENGTH];
                   6904:    double ***varpij;
                   6905: 
                   6906:    strcpy(fileresprob,"PROB_"); 
                   6907:    strcat(fileresprob,fileres);
                   6908:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   6909:      printf("Problem with resultfile: %s\n", fileresprob);
                   6910:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   6911:    }
                   6912:    strcpy(fileresprobcov,"PROBCOV_"); 
                   6913:    strcat(fileresprobcov,fileresu);
                   6914:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   6915:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   6916:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   6917:    }
                   6918:    strcpy(fileresprobcor,"PROBCOR_"); 
                   6919:    strcat(fileresprobcor,fileresu);
                   6920:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   6921:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   6922:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   6923:    }
                   6924:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   6925:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   6926:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   6927:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   6928:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   6929:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   6930:    pstamp(ficresprob);
                   6931:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   6932:    fprintf(ficresprob,"# Age");
                   6933:    pstamp(ficresprobcov);
                   6934:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   6935:    fprintf(ficresprobcov,"# Age");
                   6936:    pstamp(ficresprobcor);
                   6937:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   6938:    fprintf(ficresprobcor,"# Age");
1.126     brouard  6939: 
                   6940: 
1.222     brouard  6941:    for(i=1; i<=nlstate;i++)
                   6942:      for(j=1; j<=(nlstate+ndeath);j++){
                   6943:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   6944:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   6945:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   6946:      }  
                   6947:    /* fprintf(ficresprob,"\n");
                   6948:       fprintf(ficresprobcov,"\n");
                   6949:       fprintf(ficresprobcor,"\n");
                   6950:    */
                   6951:    xp=vector(1,npar);
                   6952:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   6953:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   6954:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   6955:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   6956:    first=1;
                   6957:    fprintf(ficgp,"\n# Routine varprob");
                   6958:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   6959:    fprintf(fichtm,"\n");
                   6960: 
1.288     brouard  6961:    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  6962:    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);
                   6963:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  6964: and drawn. It helps understanding how is the covariance between two incidences.\
                   6965:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  6966:    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  6967: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   6968: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   6969: standard deviations wide on each axis. <br>\
                   6970:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   6971:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   6972: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   6973: 
1.222     brouard  6974:    cov[1]=1;
                   6975:    /* tj=cptcoveff; */
1.225     brouard  6976:    tj = (int) pow(2,cptcoveff);
1.222     brouard  6977:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   6978:    j1=0;
1.224     brouard  6979:    for(j1=1; j1<=tj;j1++){  /* For each valid combination of covariates or only once*/
1.326     brouard  6980:      for(nres=1;nres <=1; nres++){ /* For each resultline */
                   6981:      /* for(nres=1;nres <=nresult; nres++){ /\* For each resultline *\/ */
1.222     brouard  6982:      if  (cptcovn>0) {
                   6983:        fprintf(ficresprob, "\n#********** Variable "); 
1.330     brouard  6984:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,Tvaraff[z1])]);
1.222     brouard  6985:        fprintf(ficresprob, "**********\n#\n");
                   6986:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.330     brouard  6987:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,Tvaraff[z1])]);
1.222     brouard  6988:        fprintf(ficresprobcov, "**********\n#\n");
1.220     brouard  6989:                        
1.222     brouard  6990:        fprintf(ficgp, "\n#********** Variable "); 
1.330     brouard  6991:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,Tvaraff[z1])]);
1.222     brouard  6992:        fprintf(ficgp, "**********\n#\n");
1.220     brouard  6993:                        
                   6994:                        
1.222     brouard  6995:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.319     brouard  6996:        /* for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]); */
1.330     brouard  6997:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtmcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,Tvaraff[z1])]);
1.222     brouard  6998:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  6999:                        
1.222     brouard  7000:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.330     brouard  7001:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,Tvaraff[z1])]);
1.222     brouard  7002:        fprintf(ficresprobcor, "**********\n#");    
                   7003:        if(invalidvarcomb[j1]){
                   7004:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   7005:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   7006:         continue;
                   7007:        }
                   7008:      }
                   7009:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   7010:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7011:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   7012:      gm=vector(1,(nlstate)*(nlstate+ndeath));
                   7013:      for (age=bage; age<=fage; age ++){ 
                   7014:        cov[2]=age;
                   7015:        if(nagesqr==1)
                   7016:         cov[3]= age*age;
1.326     brouard  7017:        /* for (k=1; k<=cptcovn;k++) { */
                   7018:        /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)]; */
                   7019:        for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   7020:         /* Here comes the value of the covariate 'j1' after renumbering k with single dummy covariates */
1.330     brouard  7021:         cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(j1,TvarsD[k])];
1.222     brouard  7022:         /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
                   7023:                                                                    * 1  1 1 1 1
                   7024:                                                                    * 2  2 1 1 1
                   7025:                                                                    * 3  1 2 1 1
                   7026:                                                                    */
                   7027:         /* nbcode[1][1]=0 nbcode[1][2]=1;*/
                   7028:        }
1.319     brouard  7029:        /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   7030:        /* ) p nbcode[Tvar[Tage[k]]][(1 & (ij-1) >> (k-1))+1] */
                   7031:        /*for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.326     brouard  7032:        for (k=1; k<=cptcovage;k++){  /* For product with age */
                   7033:         if(Dummy[Tage[k]]==2){ /* dummy with age */
1.330     brouard  7034:           cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(j1,Tvar[Tage[k]])]*cov[2];
1.326     brouard  7035:           /* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   7036:         } else if(Dummy[Tage[k]]==3){ /* quantitative with age */
1.327     brouard  7037:           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]);
                   7038:           exit(1);
                   7039:             /* cov[2+nagesqr+Tage[k]]=meanq[k]/idq[k]*cov[2];/\* Using the mean of quantitative variable Tvar[Tage[k]] /\* Tqresult[nres][k]; *\/ */
1.326     brouard  7040:           /* cov[++k1]=Tqresult[nres][k];  */
                   7041:         }
                   7042:         /* cov[2+Tage[k]+nagesqr]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   7043:        }
                   7044:        for (k=1; k<=cptcovprod;k++){/* For product without age */
1.329     brouard  7045:         if(Dummy[Tvard[k][1]]==0){
                   7046:           if(Dummy[Tvard[k][2]]==0){
1.330     brouard  7047:             cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(j1,Tvard[k][2])];
1.326     brouard  7048:             /* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; */
                   7049:           }else{ /* Should we use the mean of the quantitative variables? */
1.330     brouard  7050:             cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,Tvard[k][1])] * Tqresult[nres][k];
1.326     brouard  7051:             /* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; */
                   7052:           }
                   7053:         }else{
1.329     brouard  7054:           if(Dummy[Tvard[k][2]]==0){
1.330     brouard  7055:             cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(j1,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]];
1.326     brouard  7056:             /* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; */
                   7057:           }else{
                   7058:             cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   7059:             /* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   7060:           }
                   7061:         }
                   7062:         /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
                   7063:        }                       
                   7064: /* For each age and combination of dummy covariates we slightly move the parameters of delti in order to get the gradient*/                    
1.222     brouard  7065:        for(theta=1; theta <=npar; theta++){
                   7066:         for(i=1; i<=npar; i++)
                   7067:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  7068:                                
1.222     brouard  7069:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  7070:                                
1.222     brouard  7071:         k=0;
                   7072:         for(i=1; i<= (nlstate); i++){
                   7073:           for(j=1; j<=(nlstate+ndeath);j++){
                   7074:             k=k+1;
                   7075:             gp[k]=pmmij[i][j];
                   7076:           }
                   7077:         }
1.220     brouard  7078:                                
1.222     brouard  7079:         for(i=1; i<=npar; i++)
                   7080:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  7081:                                
1.222     brouard  7082:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   7083:         k=0;
                   7084:         for(i=1; i<=(nlstate); i++){
                   7085:           for(j=1; j<=(nlstate+ndeath);j++){
                   7086:             k=k+1;
                   7087:             gm[k]=pmmij[i][j];
                   7088:           }
                   7089:         }
1.220     brouard  7090:                                
1.222     brouard  7091:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   7092:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   7093:        }
1.126     brouard  7094: 
1.222     brouard  7095:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   7096:         for(theta=1; theta <=npar; theta++)
                   7097:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  7098:                        
1.222     brouard  7099:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   7100:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  7101:                        
1.222     brouard  7102:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  7103:                        
1.222     brouard  7104:        k=0;
                   7105:        for(i=1; i<=(nlstate); i++){
                   7106:         for(j=1; j<=(nlstate+ndeath);j++){
                   7107:           k=k+1;
                   7108:           mu[k][(int) age]=pmmij[i][j];
                   7109:         }
                   7110:        }
                   7111:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   7112:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   7113:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  7114:                        
1.222     brouard  7115:        /*printf("\n%d ",(int)age);
                   7116:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7117:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7118:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7119:         }*/
1.220     brouard  7120:                        
1.222     brouard  7121:        fprintf(ficresprob,"\n%d ",(int)age);
                   7122:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   7123:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  7124:                        
1.222     brouard  7125:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   7126:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   7127:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7128:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   7129:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   7130:        }
                   7131:        i=0;
                   7132:        for (k=1; k<=(nlstate);k++){
                   7133:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   7134:           i++;
                   7135:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   7136:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   7137:           for (j=1; j<=i;j++){
                   7138:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   7139:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   7140:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   7141:           }
                   7142:         }
                   7143:        }/* end of loop for state */
                   7144:      } /* end of loop for age */
                   7145:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7146:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7147:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7148:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7149:     
                   7150:      /* Confidence intervalle of pij  */
                   7151:      /*
                   7152:        fprintf(ficgp,"\nunset parametric;unset label");
                   7153:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   7154:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   7155:        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);
                   7156:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   7157:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   7158:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   7159:      */
                   7160:                
                   7161:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   7162:      first1=1;first2=2;
                   7163:      for (k2=1; k2<=(nlstate);k2++){
                   7164:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   7165:         if(l2==k2) continue;
                   7166:         j=(k2-1)*(nlstate+ndeath)+l2;
                   7167:         for (k1=1; k1<=(nlstate);k1++){
                   7168:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   7169:             if(l1==k1) continue;
                   7170:             i=(k1-1)*(nlstate+ndeath)+l1;
                   7171:             if(i<=j) continue;
                   7172:             for (age=bage; age<=fage; age ++){ 
                   7173:               if ((int)age %5==0){
                   7174:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   7175:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7176:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7177:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   7178:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   7179:                 c12=cv12/sqrt(v1*v2);
                   7180:                 /* Computing eigen value of matrix of covariance */
                   7181:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7182:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7183:                 if ((lc2 <0) || (lc1 <0) ){
                   7184:                   if(first2==1){
                   7185:                     first1=0;
                   7186:                     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);
                   7187:                   }
                   7188:                   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);
                   7189:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   7190:                   /* lc2=fabs(lc2); */
                   7191:                 }
1.220     brouard  7192:                                                                
1.222     brouard  7193:                 /* Eigen vectors */
1.280     brouard  7194:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   7195:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7196:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7197:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   7198:                 }else
                   7199:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  7200:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   7201:                 v21=(lc1-v1)/cv12*v11;
                   7202:                 v12=-v21;
                   7203:                 v22=v11;
                   7204:                 tnalp=v21/v11;
                   7205:                 if(first1==1){
                   7206:                   first1=0;
                   7207:                   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);
                   7208:                 }
                   7209:                 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);
                   7210:                 /*printf(fignu*/
                   7211:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   7212:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   7213:                 if(first==1){
                   7214:                   first=0;
                   7215:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   7216:                   fprintf(ficgp,"\nset parametric;unset label");
                   7217:                   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);
                   7218:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  7219:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  7220:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  7221: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  7222:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   7223:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7224:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7225:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   7226:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7227:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7228:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7229:                   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  7230:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   7231:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  7232:                 }else{
                   7233:                   first=0;
                   7234:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   7235:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7236:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7237:                   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  7238:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   7239:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  7240:                 }/* if first */
                   7241:               } /* age mod 5 */
                   7242:             } /* end loop age */
                   7243:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7244:             first=1;
                   7245:           } /*l12 */
                   7246:         } /* k12 */
                   7247:        } /*l1 */
                   7248:      }/* k1 */
1.326     brouard  7249:    } /* loop on nres */
1.222     brouard  7250:    }  /* loop on combination of covariates j1 */
                   7251:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   7252:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   7253:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7254:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   7255:    free_vector(xp,1,npar);
                   7256:    fclose(ficresprob);
                   7257:    fclose(ficresprobcov);
                   7258:    fclose(ficresprobcor);
                   7259:    fflush(ficgp);
                   7260:    fflush(fichtmcov);
                   7261:  }
1.126     brouard  7262: 
                   7263: 
                   7264: /******************* Printing html file ***********/
1.201     brouard  7265: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  7266:                  int lastpass, int stepm, int weightopt, char model[],\
                   7267:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  7268:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   7269:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   7270:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.237     brouard  7271:   int jj1, k1, i1, cpt, k4, nres;
1.319     brouard  7272:   /* In fact some results are already printed in fichtm which is open */
1.126     brouard  7273:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   7274:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   7275: </ul>");
1.319     brouard  7276: /*    fprintf(fichtm,"<ul><li> model=1+age+%s\n \ */
                   7277: /* </ul>", model); */
1.214     brouard  7278:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   7279:    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",
                   7280:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
                   7281:    fprintf(fichtm,"<li> - Observed 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  7282:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   7283:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  7284:    fprintf(fichtm,"\
                   7285:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  7286:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  7287:    fprintf(fichtm,"\
1.217     brouard  7288:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   7289:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   7290:    fprintf(fichtm,"\
1.288     brouard  7291:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7292:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  7293:    fprintf(fichtm,"\
1.288     brouard  7294:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  7295:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   7296:    fprintf(fichtm,"\
1.211     brouard  7297:  - (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  7298:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7299:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  7300:    if(prevfcast==1){
                   7301:      fprintf(fichtm,"\
                   7302:  - Prevalence projections by age and states:                           \
1.201     brouard  7303:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  7304:    }
1.126     brouard  7305: 
                   7306: 
1.225     brouard  7307:    m=pow(2,cptcoveff);
1.222     brouard  7308:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7309: 
1.317     brouard  7310:    fprintf(fichtm," \n<ul><li><b>Graphs (first order)</b></li><p>");
1.264     brouard  7311: 
                   7312:    jj1=0;
                   7313: 
                   7314:    fprintf(fichtm," \n<ul>");
                   7315:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   7316:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
                   7317:      if(m != 1 && TKresult[nres]!= k1)
                   7318:        continue;
                   7319:      jj1++;
                   7320:      if (cptcovn > 0) {
                   7321:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
                   7322:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7323:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7324:        }
                   7325:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7326:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7327:        }
                   7328:        fprintf(fichtm,"\">");
                   7329:        
                   7330:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   7331:        fprintf(fichtm,"************ Results for covariates");
                   7332:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7333:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7334:        }
                   7335:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7336:         fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7337:        }
                   7338:        if(invalidvarcomb[k1]){
                   7339:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   7340:         continue;
                   7341:        }
                   7342:        fprintf(fichtm,"</a></li>");
                   7343:      } /* cptcovn >0 */
                   7344:    }
1.317     brouard  7345:    fprintf(fichtm," \n</ul>");
1.264     brouard  7346: 
1.222     brouard  7347:    jj1=0;
1.237     brouard  7348: 
                   7349:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.241     brouard  7350:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
1.253     brouard  7351:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7352:        continue;
1.220     brouard  7353: 
1.222     brouard  7354:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7355:      jj1++;
                   7356:      if (cptcovn > 0) {
1.264     brouard  7357:        fprintf(fichtm,"\n<p><a name=\"rescov");
                   7358:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7359:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7360:        }
                   7361:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7362:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7363:        }
                   7364:        fprintf(fichtm,"\"</a>");
                   7365:  
1.222     brouard  7366:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  7367:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.237     brouard  7368:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7369:         printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
                   7370:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   7371:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  7372:        }
1.237     brouard  7373:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7374:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7375:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);fflush(stdout);
                   7376:       }
                   7377:        
1.230     brouard  7378:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.321     brouard  7379:        fprintf(fichtm," (model=%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.222     brouard  7380:        if(invalidvarcomb[k1]){
                   7381:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   7382:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   7383:         continue;
                   7384:        }
                   7385:      }
                   7386:      /* aij, bij */
1.259     brouard  7387:      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  7388: <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  7389:      /* Pij */
1.241     brouard  7390:      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> \
                   7391: <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  7392:      /* Quasi-incidences */
                   7393:      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  7394:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  7395:  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  7396: 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> \
                   7397: <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  7398:      /* Survival functions (period) in state j */
                   7399:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  7400:        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);
                   7401:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   7402:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.222     brouard  7403:      }
                   7404:      /* State specific survival functions (period) */
                   7405:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  7406:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
                   7407:  And probability to be observed in various states (up to %d) being in state %d at different ages.      \
1.329     brouard  7408:  <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);
                   7409:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   7410:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.222     brouard  7411:      }
1.288     brouard  7412:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  7413:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  7414:        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);
                   7415:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"P_"),subdirf2(optionfilefiname,"P_"));
                   7416:       fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.222     brouard  7417:      }
1.296     brouard  7418:      if(prevbcast==1){
1.288     brouard  7419:        /* Backward prevalence in each health state */
1.222     brouard  7420:        for(cpt=1; cpt<=nlstate;cpt++){
1.264     brouard  7421:         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  7422: <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  7423:        }
1.217     brouard  7424:      }
1.222     brouard  7425:      if(prevfcast==1){
1.288     brouard  7426:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  7427:        for(cpt=1; cpt<=nlstate;cpt++){
1.314     brouard  7428:         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);
                   7429:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
                   7430:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
                   7431:                 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  7432:        }
                   7433:      }
1.296     brouard  7434:      if(prevbcast==1){
1.268     brouard  7435:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   7436:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  7437:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
                   7438:  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 \
                   7439:  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  7440: 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);
                   7441:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
                   7442:         fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
1.268     brouard  7443:        }
                   7444:      }
1.220     brouard  7445:         
1.222     brouard  7446:      for(cpt=1; cpt<=nlstate;cpt++) {
1.314     brouard  7447:        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);
                   7448:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
                   7449:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
1.222     brouard  7450:      }
                   7451:      /* } /\* end i1 *\/ */
                   7452:    }/* End k1 */
                   7453:    fprintf(fichtm,"</ul>");
1.126     brouard  7454: 
1.222     brouard  7455:    fprintf(fichtm,"\
1.126     brouard  7456: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  7457:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  7458:  - 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  7459: But because parameters are usually highly correlated (a higher incidence of disability \
                   7460: and a higher incidence of recovery can give very close observed transition) it might \
                   7461: be very useful to look not only at linear confidence intervals estimated from the \
                   7462: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   7463: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   7464: covariance matrix of the one-step probabilities. \
                   7465: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  7466: 
1.222     brouard  7467:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   7468:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   7469:    fprintf(fichtm,"\
1.126     brouard  7470:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7471:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  7472: 
1.222     brouard  7473:    fprintf(fichtm,"\
1.126     brouard  7474:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7475:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   7476:    fprintf(fichtm,"\
1.126     brouard  7477:  - 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): \
                   7478:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7479:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  7480:    fprintf(fichtm,"\
1.126     brouard  7481:  - (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): \
                   7482:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7483:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  7484:    fprintf(fichtm,"\
1.288     brouard  7485:  - 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  7486:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   7487:    fprintf(fichtm,"\
1.128     brouard  7488:  - 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  7489:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   7490:    fprintf(fichtm,"\
1.288     brouard  7491:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  7492:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  7493: 
                   7494: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   7495: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   7496: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   7497: /*     <br>",fileres,fileres,fileres,fileres); */
                   7498: /*  else  */
                   7499: /*    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  7500:    fflush(fichtm);
1.126     brouard  7501: 
1.225     brouard  7502:    m=pow(2,cptcoveff);
1.222     brouard  7503:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7504: 
1.317     brouard  7505:    fprintf(fichtm," <ul><li><b>Graphs (second order)</b></li><p>");
                   7506: 
                   7507:   jj1=0;
                   7508: 
                   7509:    fprintf(fichtm," \n<ul>");
                   7510:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   7511:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
                   7512:      if(m != 1 && TKresult[nres]!= k1)
                   7513:        continue;
                   7514:      jj1++;
                   7515:      if (cptcovn > 0) {
                   7516:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescovsecond");
                   7517:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7518:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7519:        }
                   7520:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7521:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7522:        }
                   7523:        fprintf(fichtm,"\">");
                   7524:        
                   7525:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   7526:        fprintf(fichtm,"************ Results for covariates");
                   7527:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7528:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7529:        }
                   7530:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7531:         fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7532:        }
                   7533:        if(invalidvarcomb[k1]){
                   7534:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   7535:         continue;
                   7536:        }
                   7537:        fprintf(fichtm,"</a></li>");
                   7538:      } /* cptcovn >0 */
                   7539:    }
                   7540:    fprintf(fichtm," \n</ul>");
                   7541: 
1.222     brouard  7542:    jj1=0;
1.237     brouard  7543: 
1.241     brouard  7544:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.222     brouard  7545:    for(k1=1; k1<=m;k1++){
1.253     brouard  7546:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7547:        continue;
1.222     brouard  7548:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7549:      jj1++;
1.126     brouard  7550:      if (cptcovn > 0) {
1.317     brouard  7551:        fprintf(fichtm,"\n<p><a name=\"rescovsecond");
                   7552:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7553:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7554:        }
                   7555:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7556:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7557:        }
                   7558:        fprintf(fichtm,"\"</a>");
                   7559:        
1.126     brouard  7560:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.317     brouard  7561:        for (cpt=1; cpt<=cptcoveff;cpt++){  /**< cptcoveff number of variables */
1.237     brouard  7562:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);
1.317     brouard  7563:         printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
1.237     brouard  7564:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
1.317     brouard  7565:        }
1.237     brouard  7566:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7567:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7568:       }
                   7569: 
1.321     brouard  7570:        fprintf(fichtm," (model=%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.220     brouard  7571: 
1.222     brouard  7572:        if(invalidvarcomb[k1]){
                   7573:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   7574:         continue;
                   7575:        }
1.126     brouard  7576:      }
                   7577:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  7578:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.314     brouard  7579: 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);
                   7580:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   7581:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
1.126     brouard  7582:      }
                   7583:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.314     brouard  7584: health expectancies in each live states (1 to %d). If popbased=1 the smooth (due to the model) \
1.128     brouard  7585: true period expectancies (those weighted with period prevalences are also\
                   7586:  drawn in addition to the population based expectancies computed using\
1.314     brouard  7587:  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);
                   7588:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
                   7589:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  7590:      /* } /\* end i1 *\/ */
                   7591:    }/* End k1 */
1.241     brouard  7592:   }/* End nres */
1.222     brouard  7593:    fprintf(fichtm,"</ul>");
                   7594:    fflush(fichtm);
1.126     brouard  7595: }
                   7596: 
                   7597: /******************* Gnuplot file **************/
1.296     brouard  7598: 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  7599: 
                   7600:   char dirfileres[132],optfileres[132];
1.264     brouard  7601:   char gplotcondition[132], gplotlabel[132];
1.237     brouard  7602:   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  7603:   int lv=0, vlv=0, kl=0;
1.130     brouard  7604:   int ng=0;
1.201     brouard  7605:   int vpopbased;
1.223     brouard  7606:   int ioffset; /* variable offset for columns */
1.270     brouard  7607:   int iyearc=1; /* variable column for year of projection  */
                   7608:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  7609:   int nres=0; /* Index of resultline */
1.266     brouard  7610:   int istart=1; /* For starting graphs in projections */
1.219     brouard  7611: 
1.126     brouard  7612: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   7613: /*     printf("Problem with file %s",optionfilegnuplot); */
                   7614: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   7615: /*   } */
                   7616: 
                   7617:   /*#ifdef windows */
                   7618:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  7619:   /*#endif */
1.225     brouard  7620:   m=pow(2,cptcoveff);
1.126     brouard  7621: 
1.274     brouard  7622:   /* diagram of the model */
                   7623:   fprintf(ficgp,"\n#Diagram of the model \n");
                   7624:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   7625:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   7626:   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);
                   7627: 
                   7628:   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);
                   7629:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   7630:   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);
                   7631:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   7632:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   7633:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   7634:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   7635: 
1.202     brouard  7636:   /* Contribution to likelihood */
                   7637:   /* Plot the probability implied in the likelihood */
1.223     brouard  7638:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   7639:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   7640:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   7641:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  7642: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  7643:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   7644: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  7645:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   7646:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   7647:   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));
                   7648:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   7649:   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));
                   7650:   for (i=1; i<= nlstate ; i ++) {
                   7651:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   7652:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   7653:     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);
                   7654:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   7655:       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);
                   7656:     }
                   7657:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   7658:   }
                   7659:   /* 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 */               
                   7660:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   7661:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   7662:   fprintf(ficgp,"\nset out;unset log\n");
                   7663:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  7664: 
1.126     brouard  7665:   strcpy(dirfileres,optionfilefiname);
                   7666:   strcpy(optfileres,"vpl");
1.223     brouard  7667:   /* 1eme*/
1.238     brouard  7668:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
                   7669:     for (k1=1; k1<= m ; k1 ++){ /* For each valid combination of covariate */
1.236     brouard  7670:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.238     brouard  7671:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.253     brouard  7672:        if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7673:          continue;
                   7674:        /* We are interested in selected combination by the resultline */
1.246     brouard  7675:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  7676:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  7677:        strcpy(gplotlabel,"(");
1.238     brouard  7678:        for (k=1; k<=cptcoveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   7679:          lv= decodtabm(k1,k,cptcoveff); /* Should be the value of the covariate corresponding to k1 combination */
                   7680:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7681:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7682:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7683:          vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
                   7684:          /* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
1.246     brouard  7685:          /* printf(" V%d=%d ",Tvaraff[k],vlv); */
1.238     brouard  7686:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7687:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7688:        }
                   7689:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.246     brouard  7690:          /* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  7691:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7692:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7693:        }
                   7694:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  7695:        /* printf("\n#\n"); */
1.238     brouard  7696:        fprintf(ficgp,"\n#\n");
                   7697:        if(invalidvarcomb[k1]){
1.260     brouard  7698:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  7699:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7700:          continue;
                   7701:        }
1.235     brouard  7702:       
1.241     brouard  7703:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   7704:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  7705:        /* 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  7706:        fprintf(ficgp,"set title \"Alive state %d %s model=%s\" font \"Helvetica,12\"\n",cpt,gplotlabel,model);
1.260     brouard  7707:        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);
                   7708:        /* 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); */
                   7709:       /* k1-1 error should be nres-1*/
1.238     brouard  7710:        for (i=1; i<= nlstate ; i ++) {
                   7711:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7712:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   7713:        }
1.288     brouard  7714:        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  7715:        for (i=1; i<= nlstate ; i ++) {
                   7716:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7717:          else fprintf(ficgp," %%*lf (%%*lf)");
                   7718:        } 
1.260     brouard  7719:        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  7720:        for (i=1; i<= nlstate ; i ++) {
                   7721:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7722:          else fprintf(ficgp," %%*lf (%%*lf)");
                   7723:        }  
1.265     brouard  7724:        /* 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)); */
                   7725:        
                   7726:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   7727:         if(cptcoveff ==0){
1.271     brouard  7728:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  7729:        }else{
                   7730:          kl=0;
                   7731:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   7732:            lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7733:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7734:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7735:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7736:            vlv= nbcode[Tvaraff[k]][lv];
                   7737:            kl++;
                   7738:            /* 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 *\/ */
                   7739:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7740:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7741:            /* ''  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*/
                   7742:            if(k==cptcoveff){
                   7743:              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], \
                   7744:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   7745:            }else{
                   7746:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   7747:              kl++;
                   7748:            }
                   7749:          } /* end covariate */
                   7750:        } /* end if no covariate */
                   7751: 
1.296     brouard  7752:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  7753:          /* 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  7754:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  7755:          if(cptcoveff ==0){
1.245     brouard  7756:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  7757:          }else{
                   7758:            kl=0;
                   7759:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   7760:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7761:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7762:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7763:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7764:              vlv= nbcode[Tvaraff[k]][lv];
1.223     brouard  7765:              kl++;
1.238     brouard  7766:              /* 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 *\/ */
                   7767:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7768:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7769:              /* ''  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*/
                   7770:              if(k==cptcoveff){
1.245     brouard  7771:                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  7772:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  7773:              }else{
                   7774:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   7775:                kl++;
                   7776:              }
                   7777:            } /* end covariate */
                   7778:          } /* end if no covariate */
1.296     brouard  7779:          if(prevbcast == 1){
1.268     brouard  7780:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   7781:            /* k1-1 error should be nres-1*/
                   7782:            for (i=1; i<= nlstate ; i ++) {
                   7783:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7784:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   7785:            }
1.271     brouard  7786:            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  7787:            for (i=1; i<= nlstate ; i ++) {
                   7788:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7789:              else fprintf(ficgp," %%*lf (%%*lf)");
                   7790:            } 
1.276     brouard  7791:            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  7792:            for (i=1; i<= nlstate ; i ++) {
                   7793:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7794:              else fprintf(ficgp," %%*lf (%%*lf)");
                   7795:            } 
1.274     brouard  7796:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  7797:          } /* end if backprojcast */
1.296     brouard  7798:        } /* end if prevbcast */
1.276     brouard  7799:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   7800:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  7801:       } /* nres */
1.201     brouard  7802:     } /* k1 */
                   7803:   } /* cpt */
1.235     brouard  7804: 
                   7805:   
1.126     brouard  7806:   /*2 eme*/
1.238     brouard  7807:   for (k1=1; k1<= m ; k1 ++){  
                   7808:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7809:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7810:        continue;
                   7811:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  7812:       strcpy(gplotlabel,"(");
1.238     brouard  7813:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.225     brouard  7814:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
1.223     brouard  7815:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7816:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7817:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7818:        vlv= nbcode[Tvaraff[k]][lv];
                   7819:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7820:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  7821:       }
1.237     brouard  7822:       /* for(k=1; k <= ncovds; k++){ */
1.236     brouard  7823:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  7824:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.236     brouard  7825:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7826:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7827:       }
1.264     brouard  7828:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  7829:       fprintf(ficgp,"\n#\n");
1.223     brouard  7830:       if(invalidvarcomb[k1]){
                   7831:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7832:        continue;
                   7833:       }
1.219     brouard  7834:                        
1.241     brouard  7835:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  7836:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  7837:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   7838:        if(vpopbased==0){
1.238     brouard  7839:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  7840:        }else
1.238     brouard  7841:          fprintf(ficgp,"\nreplot ");
                   7842:        for (i=1; i<= nlstate+1 ; i ++) {
                   7843:          k=2*i;
1.261     brouard  7844:          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  7845:          for (j=1; j<= nlstate+1 ; j ++) {
                   7846:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7847:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7848:          }   
                   7849:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   7850:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
1.261     brouard  7851:          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  7852:          for (j=1; j<= nlstate+1 ; j ++) {
                   7853:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7854:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7855:          }   
                   7856:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  7857:          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  7858:          for (j=1; j<= nlstate+1 ; j ++) {
                   7859:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7860:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7861:          }   
                   7862:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   7863:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   7864:        } /* state */
                   7865:       } /* vpopbased */
1.264     brouard  7866:       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  7867:     } /* end nres */
                   7868:   } /* k1 end 2 eme*/
                   7869:        
                   7870:        
                   7871:   /*3eme*/
                   7872:   for (k1=1; k1<= m ; k1 ++){
                   7873:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7874:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7875:        continue;
                   7876: 
                   7877:       for (cpt=1; cpt<= nlstate ; cpt ++) {
1.261     brouard  7878:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  7879:        strcpy(gplotlabel,"(");
1.238     brouard  7880:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7881:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7882:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7883:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7884:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7885:          vlv= nbcode[Tvaraff[k]][lv];
                   7886:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7887:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7888:        }
                   7889:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7890:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7891:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7892:        }       
1.264     brouard  7893:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7894:        fprintf(ficgp,"\n#\n");
                   7895:        if(invalidvarcomb[k1]){
                   7896:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7897:          continue;
                   7898:        }
                   7899:                        
                   7900:        /*       k=2+nlstate*(2*cpt-2); */
                   7901:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  7902:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  7903:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  7904:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  7905: 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  7906:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   7907:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   7908:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   7909:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   7910:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   7911:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  7912:                                
1.238     brouard  7913:        */
                   7914:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  7915:          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  7916:          /*    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  7917:                                
1.238     brouard  7918:        } 
1.261     brouard  7919:        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  7920:       }
1.264     brouard  7921:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  7922:     } /* end nres */
                   7923:   } /* end kl 3eme */
1.126     brouard  7924:   
1.223     brouard  7925:   /* 4eme */
1.201     brouard  7926:   /* Survival functions (period) from state i in state j by initial state i */
1.238     brouard  7927:   for (k1=1; k1<=m; k1++){    /* For each covariate and each value */
                   7928:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7929:       if(m != 1 && TKresult[nres]!= k1)
1.223     brouard  7930:        continue;
1.238     brouard  7931:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  7932:        strcpy(gplotlabel,"(");
1.238     brouard  7933:        fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
                   7934:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7935:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7936:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7937:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7938:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7939:          vlv= nbcode[Tvaraff[k]][lv];
                   7940:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7941:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7942:        }
                   7943:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7944:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7945:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7946:        }       
1.264     brouard  7947:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7948:        fprintf(ficgp,"\n#\n");
                   7949:        if(invalidvarcomb[k1]){
                   7950:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7951:          continue;
1.223     brouard  7952:        }
1.238     brouard  7953:       
1.241     brouard  7954:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  7955:        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  7956:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   7957: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   7958:        k=3;
                   7959:        for (i=1; i<= nlstate ; i ++){
                   7960:          if(i==1){
                   7961:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   7962:          }else{
                   7963:            fprintf(ficgp,", '' ");
                   7964:          }
                   7965:          l=(nlstate+ndeath)*(i-1)+1;
                   7966:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   7967:          for (j=2; j<= nlstate+ndeath ; j ++)
                   7968:            fprintf(ficgp,"+$%d",k+l+j-1);
                   7969:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   7970:        } /* nlstate */
1.264     brouard  7971:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  7972:       } /* end cpt state*/ 
                   7973:     } /* end nres */
                   7974:   } /* end covariate k1 */  
                   7975: 
1.220     brouard  7976: /* 5eme */
1.201     brouard  7977:   /* Survival functions (period) from state i in state j by final state j */
1.238     brouard  7978:   for (k1=1; k1<= m ; k1++){ /* For each covariate combination if any */
                   7979:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7980:       if(m != 1 && TKresult[nres]!= k1)
1.227     brouard  7981:        continue;
1.238     brouard  7982:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  7983:        strcpy(gplotlabel,"(");
1.238     brouard  7984:        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);
                   7985:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7986:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7987:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7988:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7989:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7990:          vlv= nbcode[Tvaraff[k]][lv];
                   7991:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7992:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7993:        }
                   7994:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7995:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7996:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7997:        }       
1.264     brouard  7998:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7999:        fprintf(ficgp,"\n#\n");
                   8000:        if(invalidvarcomb[k1]){
                   8001:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8002:          continue;
                   8003:        }
1.227     brouard  8004:       
1.241     brouard  8005:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  8006:        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  8007:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8008: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8009:        k=3;
                   8010:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8011:          if(j==1)
                   8012:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8013:          else
                   8014:            fprintf(ficgp,", '' ");
                   8015:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8016:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   8017:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   8018:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   8019:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   8020:        } /* nlstate */
                   8021:        fprintf(ficgp,", '' ");
                   8022:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   8023:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8024:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8025:          if(j < nlstate)
                   8026:            fprintf(ficgp,"$%d +",k+l);
                   8027:          else
                   8028:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   8029:        }
1.264     brouard  8030:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8031:       } /* end cpt state*/ 
                   8032:     } /* end covariate */  
                   8033:   } /* end nres */
1.227     brouard  8034:   
1.220     brouard  8035: /* 6eme */
1.202     brouard  8036:   /* CV preval stable (period) for each covariate */
1.237     brouard  8037:   for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   8038:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  8039:     if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  8040:       continue;
1.255     brouard  8041:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  8042:       strcpy(gplotlabel,"(");      
1.288     brouard  8043:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.225     brouard  8044:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.227     brouard  8045:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   8046:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8047:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8048:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8049:        vlv= nbcode[Tvaraff[k]][lv];
                   8050:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8051:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  8052:       }
1.237     brouard  8053:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   8054:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  8055:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  8056:       }        
1.264     brouard  8057:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8058:       fprintf(ficgp,"\n#\n");
1.223     brouard  8059:       if(invalidvarcomb[k1]){
1.227     brouard  8060:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8061:        continue;
1.223     brouard  8062:       }
1.227     brouard  8063:       
1.241     brouard  8064:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  8065:       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  8066:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8067: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  8068:       k=3; /* Offset */
1.255     brouard  8069:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  8070:        if(i==1)
                   8071:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8072:        else
                   8073:          fprintf(ficgp,", '' ");
1.255     brouard  8074:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  8075:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8076:        for (j=2; j<= nlstate ; j ++)
                   8077:          fprintf(ficgp,"+$%d",k+l+j-1);
                   8078:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  8079:       } /* nlstate */
1.264     brouard  8080:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  8081:     } /* end cpt state*/ 
                   8082:   } /* end covariate */  
1.227     brouard  8083:   
                   8084:   
1.220     brouard  8085: /* 7eme */
1.296     brouard  8086:   if(prevbcast == 1){
1.288     brouard  8087:     /* CV backward prevalence  for each covariate */
1.237     brouard  8088:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   8089:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  8090:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  8091:        continue;
1.268     brouard  8092:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  8093:        strcpy(gplotlabel,"(");      
1.288     brouard  8094:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.227     brouard  8095:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   8096:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   8097:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8098:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
1.223     brouard  8099:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.227     brouard  8100:          vlv= nbcode[Tvaraff[k]][lv];
                   8101:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8102:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.227     brouard  8103:        }
1.237     brouard  8104:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   8105:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  8106:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  8107:        }       
1.264     brouard  8108:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8109:        fprintf(ficgp,"\n#\n");
                   8110:        if(invalidvarcomb[k1]){
                   8111:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8112:          continue;
                   8113:        }
                   8114:        
1.241     brouard  8115:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  8116:        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  8117:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8118: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  8119:        k=3; /* Offset */
1.268     brouard  8120:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  8121:          if(i==1)
                   8122:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   8123:          else
                   8124:            fprintf(ficgp,", '' ");
                   8125:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  8126:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.324     brouard  8127:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   8128:          /* 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  8129:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  8130:          /* for (j=2; j<= nlstate ; j ++) */
                   8131:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   8132:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  8133:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  8134:        } /* nlstate */
1.264     brouard  8135:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  8136:       } /* end cpt state*/ 
                   8137:     } /* end covariate */  
1.296     brouard  8138:   } /* End if prevbcast */
1.218     brouard  8139:   
1.223     brouard  8140:   /* 8eme */
1.218     brouard  8141:   if(prevfcast==1){
1.288     brouard  8142:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  8143:     
1.237     brouard  8144:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   8145:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  8146:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  8147:        continue;
1.211     brouard  8148:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  8149:        strcpy(gplotlabel,"(");      
1.288     brouard  8150:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.227     brouard  8151:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   8152:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   8153:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8154:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8155:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8156:          vlv= nbcode[Tvaraff[k]][lv];
                   8157:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8158:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.227     brouard  8159:        }
1.237     brouard  8160:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   8161:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  8162:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  8163:        }       
1.264     brouard  8164:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8165:        fprintf(ficgp,"\n#\n");
                   8166:        if(invalidvarcomb[k1]){
                   8167:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8168:          continue;
                   8169:        }
                   8170:        
                   8171:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  8172:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  8173:        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  8174:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  8175: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  8176: 
                   8177:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   8178:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8179:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8180:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  8181:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8182:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8183:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8184:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  8185:          if(i==istart){
1.227     brouard  8186:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   8187:          }else{
                   8188:            fprintf(ficgp,",\\\n '' ");
                   8189:          }
                   8190:          if(cptcoveff ==0){ /* No covariate */
                   8191:            ioffset=2; /* Age is in 2 */
                   8192:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8193:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8194:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8195:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8196:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  8197:            if(i==nlstate+1){
1.270     brouard  8198:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  8199:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   8200:              fprintf(ficgp,",\\\n '' ");
                   8201:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  8202:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  8203:                     offyear,                           \
1.268     brouard  8204:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  8205:            }else
1.227     brouard  8206:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   8207:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8208:          }else{ /* more than 2 covariates */
1.270     brouard  8209:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   8210:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8211:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   8212:            iyearc=ioffset-1;
                   8213:            iagec=ioffset;
1.227     brouard  8214:            fprintf(ficgp," u %d:(",ioffset); 
                   8215:            kl=0;
                   8216:            strcpy(gplotcondition,"(");
                   8217:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
                   8218:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   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]; /* Value of the modality of Tvaraff[k] */
                   8223:              kl++;
                   8224:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   8225:              kl++;
                   8226:              if(k <cptcoveff && cptcoveff>1)
                   8227:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   8228:            }
                   8229:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   8230:            /* 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 *\/ */
                   8231:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8232:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8233:            /* ''  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*/
                   8234:            if(i==nlstate+1){
1.270     brouard  8235:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   8236:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  8237:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  8238:              fprintf(ficgp," u %d:(",iagec); 
                   8239:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   8240:                      iyearc, iagec, offyear,                           \
                   8241:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  8242: /*  '' 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  8243:            }else{
                   8244:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   8245:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8246:            }
                   8247:          } /* end if covariate */
                   8248:        } /* nlstate */
1.264     brouard  8249:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  8250:       } /* end cpt state*/
                   8251:     } /* end covariate */
                   8252:   } /* End if prevfcast */
1.227     brouard  8253:   
1.296     brouard  8254:   if(prevbcast==1){
1.268     brouard  8255:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   8256:     
                   8257:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   8258:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8259:       if(m != 1 && TKresult[nres]!= k1)
                   8260:        continue;
                   8261:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   8262:        strcpy(gplotlabel,"(");      
                   8263:        fprintf(ficgp,"\n#\n#\n#Back projection of prevalence to stable (mixed) back prevalence: 'BPROJ_' files, covariatecombination#=%d originstate=%d",k1, cpt);
                   8264:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   8265:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   8266:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8267:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8268:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8269:          vlv= nbcode[Tvaraff[k]][lv];
                   8270:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   8271:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
                   8272:        }
                   8273:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   8274:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   8275:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   8276:        }       
                   8277:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   8278:        fprintf(ficgp,"\n#\n");
                   8279:        if(invalidvarcomb[k1]){
                   8280:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8281:          continue;
                   8282:        }
                   8283:        
                   8284:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   8285:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   8286:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   8287:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   8288: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8289: 
                   8290:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   8291:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8292:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8293:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   8294:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8295:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8296:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8297:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8298:          if(i==istart){
                   8299:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   8300:          }else{
                   8301:            fprintf(ficgp,",\\\n '' ");
                   8302:          }
                   8303:          if(cptcoveff ==0){ /* No covariate */
                   8304:            ioffset=2; /* Age is in 2 */
                   8305:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8306:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8307:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8308:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8309:            fprintf(ficgp," u %d:(", ioffset); 
                   8310:            if(i==nlstate+1){
1.270     brouard  8311:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  8312:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   8313:              fprintf(ficgp,",\\\n '' ");
                   8314:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  8315:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  8316:                     offbyear,                          \
                   8317:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   8318:            }else
                   8319:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   8320:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   8321:          }else{ /* more than 2 covariates */
1.270     brouard  8322:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   8323:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8324:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   8325:            iyearc=ioffset-1;
                   8326:            iagec=ioffset;
1.268     brouard  8327:            fprintf(ficgp," u %d:(",ioffset); 
                   8328:            kl=0;
                   8329:            strcpy(gplotcondition,"(");
                   8330:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
                   8331:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   8332:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8333:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8334:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8335:              vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   8336:              kl++;
                   8337:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   8338:              kl++;
                   8339:              if(k <cptcoveff && cptcoveff>1)
                   8340:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   8341:            }
                   8342:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   8343:            /* 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 *\/ */
                   8344:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8345:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8346:            /* ''  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*/
                   8347:            if(i==nlstate+1){
1.270     brouard  8348:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   8349:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  8350:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  8351:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  8352:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  8353:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   8354:                      iyearc,iagec,offbyear,                            \
                   8355:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  8356: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   8357:            }else{
                   8358:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   8359:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   8360:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   8361:            }
                   8362:          } /* end if covariate */
                   8363:        } /* nlstate */
                   8364:        fprintf(ficgp,"\nset out; unset label;\n");
                   8365:       } /* end cpt state*/
                   8366:     } /* end covariate */
1.296     brouard  8367:   } /* End if prevbcast */
1.268     brouard  8368:   
1.227     brouard  8369:   
1.238     brouard  8370:   /* 9eme writing MLE parameters */
                   8371:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  8372:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  8373:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  8374:     for(k=1; k <=(nlstate+ndeath); k++){
                   8375:       if (k != i) {
1.227     brouard  8376:        fprintf(ficgp,"#   current state %d\n",k);
                   8377:        for(j=1; j <=ncovmodel; j++){
                   8378:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   8379:          jk++; 
                   8380:        }
                   8381:        fprintf(ficgp,"\n");
1.126     brouard  8382:       }
                   8383:     }
1.223     brouard  8384:   }
1.187     brouard  8385:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  8386:   
1.145     brouard  8387:   /*goto avoid;*/
1.238     brouard  8388:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   8389:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  8390:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   8391:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   8392:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   8393:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   8394:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8395:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   8396:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8397:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   8398:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   8399:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8400:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   8401:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   8402:   fprintf(ficgp,"#\n");
1.223     brouard  8403:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  8404:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.237     brouard  8405:     fprintf(ficgp,"#model=%s \n",model);
1.238     brouard  8406:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.264     brouard  8407:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
                   8408:     for(k1=1; k1 <=m; k1++)  /* For each combination of covariate */
1.237     brouard  8409:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.264     brouard  8410:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  8411:        continue;
1.264     brouard  8412:       fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1);
                   8413:       strcpy(gplotlabel,"(");
1.276     brouard  8414:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.264     brouard  8415:       for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   8416:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   8417:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8418:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8419:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8420:        vlv= nbcode[Tvaraff[k]][lv];
                   8421:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   8422:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
                   8423:       }
1.237     brouard  8424:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   8425:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  8426:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  8427:       }        
1.264     brouard  8428:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  8429:       fprintf(ficgp,"\n#\n");
1.264     brouard  8430:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  8431:       fprintf(ficgp,"\nset key outside ");
                   8432:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   8433:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  8434:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   8435:       if (ng==1){
                   8436:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   8437:        fprintf(ficgp,"\nunset log y");
                   8438:       }else if (ng==2){
                   8439:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   8440:        fprintf(ficgp,"\nset log y");
                   8441:       }else if (ng==3){
                   8442:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   8443:        fprintf(ficgp,"\nset log y");
                   8444:       }else
                   8445:        fprintf(ficgp,"\nunset title ");
                   8446:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   8447:       i=1;
                   8448:       for(k2=1; k2<=nlstate; k2++) {
                   8449:        k3=i;
                   8450:        for(k=1; k<=(nlstate+ndeath); k++) {
                   8451:          if (k != k2){
                   8452:            switch( ng) {
                   8453:            case 1:
                   8454:              if(nagesqr==0)
                   8455:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   8456:              else /* nagesqr =1 */
                   8457:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   8458:              break;
                   8459:            case 2: /* ng=2 */
                   8460:              if(nagesqr==0)
                   8461:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   8462:              else /* nagesqr =1 */
                   8463:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   8464:              break;
                   8465:            case 3:
                   8466:              if(nagesqr==0)
                   8467:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   8468:              else /* nagesqr =1 */
                   8469:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   8470:              break;
                   8471:            }
                   8472:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  8473:            ijp=1; /* product no age */
                   8474:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   8475:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  8476:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.329     brouard  8477:              switch(Typevar[j]){
                   8478:              case 1:
                   8479:                if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   8480:                  if(j==Tage[ij]) { /* Product by age  To be looked at!!*//* Bug valgrind */
                   8481:                    if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   8482:                      if(DummyV[j]==0){/* Bug valgrind */
                   8483:                        fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   8484:                      }else{ /* quantitative */
                   8485:                        fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   8486:                        /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8487:                      }
                   8488:                      ij++;
1.268     brouard  8489:                    }
1.237     brouard  8490:                  }
1.329     brouard  8491:                }
                   8492:                break;
                   8493:              case 2:
                   8494:                if(cptcovprod >0){
                   8495:                  if(j==Tprod[ijp]) { /* */ 
                   8496:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   8497:                    if(ijp <=cptcovprod) { /* Product */
                   8498:                      if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   8499:                        if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   8500:                          /* 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)]); */
                   8501:                          fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   8502:                        }else{ /* Vn is dummy and Vm is quanti */
                   8503:                          /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8504:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8505:                        }
                   8506:                      }else{ /* Vn*Vm Vn is quanti */
                   8507:                        if(DummyV[Tvard[ijp][2]]==0){
                   8508:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   8509:                        }else{ /* Both quanti */
                   8510:                          fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8511:                        }
1.268     brouard  8512:                      }
1.329     brouard  8513:                      ijp++;
1.237     brouard  8514:                    }
1.329     brouard  8515:                  } /* end Tprod */
                   8516:                }
                   8517:                break;
                   8518:              case 0:
                   8519:                /* simple covariate */
1.264     brouard  8520:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  8521:                if(Dummy[j]==0){
                   8522:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   8523:                }else{ /* quantitative */
                   8524:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  8525:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  8526:                }
1.329     brouard  8527:               /* end simple */
                   8528:                break;
                   8529:              default:
                   8530:                break;
                   8531:              } /* end switch */
1.237     brouard  8532:            } /* end j */
1.329     brouard  8533:          }else{ /* k=k2 */
                   8534:            if(ng !=1 ){ /* For logit formula of log p11 is more difficult to get */
                   8535:              fprintf(ficgp," (1.");i=i-ncovmodel;
                   8536:            }else
                   8537:              i=i-ncovmodel;
1.223     brouard  8538:          }
1.227     brouard  8539:          
1.223     brouard  8540:          if(ng != 1){
                   8541:            fprintf(ficgp,")/(1");
1.227     brouard  8542:            
1.264     brouard  8543:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  8544:              if(nagesqr==0)
1.264     brouard  8545:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  8546:              else /* nagesqr =1 */
1.264     brouard  8547:                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  8548:               
1.223     brouard  8549:              ij=1;
1.329     brouard  8550:              ijp=1;
                   8551:              /* for(j=3; j <=ncovmodel-nagesqr; j++){ */
                   8552:              for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
                   8553:                switch(Typevar[j]){
                   8554:                case 1:
                   8555:                  if(cptcovage >0){ 
                   8556:                    if(j==Tage[ij]) { /* Bug valgrind */
                   8557:                      if(ij <=cptcovage) { /* Bug valgrind */
                   8558:                        if(DummyV[j]==0){/* Bug valgrind */
                   8559:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]); */
                   8560:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,nbcode[Tvar[j]][codtabm(k1,j)]); */
                   8561:                          fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]);
                   8562:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);; */
                   8563:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8564:                        }else{ /* quantitative */
                   8565:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   8566:                          fprintf(ficgp,"+p%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   8567:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   8568:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8569:                        }
                   8570:                        ij++;
                   8571:                      }
                   8572:                    }
                   8573:                  }
                   8574:                  break;
                   8575:                case 2:
                   8576:                  if(cptcovprod >0){
                   8577:                    if(j==Tprod[ijp]) { /* */ 
                   8578:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   8579:                      if(ijp <=cptcovprod) { /* Product */
                   8580:                        if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   8581:                          if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   8582:                            /* 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)]); */
                   8583:                            fprintf(ficgp,"+p%d*%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   8584:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   8585:                          }else{ /* Vn is dummy and Vm is quanti */
                   8586:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8587:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8588:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8589:                          }
                   8590:                        }else{ /* Vn*Vm Vn is quanti */
                   8591:                          if(DummyV[Tvard[ijp][2]]==0){
                   8592:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   8593:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   8594:                          }else{ /* Both quanti */
                   8595:                            fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8596:                            /* fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8597:                          } 
                   8598:                        }
                   8599:                        ijp++;
                   8600:                      }
                   8601:                    } /* end Tprod */
                   8602:                  } /* end if */
                   8603:                  break;
                   8604:                case 0: 
                   8605:                  /* simple covariate */
                   8606:                  /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
                   8607:                  if(Dummy[j]==0){
                   8608:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   8609:                    fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]); /*  */
                   8610:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   8611:                  }else{ /* quantitative */
                   8612:                    fprintf(ficgp,"+p%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* */
                   8613:                    /* fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* *\/ */
                   8614:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8615:                  }
                   8616:                  /* end simple */
                   8617:                  /* fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);/\* Valgrind bug nbcode *\/ */
                   8618:                  break;
                   8619:                default:
                   8620:                  break;
                   8621:                } /* end switch */
1.223     brouard  8622:              }
                   8623:              fprintf(ficgp,")");
                   8624:            }
                   8625:            fprintf(ficgp,")");
                   8626:            if(ng ==2)
1.276     brouard  8627:              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  8628:            else /* ng= 3 */
1.276     brouard  8629:              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  8630:           }else{ /* end ng <> 1 */
1.223     brouard  8631:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  8632:              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  8633:          }
                   8634:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   8635:            fprintf(ficgp,",");
                   8636:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   8637:            fprintf(ficgp,",");
                   8638:          i=i+ncovmodel;
                   8639:        } /* end k */
                   8640:       } /* end k2 */
1.276     brouard  8641:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   8642:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.264     brouard  8643:     } /* end k1 */
1.223     brouard  8644:   } /* end ng */
                   8645:   /* avoid: */
                   8646:   fflush(ficgp); 
1.126     brouard  8647: }  /* end gnuplot */
                   8648: 
                   8649: 
                   8650: /*************** Moving average **************/
1.219     brouard  8651: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  8652:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  8653:    
1.222     brouard  8654:    int i, cpt, cptcod;
                   8655:    int modcovmax =1;
                   8656:    int mobilavrange, mob;
                   8657:    int iage=0;
1.288     brouard  8658:    int firstA1=0, firstA2=0;
1.222     brouard  8659: 
1.266     brouard  8660:    double sum=0., sumr=0.;
1.222     brouard  8661:    double age;
1.266     brouard  8662:    double *sumnewp, *sumnewm, *sumnewmr;
                   8663:    double *agemingood, *agemaxgood; 
                   8664:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  8665:   
                   8666:   
1.278     brouard  8667:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   8668:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  8669: 
                   8670:    sumnewp = vector(1,ncovcombmax);
                   8671:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  8672:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  8673:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  8674:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  8675:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  8676:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  8677: 
                   8678:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  8679:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  8680:      sumnewp[cptcod]=0.;
1.266     brouard  8681:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   8682:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  8683:    }
                   8684:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   8685:   
1.266     brouard  8686:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   8687:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  8688:      else mobilavrange=mobilav;
                   8689:      for (age=bage; age<=fage; age++)
                   8690:        for (i=1; i<=nlstate;i++)
                   8691:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   8692:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8693:      /* We keep the original values on the extreme ages bage, fage and for 
                   8694:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   8695:        we use a 5 terms etc. until the borders are no more concerned. 
                   8696:      */ 
                   8697:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   8698:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  8699:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   8700:           sumnewm[cptcod]=0.;
                   8701:           for (i=1; i<=nlstate;i++){
1.222     brouard  8702:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   8703:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   8704:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   8705:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   8706:             }
                   8707:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  8708:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8709:           } /* end i */
                   8710:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   8711:         } /* end cptcod */
1.222     brouard  8712:        }/* end age */
                   8713:      }/* end mob */
1.266     brouard  8714:    }else{
                   8715:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  8716:      return -1;
1.266     brouard  8717:    }
                   8718: 
                   8719:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  8720:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   8721:      if(invalidvarcomb[cptcod]){
                   8722:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   8723:        continue;
                   8724:      }
1.219     brouard  8725: 
1.266     brouard  8726:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   8727:        sumnewm[cptcod]=0.;
                   8728:        sumnewmr[cptcod]=0.;
                   8729:        for (i=1; i<=nlstate;i++){
                   8730:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8731:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8732:        }
                   8733:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8734:         agemingoodr[cptcod]=age;
                   8735:        }
                   8736:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8737:           agemingood[cptcod]=age;
                   8738:        }
                   8739:      } /* age */
                   8740:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  8741:        sumnewm[cptcod]=0.;
1.266     brouard  8742:        sumnewmr[cptcod]=0.;
1.222     brouard  8743:        for (i=1; i<=nlstate;i++){
                   8744:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  8745:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8746:        }
                   8747:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8748:         agemaxgoodr[cptcod]=age;
1.222     brouard  8749:        }
                   8750:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  8751:         agemaxgood[cptcod]=age;
                   8752:        }
                   8753:      } /* age */
                   8754:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   8755:      /* but they will change */
1.288     brouard  8756:      firstA1=0;firstA2=0;
1.266     brouard  8757:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   8758:        sumnewm[cptcod]=0.;
                   8759:        sumnewmr[cptcod]=0.;
                   8760:        for (i=1; i<=nlstate;i++){
                   8761:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8762:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8763:        }
                   8764:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   8765:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8766:           agemaxgoodr[cptcod]=age;  /* age min */
                   8767:           for (i=1; i<=nlstate;i++)
                   8768:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8769:         }else{ /* bad we change the value with the values of good ages */
                   8770:           for (i=1; i<=nlstate;i++){
                   8771:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   8772:           } /* i */
                   8773:         } /* end bad */
                   8774:        }else{
                   8775:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8776:           agemaxgood[cptcod]=age;
                   8777:         }else{ /* bad we change the value with the values of good ages */
                   8778:           for (i=1; i<=nlstate;i++){
                   8779:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   8780:           } /* i */
                   8781:         } /* end bad */
                   8782:        }/* end else */
                   8783:        sum=0.;sumr=0.;
                   8784:        for (i=1; i<=nlstate;i++){
                   8785:         sum+=mobaverage[(int)age][i][cptcod];
                   8786:         sumr+=probs[(int)age][i][cptcod];
                   8787:        }
                   8788:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  8789:         if(!firstA1){
                   8790:           firstA1=1;
                   8791:           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);
                   8792:         }
                   8793:         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  8794:        } /* end bad */
                   8795:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   8796:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  8797:         if(!firstA2){
                   8798:           firstA2=1;
                   8799:           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);
                   8800:         }
                   8801:         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  8802:        } /* end bad */
                   8803:      }/* age */
1.266     brouard  8804: 
                   8805:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  8806:        sumnewm[cptcod]=0.;
1.266     brouard  8807:        sumnewmr[cptcod]=0.;
1.222     brouard  8808:        for (i=1; i<=nlstate;i++){
                   8809:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  8810:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8811:        } 
                   8812:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   8813:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   8814:           agemingoodr[cptcod]=age;
                   8815:           for (i=1; i<=nlstate;i++)
                   8816:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8817:         }else{ /* bad we change the value with the values of good ages */
                   8818:           for (i=1; i<=nlstate;i++){
                   8819:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   8820:           } /* i */
                   8821:         } /* end bad */
                   8822:        }else{
                   8823:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8824:           agemingood[cptcod]=age;
                   8825:         }else{ /* bad */
                   8826:           for (i=1; i<=nlstate;i++){
                   8827:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   8828:           } /* i */
                   8829:         } /* end bad */
                   8830:        }/* end else */
                   8831:        sum=0.;sumr=0.;
                   8832:        for (i=1; i<=nlstate;i++){
                   8833:         sum+=mobaverage[(int)age][i][cptcod];
                   8834:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  8835:        }
1.266     brouard  8836:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  8837:         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  8838:        } /* end bad */
                   8839:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   8840:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  8841:         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  8842:        } /* end bad */
                   8843:      }/* age */
1.266     brouard  8844: 
1.222     brouard  8845:                
                   8846:      for (age=bage; age<=fage; age++){
1.235     brouard  8847:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  8848:        sumnewp[cptcod]=0.;
                   8849:        sumnewm[cptcod]=0.;
                   8850:        for (i=1; i<=nlstate;i++){
                   8851:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   8852:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8853:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   8854:        }
                   8855:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   8856:      }
                   8857:      /* printf("\n"); */
                   8858:      /* } */
1.266     brouard  8859: 
1.222     brouard  8860:      /* brutal averaging */
1.266     brouard  8861:      /* for (i=1; i<=nlstate;i++){ */
                   8862:      /*   for (age=1; age<=bage; age++){ */
                   8863:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   8864:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   8865:      /*   }     */
                   8866:      /*   for (age=fage; age<=AGESUP; age++){ */
                   8867:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   8868:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   8869:      /*   } */
                   8870:      /* } /\* end i status *\/ */
                   8871:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   8872:      /*   for (age=1; age<=AGESUP; age++){ */
                   8873:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   8874:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   8875:      /*   } */
                   8876:      /* } */
1.222     brouard  8877:    }/* end cptcod */
1.266     brouard  8878:    free_vector(agemaxgoodr,1, ncovcombmax);
                   8879:    free_vector(agemaxgood,1, ncovcombmax);
                   8880:    free_vector(agemingood,1, ncovcombmax);
                   8881:    free_vector(agemingoodr,1, ncovcombmax);
                   8882:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  8883:    free_vector(sumnewm,1, ncovcombmax);
                   8884:    free_vector(sumnewp,1, ncovcombmax);
                   8885:    return 0;
                   8886:  }/* End movingaverage */
1.218     brouard  8887:  
1.126     brouard  8888: 
1.296     brouard  8889:  
1.126     brouard  8890: /************** Forecasting ******************/
1.296     brouard  8891: /* 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)*/
                   8892: 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){
                   8893:   /* dateintemean, mean date of interviews
                   8894:      dateprojd, year, month, day of starting projection 
                   8895:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  8896:      agemin, agemax range of age
                   8897:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   8898:   */
1.296     brouard  8899:   /* double anprojd, mprojd, jprojd; */
                   8900:   /* double anprojf, mprojf, jprojf; */
1.267     brouard  8901:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  8902:   double agec; /* generic age */
1.296     brouard  8903:   double agelim, ppij, yp,yp1,yp2;
1.126     brouard  8904:   double *popeffectif,*popcount;
                   8905:   double ***p3mat;
1.218     brouard  8906:   /* double ***mobaverage; */
1.126     brouard  8907:   char fileresf[FILENAMELENGTH];
                   8908: 
                   8909:   agelim=AGESUP;
1.211     brouard  8910:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   8911:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   8912:      We still use firstpass and lastpass as another selection.
                   8913:   */
1.214     brouard  8914:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   8915:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  8916:  
1.201     brouard  8917:   strcpy(fileresf,"F_"); 
                   8918:   strcat(fileresf,fileresu);
1.126     brouard  8919:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   8920:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   8921:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   8922:   }
1.235     brouard  8923:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   8924:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  8925: 
1.225     brouard  8926:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  8927: 
                   8928: 
                   8929:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   8930:   if (stepm<=12) stepsize=1;
                   8931:   if(estepm < stepm){
                   8932:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   8933:   }
1.270     brouard  8934:   else{
                   8935:     hstepm=estepm;   
                   8936:   }
                   8937:   if(estepm > stepm){ /* Yes every two year */
                   8938:     stepsize=2;
                   8939:   }
1.296     brouard  8940:   hstepm=hstepm/stepm;
1.126     brouard  8941: 
1.296     brouard  8942:   
                   8943:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   8944:   /*                              fractional in yp1 *\/ */
                   8945:   /* aintmean=yp; */
                   8946:   /* yp2=modf((yp1*12),&yp); */
                   8947:   /* mintmean=yp; */
                   8948:   /* yp1=modf((yp2*30.5),&yp); */
                   8949:   /* jintmean=yp; */
                   8950:   /* if(jintmean==0) jintmean=1; */
                   8951:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  8952: 
1.296     brouard  8953: 
                   8954:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   8955:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   8956:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.227     brouard  8957:   i1=pow(2,cptcoveff);
1.126     brouard  8958:   if (cptcovn < 1){i1=1;}
                   8959:   
1.296     brouard  8960:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  8961:   
                   8962:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  8963:   
1.126     brouard  8964: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  8965:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8966:   for(k=1; k<=i1;k++){
1.253     brouard  8967:     if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  8968:       continue;
1.227     brouard  8969:     if(invalidvarcomb[k]){
                   8970:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   8971:       continue;
                   8972:     }
                   8973:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   8974:     for(j=1;j<=cptcoveff;j++) {
1.330     brouard  8975:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
1.227     brouard  8976:     }
1.235     brouard  8977:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  8978:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.235     brouard  8979:     }
1.227     brouard  8980:     fprintf(ficresf," yearproj age");
                   8981:     for(j=1; j<=nlstate+ndeath;j++){ 
                   8982:       for(i=1; i<=nlstate;i++)               
                   8983:        fprintf(ficresf," p%d%d",i,j);
                   8984:       fprintf(ficresf," wp.%d",j);
                   8985:     }
1.296     brouard  8986:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  8987:       fprintf(ficresf,"\n");
1.296     brouard  8988:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  8989:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   8990:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  8991:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   8992:        nhstepm = nhstepm/hstepm; 
                   8993:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8994:        oldm=oldms;savm=savms;
1.268     brouard  8995:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  8996:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  8997:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  8998:        for (h=0; h<=nhstepm; h++){
                   8999:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  9000:            break;
                   9001:          }
                   9002:        }
                   9003:        fprintf(ficresf,"\n");
                   9004:        for(j=1;j<=cptcoveff;j++) 
1.330     brouard  9005:          fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
1.296     brouard  9006:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  9007:        
                   9008:        for(j=1; j<=nlstate+ndeath;j++) {
                   9009:          ppij=0.;
                   9010:          for(i=1; i<=nlstate;i++) {
1.278     brouard  9011:            if (mobilav>=1)
                   9012:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   9013:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   9014:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   9015:            }
1.268     brouard  9016:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   9017:          } /* end i */
                   9018:          fprintf(ficresf," %.3f", ppij);
                   9019:        }/* end j */
1.227     brouard  9020:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9021:       } /* end agec */
1.266     brouard  9022:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   9023:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  9024:     } /* end yearp */
                   9025:   } /* end  k */
1.219     brouard  9026:        
1.126     brouard  9027:   fclose(ficresf);
1.215     brouard  9028:   printf("End of Computing forecasting \n");
                   9029:   fprintf(ficlog,"End of Computing forecasting\n");
                   9030: 
1.126     brouard  9031: }
                   9032: 
1.269     brouard  9033: /************** Back Forecasting ******************/
1.296     brouard  9034:  /* 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){ */
                   9035:  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){
                   9036:   /* back1, year, month, day of starting backprojection
1.267     brouard  9037:      agemin, agemax range of age
                   9038:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  9039:      anback2 year of end of backprojection (same day and month as back1).
                   9040:      prevacurrent and prev are prevalences.
1.267     brouard  9041:   */
                   9042:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   9043:   double agec; /* generic age */
1.302     brouard  9044:   double agelim, ppij, ppi, yp,yp1,yp2; /* ,jintmean,mintmean,aintmean;*/
1.267     brouard  9045:   double *popeffectif,*popcount;
                   9046:   double ***p3mat;
                   9047:   /* double ***mobaverage; */
                   9048:   char fileresfb[FILENAMELENGTH];
                   9049:  
1.268     brouard  9050:   agelim=AGEINF;
1.267     brouard  9051:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9052:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9053:      We still use firstpass and lastpass as another selection.
                   9054:   */
                   9055:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9056:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   9057: 
                   9058:   /*Do we need to compute prevalence again?*/
                   9059: 
                   9060:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   9061:   
                   9062:   strcpy(fileresfb,"FB_");
                   9063:   strcat(fileresfb,fileresu);
                   9064:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   9065:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   9066:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   9067:   }
                   9068:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   9069:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   9070:   
                   9071:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   9072:   
                   9073:    
                   9074:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9075:   if (stepm<=12) stepsize=1;
                   9076:   if(estepm < stepm){
                   9077:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9078:   }
1.270     brouard  9079:   else{
                   9080:     hstepm=estepm;   
                   9081:   }
                   9082:   if(estepm >= stepm){ /* Yes every two year */
                   9083:     stepsize=2;
                   9084:   }
1.267     brouard  9085:   
                   9086:   hstepm=hstepm/stepm;
1.296     brouard  9087:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9088:   /*                              fractional in yp1 *\/ */
                   9089:   /* aintmean=yp; */
                   9090:   /* yp2=modf((yp1*12),&yp); */
                   9091:   /* mintmean=yp; */
                   9092:   /* yp1=modf((yp2*30.5),&yp); */
                   9093:   /* jintmean=yp; */
                   9094:   /* if(jintmean==0) jintmean=1; */
                   9095:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  9096:   
                   9097:   i1=pow(2,cptcoveff);
                   9098:   if (cptcovn < 1){i1=1;}
                   9099:   
1.296     brouard  9100:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   9101:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  9102:   
                   9103:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   9104:   
                   9105:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9106:   for(k=1; k<=i1;k++){
                   9107:     if(i1 != 1 && TKresult[nres]!= k)
                   9108:       continue;
                   9109:     if(invalidvarcomb[k]){
                   9110:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   9111:       continue;
                   9112:     }
1.268     brouard  9113:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.267     brouard  9114:     for(j=1;j<=cptcoveff;j++) {
1.330     brouard  9115:       fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
1.267     brouard  9116:     }
                   9117:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   9118:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9119:     }
                   9120:     fprintf(ficresfb," yearbproj age");
                   9121:     for(j=1; j<=nlstate+ndeath;j++){
                   9122:       for(i=1; i<=nlstate;i++)
1.268     brouard  9123:        fprintf(ficresfb," b%d%d",i,j);
                   9124:       fprintf(ficresfb," b.%d",j);
1.267     brouard  9125:     }
1.296     brouard  9126:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  9127:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   9128:       fprintf(ficresfb,"\n");
1.296     brouard  9129:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  9130:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  9131:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   9132:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  9133:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  9134:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  9135:        nhstepm = nhstepm/hstepm;
                   9136:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9137:        oldm=oldms;savm=savms;
1.268     brouard  9138:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  9139:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  9140:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  9141:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   9142:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   9143:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  9144:        for (h=0; h<=nhstepm; h++){
1.268     brouard  9145:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   9146:            break;
                   9147:          }
                   9148:        }
                   9149:        fprintf(ficresfb,"\n");
                   9150:        for(j=1;j<=cptcoveff;j++)
1.330     brouard  9151:          fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
1.296     brouard  9152:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  9153:        for(i=1; i<=nlstate+ndeath;i++) {
                   9154:          ppij=0.;ppi=0.;
                   9155:          for(j=1; j<=nlstate;j++) {
                   9156:            /* if (mobilav==1) */
1.269     brouard  9157:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   9158:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   9159:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   9160:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  9161:              /* else { */
                   9162:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   9163:              /* } */
1.268     brouard  9164:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   9165:          } /* end j */
                   9166:          if(ppi <0.99){
                   9167:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   9168:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   9169:          }
                   9170:          fprintf(ficresfb," %.3f", ppij);
                   9171:        }/* end j */
1.267     brouard  9172:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9173:       } /* end agec */
                   9174:     } /* end yearp */
                   9175:   } /* end k */
1.217     brouard  9176:   
1.267     brouard  9177:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  9178:   
1.267     brouard  9179:   fclose(ficresfb);
                   9180:   printf("End of Computing Back forecasting \n");
                   9181:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  9182:        
1.267     brouard  9183: }
1.217     brouard  9184: 
1.269     brouard  9185: /* Variance of prevalence limit: varprlim */
                   9186:  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  9187:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  9188:  
                   9189:    char fileresvpl[FILENAMELENGTH];  
                   9190:    FILE *ficresvpl;
                   9191:    double **oldm, **savm;
                   9192:    double **varpl; /* Variances of prevalence limits by age */   
                   9193:    int i1, k, nres, j ;
                   9194:    
                   9195:     strcpy(fileresvpl,"VPL_");
                   9196:     strcat(fileresvpl,fileresu);
                   9197:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  9198:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  9199:       exit(0);
                   9200:     }
1.288     brouard  9201:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   9202:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  9203:     
                   9204:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   9205:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   9206:     
                   9207:     i1=pow(2,cptcoveff);
                   9208:     if (cptcovn < 1){i1=1;}
                   9209: 
                   9210:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9211:     for(k=1; k<=i1;k++){
                   9212:       if(i1 != 1 && TKresult[nres]!= k)
                   9213:        continue;
                   9214:       fprintf(ficresvpl,"\n#****** ");
                   9215:       printf("\n#****** ");
                   9216:       fprintf(ficlog,"\n#****** ");
                   9217:       for(j=1;j<=cptcoveff;j++) {
1.330     brouard  9218:        fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
                   9219:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
                   9220:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
1.269     brouard  9221:       }
                   9222:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   9223:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9224:        fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9225:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9226:       }        
                   9227:       fprintf(ficresvpl,"******\n");
                   9228:       printf("******\n");
                   9229:       fprintf(ficlog,"******\n");
                   9230:       
                   9231:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9232:       oldm=oldms;savm=savms;
                   9233:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   9234:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   9235:       /*}*/
                   9236:     }
                   9237:     
                   9238:     fclose(ficresvpl);
1.288     brouard  9239:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   9240:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  9241: 
                   9242:  }
                   9243: /* Variance of back prevalence: varbprlim */
                   9244:  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){
                   9245:       /*------- Variance of back (stable) prevalence------*/
                   9246: 
                   9247:    char fileresvbl[FILENAMELENGTH];  
                   9248:    FILE  *ficresvbl;
                   9249: 
                   9250:    double **oldm, **savm;
                   9251:    double **varbpl; /* Variances of back prevalence limits by age */   
                   9252:    int i1, k, nres, j ;
                   9253: 
                   9254:    strcpy(fileresvbl,"VBL_");
                   9255:    strcat(fileresvbl,fileresu);
                   9256:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   9257:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   9258:      exit(0);
                   9259:    }
                   9260:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   9261:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   9262:    
                   9263:    
                   9264:    i1=pow(2,cptcoveff);
                   9265:    if (cptcovn < 1){i1=1;}
                   9266:    
                   9267:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9268:      for(k=1; k<=i1;k++){
                   9269:        if(i1 != 1 && TKresult[nres]!= k)
                   9270:         continue;
                   9271:        fprintf(ficresvbl,"\n#****** ");
                   9272:        printf("\n#****** ");
                   9273:        fprintf(ficlog,"\n#****** ");
                   9274:        for(j=1;j<=cptcoveff;j++) {
1.330     brouard  9275:         fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
                   9276:         fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
                   9277:         printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
1.269     brouard  9278:        }
                   9279:        for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   9280:         printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9281:         fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9282:         fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9283:        }
                   9284:        fprintf(ficresvbl,"******\n");
                   9285:        printf("******\n");
                   9286:        fprintf(ficlog,"******\n");
                   9287:        
                   9288:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9289:        oldm=oldms;savm=savms;
                   9290:        
                   9291:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   9292:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   9293:        /*}*/
                   9294:      }
                   9295:    
                   9296:    fclose(ficresvbl);
                   9297:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   9298:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   9299: 
                   9300:  } /* End of varbprlim */
                   9301: 
1.126     brouard  9302: /************** Forecasting *****not tested NB*************/
1.227     brouard  9303: /* 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  9304:   
1.227     brouard  9305: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   9306: /*   int *popage; */
                   9307: /*   double calagedatem, agelim, kk1, kk2; */
                   9308: /*   double *popeffectif,*popcount; */
                   9309: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   9310: /*   /\* double ***mobaverage; *\/ */
                   9311: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  9312: 
1.227     brouard  9313: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9314: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9315: /*   agelim=AGESUP; */
                   9316: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  9317:   
1.227     brouard  9318: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  9319:   
                   9320:   
1.227     brouard  9321: /*   strcpy(filerespop,"POP_");  */
                   9322: /*   strcat(filerespop,fileresu); */
                   9323: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   9324: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   9325: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   9326: /*   } */
                   9327: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   9328: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  9329: 
1.227     brouard  9330: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  9331: 
1.227     brouard  9332: /*   /\* if (mobilav!=0) { *\/ */
                   9333: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   9334: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   9335: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   9336: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   9337: /*   /\*   } *\/ */
                   9338: /*   /\* } *\/ */
1.126     brouard  9339: 
1.227     brouard  9340: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   9341: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  9342:   
1.227     brouard  9343: /*   agelim=AGESUP; */
1.126     brouard  9344:   
1.227     brouard  9345: /*   hstepm=1; */
                   9346: /*   hstepm=hstepm/stepm;  */
1.218     brouard  9347:        
1.227     brouard  9348: /*   if (popforecast==1) { */
                   9349: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   9350: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   9351: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   9352: /*     }  */
                   9353: /*     popage=ivector(0,AGESUP); */
                   9354: /*     popeffectif=vector(0,AGESUP); */
                   9355: /*     popcount=vector(0,AGESUP); */
1.126     brouard  9356:     
1.227     brouard  9357: /*     i=1;    */
                   9358: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  9359:     
1.227     brouard  9360: /*     imx=i; */
                   9361: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   9362: /*   } */
1.218     brouard  9363:   
1.227     brouard  9364: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   9365: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   9366: /*       k=k+1; */
                   9367: /*       fprintf(ficrespop,"\n#******"); */
                   9368: /*       for(j=1;j<=cptcoveff;j++) { */
                   9369: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   9370: /*       } */
                   9371: /*       fprintf(ficrespop,"******\n"); */
                   9372: /*       fprintf(ficrespop,"# Age"); */
                   9373: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   9374: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  9375:       
1.227     brouard  9376: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   9377: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  9378:        
1.227     brouard  9379: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   9380: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   9381: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  9382:          
1.227     brouard  9383: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9384: /*       oldm=oldms;savm=savms; */
                   9385: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  9386:          
1.227     brouard  9387: /*       for (h=0; h<=nhstepm; h++){ */
                   9388: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   9389: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   9390: /*         }  */
                   9391: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   9392: /*           kk1=0.;kk2=0; */
                   9393: /*           for(i=1; i<=nlstate;i++) {               */
                   9394: /*             if (mobilav==1)  */
                   9395: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   9396: /*             else { */
                   9397: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   9398: /*             } */
                   9399: /*           } */
                   9400: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   9401: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   9402: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   9403: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   9404: /*           } */
                   9405: /*         } */
                   9406: /*         for(i=1; i<=nlstate;i++){ */
                   9407: /*           kk1=0.; */
                   9408: /*           for(j=1; j<=nlstate;j++){ */
                   9409: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   9410: /*           } */
                   9411: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   9412: /*         } */
1.218     brouard  9413:            
1.227     brouard  9414: /*         if (h==(int)(calagedatem+12*cpt)) */
                   9415: /*           for(j=1; j<=nlstate;j++)  */
                   9416: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   9417: /*       } */
                   9418: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9419: /*     } */
                   9420: /*       } */
1.218     brouard  9421:       
1.227     brouard  9422: /*       /\******\/ */
1.218     brouard  9423:       
1.227     brouard  9424: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   9425: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   9426: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   9427: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   9428: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  9429:          
1.227     brouard  9430: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9431: /*       oldm=oldms;savm=savms; */
                   9432: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   9433: /*       for (h=0; h<=nhstepm; h++){ */
                   9434: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   9435: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   9436: /*         }  */
                   9437: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   9438: /*           kk1=0.;kk2=0; */
                   9439: /*           for(i=1; i<=nlstate;i++) {               */
                   9440: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   9441: /*           } */
                   9442: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   9443: /*         } */
                   9444: /*       } */
                   9445: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9446: /*     } */
                   9447: /*       } */
                   9448: /*     }  */
                   9449: /*   } */
1.218     brouard  9450:   
1.227     brouard  9451: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  9452:   
1.227     brouard  9453: /*   if (popforecast==1) { */
                   9454: /*     free_ivector(popage,0,AGESUP); */
                   9455: /*     free_vector(popeffectif,0,AGESUP); */
                   9456: /*     free_vector(popcount,0,AGESUP); */
                   9457: /*   } */
                   9458: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9459: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9460: /*   fclose(ficrespop); */
                   9461: /* } /\* End of popforecast *\/ */
1.218     brouard  9462:  
1.126     brouard  9463: int fileappend(FILE *fichier, char *optionfich)
                   9464: {
                   9465:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   9466:     printf("Problem with file: %s\n", optionfich);
                   9467:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   9468:     return (0);
                   9469:   }
                   9470:   fflush(fichier);
                   9471:   return (1);
                   9472: }
                   9473: 
                   9474: 
                   9475: /**************** function prwizard **********************/
                   9476: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   9477: {
                   9478: 
                   9479:   /* Wizard to print covariance matrix template */
                   9480: 
1.164     brouard  9481:   char ca[32], cb[32];
                   9482:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  9483:   int numlinepar;
                   9484: 
                   9485:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9486:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9487:   for(i=1; i <=nlstate; i++){
                   9488:     jj=0;
                   9489:     for(j=1; j <=nlstate+ndeath; j++){
                   9490:       if(j==i) continue;
                   9491:       jj++;
                   9492:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   9493:       printf("%1d%1d",i,j);
                   9494:       fprintf(ficparo,"%1d%1d",i,j);
                   9495:       for(k=1; k<=ncovmodel;k++){
                   9496:        /*        printf(" %lf",param[i][j][k]); */
                   9497:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   9498:        printf(" 0.");
                   9499:        fprintf(ficparo," 0.");
                   9500:       }
                   9501:       printf("\n");
                   9502:       fprintf(ficparo,"\n");
                   9503:     }
                   9504:   }
                   9505:   printf("# Scales (for hessian or gradient estimation)\n");
                   9506:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   9507:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   9508:   for(i=1; i <=nlstate; i++){
                   9509:     jj=0;
                   9510:     for(j=1; j <=nlstate+ndeath; j++){
                   9511:       if(j==i) continue;
                   9512:       jj++;
                   9513:       fprintf(ficparo,"%1d%1d",i,j);
                   9514:       printf("%1d%1d",i,j);
                   9515:       fflush(stdout);
                   9516:       for(k=1; k<=ncovmodel;k++){
                   9517:        /*      printf(" %le",delti3[i][j][k]); */
                   9518:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   9519:        printf(" 0.");
                   9520:        fprintf(ficparo," 0.");
                   9521:       }
                   9522:       numlinepar++;
                   9523:       printf("\n");
                   9524:       fprintf(ficparo,"\n");
                   9525:     }
                   9526:   }
                   9527:   printf("# Covariance matrix\n");
                   9528: /* # 121 Var(a12)\n\ */
                   9529: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   9530: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   9531: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   9532: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   9533: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   9534: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   9535: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   9536:   fflush(stdout);
                   9537:   fprintf(ficparo,"# Covariance matrix\n");
                   9538:   /* # 121 Var(a12)\n\ */
                   9539:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   9540:   /* #   ...\n\ */
                   9541:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   9542:   
                   9543:   for(itimes=1;itimes<=2;itimes++){
                   9544:     jj=0;
                   9545:     for(i=1; i <=nlstate; i++){
                   9546:       for(j=1; j <=nlstate+ndeath; j++){
                   9547:        if(j==i) continue;
                   9548:        for(k=1; k<=ncovmodel;k++){
                   9549:          jj++;
                   9550:          ca[0]= k+'a'-1;ca[1]='\0';
                   9551:          if(itimes==1){
                   9552:            printf("#%1d%1d%d",i,j,k);
                   9553:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   9554:          }else{
                   9555:            printf("%1d%1d%d",i,j,k);
                   9556:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   9557:            /*  printf(" %.5le",matcov[i][j]); */
                   9558:          }
                   9559:          ll=0;
                   9560:          for(li=1;li <=nlstate; li++){
                   9561:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   9562:              if(lj==li) continue;
                   9563:              for(lk=1;lk<=ncovmodel;lk++){
                   9564:                ll++;
                   9565:                if(ll<=jj){
                   9566:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   9567:                  if(ll<jj){
                   9568:                    if(itimes==1){
                   9569:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9570:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9571:                    }else{
                   9572:                      printf(" 0.");
                   9573:                      fprintf(ficparo," 0.");
                   9574:                    }
                   9575:                  }else{
                   9576:                    if(itimes==1){
                   9577:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   9578:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   9579:                    }else{
                   9580:                      printf(" 0.");
                   9581:                      fprintf(ficparo," 0.");
                   9582:                    }
                   9583:                  }
                   9584:                }
                   9585:              } /* end lk */
                   9586:            } /* end lj */
                   9587:          } /* end li */
                   9588:          printf("\n");
                   9589:          fprintf(ficparo,"\n");
                   9590:          numlinepar++;
                   9591:        } /* end k*/
                   9592:       } /*end j */
                   9593:     } /* end i */
                   9594:   } /* end itimes */
                   9595: 
                   9596: } /* end of prwizard */
                   9597: /******************* Gompertz Likelihood ******************************/
                   9598: double gompertz(double x[])
                   9599: { 
1.302     brouard  9600:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
1.126     brouard  9601:   int i,n=0; /* n is the size of the sample */
                   9602: 
1.220     brouard  9603:   for (i=1;i<=imx ; i++) {
1.126     brouard  9604:     sump=sump+weight[i];
                   9605:     /*    sump=sump+1;*/
                   9606:     num=num+1;
                   9607:   }
1.302     brouard  9608:   L=0.0;
                   9609:   /* agegomp=AGEGOMP; */
1.126     brouard  9610:   /* for (i=0; i<=imx; i++) 
                   9611:      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]);*/
                   9612: 
1.302     brouard  9613:   for (i=1;i<=imx ; i++) {
                   9614:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   9615:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   9616:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   9617:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   9618:      * +
                   9619:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   9620:      */
                   9621:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   9622:        if (cens[i] == 1){
                   9623:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   9624:        } else if (cens[i] == 0){
1.126     brouard  9625:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
1.302     brouard  9626:          +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   9627:       } else
                   9628:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
1.126     brouard  9629:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
1.302     brouard  9630:        L=L+A*weight[i];
1.126     brouard  9631:        /*      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  9632:      }
                   9633:   }
1.126     brouard  9634: 
1.302     brouard  9635:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
1.126     brouard  9636:  
                   9637:   return -2*L*num/sump;
                   9638: }
                   9639: 
1.136     brouard  9640: #ifdef GSL
                   9641: /******************* Gompertz_f Likelihood ******************************/
                   9642: double gompertz_f(const gsl_vector *v, void *params)
                   9643: { 
1.302     brouard  9644:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
1.136     brouard  9645:   double *x= (double *) v->data;
                   9646:   int i,n=0; /* n is the size of the sample */
                   9647: 
                   9648:   for (i=0;i<=imx-1 ; i++) {
                   9649:     sump=sump+weight[i];
                   9650:     /*    sump=sump+1;*/
                   9651:     num=num+1;
                   9652:   }
                   9653:  
                   9654:  
                   9655:   /* for (i=0; i<=imx; i++) 
                   9656:      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]);*/
                   9657:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   9658:   for (i=1;i<=imx ; i++)
                   9659:     {
                   9660:       if (cens[i] == 1 && wav[i]>1)
                   9661:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   9662:       
                   9663:       if (cens[i] == 0 && wav[i]>1)
                   9664:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   9665:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   9666:       
                   9667:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   9668:       if (wav[i] > 1 ) { /* ??? */
                   9669:        LL=LL+A*weight[i];
                   9670:        /*      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]);*/
                   9671:       }
                   9672:     }
                   9673: 
                   9674:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   9675:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   9676:  
                   9677:   return -2*LL*num/sump;
                   9678: }
                   9679: #endif
                   9680: 
1.126     brouard  9681: /******************* Printing html file ***********/
1.201     brouard  9682: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  9683:                  int lastpass, int stepm, int weightopt, char model[],\
                   9684:                  int imx,  double p[],double **matcov,double agemortsup){
                   9685:   int i,k;
                   9686: 
                   9687:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   9688:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   9689:   for (i=1;i<=2;i++) 
                   9690:     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  9691:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  9692:   fprintf(fichtm,"</ul>");
                   9693: 
                   9694: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   9695: 
                   9696:  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>");
                   9697: 
                   9698:  for (k=agegomp;k<(agemortsup-2);k++) 
                   9699:    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]);
                   9700: 
                   9701:  
                   9702:   fflush(fichtm);
                   9703: }
                   9704: 
                   9705: /******************* Gnuplot file **************/
1.201     brouard  9706: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  9707: 
                   9708:   char dirfileres[132],optfileres[132];
1.164     brouard  9709: 
1.126     brouard  9710:   int ng;
                   9711: 
                   9712: 
                   9713:   /*#ifdef windows */
                   9714:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   9715:     /*#endif */
                   9716: 
                   9717: 
                   9718:   strcpy(dirfileres,optionfilefiname);
                   9719:   strcpy(optfileres,"vpl");
1.199     brouard  9720:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  9721:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  9722:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  9723:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  9724:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   9725: 
                   9726: } 
                   9727: 
1.136     brouard  9728: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   9729: {
1.126     brouard  9730: 
1.136     brouard  9731:   /*-------- data file ----------*/
                   9732:   FILE *fic;
                   9733:   char dummy[]="                         ";
1.240     brouard  9734:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  9735:   int lstra;
1.136     brouard  9736:   int linei, month, year,iout;
1.302     brouard  9737:   int noffset=0; /* This is the offset if BOM data file */
1.136     brouard  9738:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  9739:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  9740:   char *stratrunc;
1.223     brouard  9741: 
1.240     brouard  9742:   DummyV=ivector(1,NCOVMAX); /* 1 to 3 */
                   9743:   FixedV=ivector(1,NCOVMAX); /* 1 to 3 */
1.328     brouard  9744:   for(v=1;v<NCOVMAX;v++){
                   9745:     DummyV[v]=0;
                   9746:     FixedV[v]=0;
                   9747:   }
1.126     brouard  9748: 
1.240     brouard  9749:   for(v=1; v <=ncovcol;v++){
                   9750:     DummyV[v]=0;
                   9751:     FixedV[v]=0;
                   9752:   }
                   9753:   for(v=ncovcol+1; v <=ncovcol+nqv;v++){
                   9754:     DummyV[v]=1;
                   9755:     FixedV[v]=0;
                   9756:   }
                   9757:   for(v=ncovcol+nqv+1; v <=ncovcol+nqv+ntv;v++){
                   9758:     DummyV[v]=0;
                   9759:     FixedV[v]=1;
                   9760:   }
                   9761:   for(v=ncovcol+nqv+ntv+1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   9762:     DummyV[v]=1;
                   9763:     FixedV[v]=1;
                   9764:   }
                   9765:   for(v=1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   9766:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   9767:     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]);
                   9768:   }
1.126     brouard  9769: 
1.136     brouard  9770:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  9771:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   9772:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  9773:   }
1.126     brouard  9774: 
1.302     brouard  9775:     /* Is it a BOM UTF-8 Windows file? */
                   9776:   /* First data line */
                   9777:   linei=0;
                   9778:   while(fgets(line, MAXLINE, fic)) {
                   9779:     noffset=0;
                   9780:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   9781:     {
                   9782:       noffset=noffset+3;
                   9783:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   9784:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   9785:       fflush(ficlog); return 1;
                   9786:     }
                   9787:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   9788:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   9789:     {
                   9790:       noffset=noffset+2;
1.304     brouard  9791:       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);
                   9792:       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  9793:       fflush(ficlog); return 1;
                   9794:     }
                   9795:     else if( line[0] == 0 && line[1] == 0)
                   9796:     {
                   9797:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   9798:        noffset=noffset+4;
1.304     brouard  9799:        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);
                   9800:        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  9801:        fflush(ficlog); return 1;
                   9802:       }
                   9803:     } else{
                   9804:       ;/*printf(" Not a BOM file\n");*/
                   9805:     }
                   9806:         /* If line starts with a # it is a comment */
                   9807:     if (line[noffset] == '#') {
                   9808:       linei=linei+1;
                   9809:       break;
                   9810:     }else{
                   9811:       break;
                   9812:     }
                   9813:   }
                   9814:   fclose(fic);
                   9815:   if((fic=fopen(datafile,"r"))==NULL)    {
                   9816:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   9817:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   9818:   }
                   9819:   /* Not a Bom file */
                   9820:   
1.136     brouard  9821:   i=1;
                   9822:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   9823:     linei=linei+1;
                   9824:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   9825:       if(line[j] == '\t')
                   9826:        line[j] = ' ';
                   9827:     }
                   9828:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   9829:       ;
                   9830:     };
                   9831:     line[j+1]=0;  /* Trims blanks at end of line */
                   9832:     if(line[0]=='#'){
                   9833:       fprintf(ficlog,"Comment line\n%s\n",line);
                   9834:       printf("Comment line\n%s\n",line);
                   9835:       continue;
                   9836:     }
                   9837:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  9838:     strcpy(line, linetmp);
1.223     brouard  9839:     
                   9840:     /* Loops on waves */
                   9841:     for (j=maxwav;j>=1;j--){
                   9842:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  9843:        cutv(stra, strb, line, ' '); 
                   9844:        if(strb[0]=='.') { /* Missing value */
                   9845:          lval=-1;
                   9846:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
                   9847:          cotvar[j][ntv+iv][i]=-1; /* For performance reasons */
                   9848:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   9849:            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);
                   9850:            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);
                   9851:            return 1;
                   9852:          }
                   9853:        }else{
                   9854:          errno=0;
                   9855:          /* what_kind_of_number(strb); */
                   9856:          dval=strtod(strb,&endptr); 
                   9857:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   9858:          /* if(strb != endptr && *endptr == '\0') */
                   9859:          /*    dval=dlval; */
                   9860:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   9861:          if( strb[0]=='\0' || (*endptr != '\0')){
                   9862:            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);
                   9863:            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);
                   9864:            return 1;
                   9865:          }
                   9866:          cotqvar[j][iv][i]=dval; 
                   9867:          cotvar[j][ntv+iv][i]=dval; 
                   9868:        }
                   9869:        strcpy(line,stra);
1.223     brouard  9870:       }/* end loop ntqv */
1.225     brouard  9871:       
1.223     brouard  9872:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  9873:        cutv(stra, strb, line, ' '); 
                   9874:        if(strb[0]=='.') { /* Missing value */
                   9875:          lval=-1;
                   9876:        }else{
                   9877:          errno=0;
                   9878:          lval=strtol(strb,&endptr,10); 
                   9879:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   9880:          if( strb[0]=='\0' || (*endptr != '\0')){
                   9881:            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);
                   9882:            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);
                   9883:            return 1;
                   9884:          }
                   9885:        }
                   9886:        if(lval <-1 || lval >1){
                   9887:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  9888:  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  9889:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  9890:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9891:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9892:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  9893:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  9894:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  9895:  Exiting.\n",lval,linei, i,line,iv,j);
1.238     brouard  9896:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  9897:  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  9898:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  9899:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9900:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9901:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  9902:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  9903:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  9904:  Exiting.\n",lval,linei, i,line,iv,j);fflush(ficlog);
1.238     brouard  9905:          return 1;
                   9906:        }
                   9907:        cotvar[j][iv][i]=(double)(lval);
                   9908:        strcpy(line,stra);
1.223     brouard  9909:       }/* end loop ntv */
1.225     brouard  9910:       
1.223     brouard  9911:       /* Statuses  at wave */
1.137     brouard  9912:       cutv(stra, strb, line, ' '); 
1.223     brouard  9913:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  9914:        lval=-1;
1.136     brouard  9915:       }else{
1.238     brouard  9916:        errno=0;
                   9917:        lval=strtol(strb,&endptr,10); 
                   9918:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   9919:        if( strb[0]=='\0' || (*endptr != '\0')){
                   9920:          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);
                   9921:          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);
                   9922:          return 1;
                   9923:        }
1.136     brouard  9924:       }
1.225     brouard  9925:       
1.136     brouard  9926:       s[j][i]=lval;
1.225     brouard  9927:       
1.223     brouard  9928:       /* Date of Interview */
1.136     brouard  9929:       strcpy(line,stra);
                   9930:       cutv(stra, strb,line,' ');
1.169     brouard  9931:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9932:       }
1.169     brouard  9933:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  9934:        month=99;
                   9935:        year=9999;
1.136     brouard  9936:       }else{
1.225     brouard  9937:        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);
                   9938:        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);
                   9939:        return 1;
1.136     brouard  9940:       }
                   9941:       anint[j][i]= (double) year; 
1.302     brouard  9942:       mint[j][i]= (double)month;
                   9943:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   9944:       /*       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]); */
                   9945:       /*       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]); */
                   9946:       /* } */
1.136     brouard  9947:       strcpy(line,stra);
1.223     brouard  9948:     } /* End loop on waves */
1.225     brouard  9949:     
1.223     brouard  9950:     /* Date of death */
1.136     brouard  9951:     cutv(stra, strb,line,' '); 
1.169     brouard  9952:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9953:     }
1.169     brouard  9954:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  9955:       month=99;
                   9956:       year=9999;
                   9957:     }else{
1.141     brouard  9958:       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  9959:       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);
                   9960:       return 1;
1.136     brouard  9961:     }
                   9962:     andc[i]=(double) year; 
                   9963:     moisdc[i]=(double) month; 
                   9964:     strcpy(line,stra);
                   9965:     
1.223     brouard  9966:     /* Date of birth */
1.136     brouard  9967:     cutv(stra, strb,line,' '); 
1.169     brouard  9968:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9969:     }
1.169     brouard  9970:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  9971:       month=99;
                   9972:       year=9999;
                   9973:     }else{
1.141     brouard  9974:       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);
                   9975:       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  9976:       return 1;
1.136     brouard  9977:     }
                   9978:     if (year==9999) {
1.141     brouard  9979:       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);
                   9980:       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  9981:       return 1;
                   9982:       
1.136     brouard  9983:     }
                   9984:     annais[i]=(double)(year);
1.302     brouard  9985:     moisnais[i]=(double)(month);
                   9986:     for (j=1;j<=maxwav;j++){
                   9987:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   9988:        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]);
                   9989:        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]);
                   9990:       }
                   9991:     }
                   9992: 
1.136     brouard  9993:     strcpy(line,stra);
1.225     brouard  9994:     
1.223     brouard  9995:     /* Sample weight */
1.136     brouard  9996:     cutv(stra, strb,line,' '); 
                   9997:     errno=0;
                   9998:     dval=strtod(strb,&endptr); 
                   9999:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  10000:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   10001:       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  10002:       fflush(ficlog);
                   10003:       return 1;
                   10004:     }
                   10005:     weight[i]=dval; 
                   10006:     strcpy(line,stra);
1.225     brouard  10007:     
1.223     brouard  10008:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   10009:       cutv(stra, strb, line, ' '); 
                   10010:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  10011:        lval=-1;
1.311     brouard  10012:        coqvar[iv][i]=NAN; 
                   10013:        covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  10014:       }else{
1.225     brouard  10015:        errno=0;
                   10016:        /* what_kind_of_number(strb); */
                   10017:        dval=strtod(strb,&endptr);
                   10018:        /* if(strb != endptr && *endptr == '\0') */
                   10019:        /*   dval=dlval; */
                   10020:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10021:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10022:          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);
                   10023:          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);
                   10024:          return 1;
                   10025:        }
                   10026:        coqvar[iv][i]=dval; 
1.226     brouard  10027:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  10028:       }
                   10029:       strcpy(line,stra);
                   10030:     }/* end loop nqv */
1.136     brouard  10031:     
1.223     brouard  10032:     /* Covariate values */
1.136     brouard  10033:     for (j=ncovcol;j>=1;j--){
                   10034:       cutv(stra, strb,line,' '); 
1.223     brouard  10035:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  10036:        lval=-1;
1.136     brouard  10037:       }else{
1.225     brouard  10038:        errno=0;
                   10039:        lval=strtol(strb,&endptr,10); 
                   10040:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10041:          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);
                   10042:          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);
                   10043:          return 1;
                   10044:        }
1.136     brouard  10045:       }
                   10046:       if(lval <-1 || lval >1){
1.225     brouard  10047:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  10048:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   10049:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  10050:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10051:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10052:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  10053:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  10054:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  10055:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  10056:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  10057:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   10058:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  10059:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10060:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10061:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  10062:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  10063:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  10064:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  10065:        return 1;
1.136     brouard  10066:       }
                   10067:       covar[j][i]=(double)(lval);
                   10068:       strcpy(line,stra);
                   10069:     }  
                   10070:     lstra=strlen(stra);
1.225     brouard  10071:     
1.136     brouard  10072:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   10073:       stratrunc = &(stra[lstra-9]);
                   10074:       num[i]=atol(stratrunc);
                   10075:     }
                   10076:     else
                   10077:       num[i]=atol(stra);
                   10078:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   10079:       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;}*/
                   10080:     
                   10081:     i=i+1;
                   10082:   } /* End loop reading  data */
1.225     brouard  10083:   
1.136     brouard  10084:   *imax=i-1; /* Number of individuals */
                   10085:   fclose(fic);
1.225     brouard  10086:   
1.136     brouard  10087:   return (0);
1.164     brouard  10088:   /* endread: */
1.225     brouard  10089:   printf("Exiting readdata: ");
                   10090:   fclose(fic);
                   10091:   return (1);
1.223     brouard  10092: }
1.126     brouard  10093: 
1.234     brouard  10094: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  10095:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  10096:   while (*p2 == ' ')
1.234     brouard  10097:     p2++; 
                   10098:   /* while ((*p1++ = *p2++) !=0) */
                   10099:   /*   ; */
                   10100:   /* do */
                   10101:   /*   while (*p2 == ' ') */
                   10102:   /*     p2++; */
                   10103:   /* while (*p1++ == *p2++); */
                   10104:   *stri=p2; 
1.145     brouard  10105: }
                   10106: 
1.330     brouard  10107: int decoderesult( char resultline[], int nres)
1.230     brouard  10108: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   10109: {
1.235     brouard  10110:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  10111:   char resultsav[MAXLINE];
1.330     brouard  10112:   /* int resultmodel[MAXLINE]; */
1.234     brouard  10113:   int modelresult[MAXLINE];
1.230     brouard  10114:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   10115: 
1.234     brouard  10116:   removefirstspace(&resultline);
1.230     brouard  10117: 
                   10118:   if (strstr(resultline,"v") !=0){
                   10119:     printf("Error. 'v' must be in upper case 'V' result: %s ",resultline);
                   10120:     fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultline);fflush(ficlog);
                   10121:     return 1;
                   10122:   }
                   10123:   trimbb(resultsav, resultline);
                   10124:   if (strlen(resultsav) >1){
                   10125:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' */
                   10126:   }
1.253     brouard  10127:   if(j == 0){ /* Resultline but no = */
                   10128:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   10129:     return (0);
                   10130:   }
1.234     brouard  10131:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
1.318     brouard  10132:     printf("ERROR: the number of variables in this result line, %d, differs from the number of variables used in the model line, %d.\n",j, cptcovs);
1.310     brouard  10133:     fprintf(ficlog,"ERROR: the number of variables in the resultline, %d, differs from the number of variables used in the model line, %d.\n",j, cptcovs);
1.234     brouard  10134:   }
                   10135:   for(k=1; k<=j;k++){ /* Loop on any covariate of the result line */
                   10136:     if(nbocc(resultsav,'=') >1){
1.318     brouard  10137:       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" */
                   10138:       cutl(strc,strd,strb,'=');  /* strb:"V4=1" strc="1" strd="V4" */
1.234     brouard  10139:     }else
                   10140:       cutl(strc,strd,resultsav,'=');
1.318     brouard  10141:     Tvalsel[k]=atof(strc); /* 1 */ /* Tvalsel of k is the float value of the kth covariate appearing in this result line */
1.234     brouard  10142:     
1.230     brouard  10143:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
1.318     brouard  10144:     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  10145:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   10146:     /* cptcovsel++;     */
                   10147:     if (nbocc(stra,'=') >0)
                   10148:       strcpy(resultsav,stra); /* and analyzes it */
                   10149:   }
1.235     brouard  10150:   /* Checking for missing or useless values in comparison of current model needs */
1.318     brouard  10151:   for(k1=1; k1<= cptcovt ;k1++){ /* Loop on model. model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   10152:     if(Typevar[k1]==0){ /* Single covariate in model *//*0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.234     brouard  10153:       match=0;
1.318     brouard  10154:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10155:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.236     brouard  10156:          modelresult[k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.318     brouard  10157:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
1.234     brouard  10158:          break;
                   10159:        }
                   10160:       }
                   10161:       if(match == 0){
1.310     brouard  10162:        printf("Error in result line: V%d is missing in result: %s according to model=%s\n",k1, resultline, model);
                   10163:        fprintf(ficlog,"Error in result line: V%d is missing in result: %s according to model=%s\n",k1, resultline, model);
                   10164:        return 1;
1.234     brouard  10165:       }
                   10166:     }
                   10167:   }
1.235     brouard  10168:   /* Checking for missing or useless values in comparison of current model needs */
1.318     brouard  10169:   for(k2=1; k2 <=j;k2++){ /* Loop on resultline variables: result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  10170:     match=0;
1.318     brouard  10171:     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.235     brouard  10172:       if(Typevar[k1]==0){ /* Single */
1.237     brouard  10173:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4   */
1.330     brouard  10174:          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.234     brouard  10175:          ++match;
                   10176:        }
                   10177:       }
                   10178:     }
                   10179:     if(match == 0){
                   10180:       printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
1.310     brouard  10181:       fprintf(ficlog,"Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
                   10182:       return 1;
1.234     brouard  10183:     }else if(match > 1){
                   10184:       printf("Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
1.310     brouard  10185:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
                   10186:       return 1;
1.234     brouard  10187:     }
                   10188:   }
1.235     brouard  10189:       
1.234     brouard  10190:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  10191:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.330     brouard  10192:   /* nres=1st result line: V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   10193:   /* 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*/
                   10194:   /* nres=2nd result line: V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.235     brouard  10195:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   10196:   /*    1 0 0 0 */
                   10197:   /*    2 1 0 0 */
                   10198:   /*    3 0 1 0 */ 
1.330     brouard  10199:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 (nres=2)*/
1.235     brouard  10200:   /*    5 0 0 1 */
1.330     brouard  10201:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 (nres=1)*/
1.235     brouard  10202:   /*    7 0 1 1 */
                   10203:   /*    8 1 1 1 */
1.237     brouard  10204:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   10205:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   10206:   /* V5*age V5 known which value for nres?  */
                   10207:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.330     brouard  10208:   for(k1=1, k=0, k4=0, k4q=0; k1 <=cptcovt;k1++){ /* loop k1 on position in the model line (excluding product) */
1.331   ! brouard  10209:     /* k counting number of combination of single dummies in the equation model */
        !          10210:     /* k4 counting single dummies in the equation model */
        !          10211:     /* k4q counting single quantitatives in the equation model */
        !          10212:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Dummy and Single */
        !          10213:        /* k4+1= position in the resultline V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) */
1.330     brouard  10214:       /* modelresult[k3]=k1: k3th position in the result line correspond to the k1 position in the model line */
                   10215:       /* Value in the (current nres) resultline of the variable at the k1th position in the model equation resultmodel[nres][k1]= k3 */
                   10216:       /* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline */
                   10217:       /*      k3 is the position in the nres result line of the k1th variable of the model equation                                          */
1.331   ! brouard  10218:       /* Tvarsel[k3]: Name of the variable at the k3th position in the result line.                                                          */
        !          10219:       /* Tvalsel[k3]: Value of the variable at the k3th position in the result line.                                                         */
1.330     brouard  10220:       /* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline                                 */
                   10221:       /* Tvresult[nres][result_position]= id of the dummy variable at the result_position in the nres resultline                                   */
                   10222:       /* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line                                                      */
                   10223:       /* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line                                                      */
                   10224:       k3= resultmodel[nres][k1]; /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   10225:       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)*/
                   10226:       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.331   ! brouard  10227:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.330     brouard  10228:       Tresult[nres][k4+1]=Tvalsel[k3];/* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) */
1.237     brouard  10229:       Tvresult[nres][k4+1]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   10230:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.235     brouard  10231:       printf("Decoderesult Dummy k=%d, V(k2=V%d)= Tvalsel[%d]=%d, 2**(%d)\n",k, k2, k3, (int)Tvalsel[k3], k4);
                   10232:       k4++;;
1.331   ! brouard  10233:     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Quantitative and single */
1.330     brouard  10234:       /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 */
                   10235:       /* Tqvresult[nres][result_position]= id of the variable at the result_position in the nres resultline                                 */
                   10236:       /* Tqinvresult[nres][Name of a quantitative variable]= value of the variable in the result line                                                      */
                   10237:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 25.1=k3q */
1.318     brouard  10238:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.237     brouard  10239:       Tqresult[nres][k4q+1]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   10240:       Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
                   10241:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.330     brouard  10242:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.235     brouard  10243:       printf("Decoderesult Quantitative nres=%d, V(k2q=V%d)= Tvalsel[%d]=%d, Tvarsel[%d]=%f\n",nres, k2q, k3q, Tvarsel[k3q], k3q, Tvalsel[k3q]);
                   10244:       k4q++;;
1.331   ! brouard  10245:     }else if( Dummy[k1]==2 ){ /* For dummy with age product */
        !          10246:       /* Tvar[k1]; */ /* Age variable */
        !          10247:       k3= resultmodel[nres][Tvar[k1]]; /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
        !          10248:       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)*/
        !          10249:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
        !          10250:       printf("Decoderesult Dummy with age k=%d, k1=%d Tvar[%d]=V%d k2=Tvarsel[%d]=%d Tvalsel[%d]=%d\n",k, k1, k1, Tvar[k1], k3,(int)Tvarsel[k3], k3, (int)Tvalsel[k3]);
        !          10251:     }else if( Dummy[k1]==3 ){ /* For quant with age product */
        !          10252:       k3q= resultmodel[nres][Tvar[k1]]; /* resultmodel[1(V5)] = 25.1=k3q */
        !          10253:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
        !          10254:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
        !          10255:       printf("Decoderesult Quantitative with age nres=%d, k1=%d, Tvar[%d]=V%d V(k2q=V%d)= Tvalsel[%d]=%d, Tvarsel[%d]=%f\n",nres, k1, k1,  Tvar[k1], k2q, k3q, Tvarsel[k3q], k3q, Tvalsel[k3q]);
        !          10256:     }else if(Typevar[k1]==2 ){ /* For product quant or dummy (not with age) */
        !          10257:       printf("Decoderesult Quantitative or Dummy (not with age) nres=%d k1=%d Tvar[%d]=%d \n",nres, k1, k1, Tvar[k1]);
1.330     brouard  10258:     }else{
1.331   ! brouard  10259:       printf("Error Decodemodel probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
        !          10260:       fprintf(ficlog,"Error Decodemodel probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
1.235     brouard  10261:     }
                   10262:   }
1.234     brouard  10263:   
1.235     brouard  10264:   TKresult[nres]=++k; /* Combination for the nresult and the model */
1.230     brouard  10265:   return (0);
                   10266: }
1.235     brouard  10267: 
1.230     brouard  10268: int decodemodel( char model[], int lastobs)
                   10269:  /**< This routine decodes the model and returns:
1.224     brouard  10270:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   10271:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   10272:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   10273:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   10274:        * - cptcovage number of covariates with age*products =2
                   10275:        * - cptcovs number of simple covariates
                   10276:        * - 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
                   10277:        *     which is a new column after the 9 (ncovcol) variables. 
1.319     brouard  10278:        * - if k is a product Vn*Vm, covar[k][i] is filled with correct values for each individual
1.224     brouard  10279:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   10280:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   10281:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   10282:        */
1.319     brouard  10283: /* 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  10284: {
1.238     brouard  10285:   int i, j, k, ks, v;
1.227     brouard  10286:   int  j1, k1, k2, k3, k4;
1.136     brouard  10287:   char modelsav[80];
1.145     brouard  10288:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  10289:   char *strpt;
1.136     brouard  10290: 
1.145     brouard  10291:   /*removespace(model);*/
1.136     brouard  10292:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  10293:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  10294:     if (strstr(model,"AGE") !=0){
1.192     brouard  10295:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   10296:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  10297:       return 1;
                   10298:     }
1.141     brouard  10299:     if (strstr(model,"v") !=0){
                   10300:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   10301:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   10302:       return 1;
                   10303:     }
1.187     brouard  10304:     strcpy(modelsav,model); 
                   10305:     if ((strpt=strstr(model,"age*age")) !=0){
                   10306:       printf(" strpt=%s, model=%s\n",strpt, model);
                   10307:       if(strpt != model){
1.234     brouard  10308:        printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  10309:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  10310:  corresponding column of parameters.\n",model);
1.234     brouard  10311:        fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  10312:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  10313:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  10314:        return 1;
1.225     brouard  10315:       }
1.187     brouard  10316:       nagesqr=1;
                   10317:       if (strstr(model,"+age*age") !=0)
1.234     brouard  10318:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  10319:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  10320:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  10321:       else 
1.234     brouard  10322:        substrchaine(modelsav, model, "age*age");
1.187     brouard  10323:     }else
                   10324:       nagesqr=0;
                   10325:     if (strlen(modelsav) >1){
                   10326:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   10327:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224     brouard  10328:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  10329:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  10330:                     * cst, age and age*age 
                   10331:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   10332:       /* including age products which are counted in cptcovage.
                   10333:        * but the covariates which are products must be treated 
                   10334:        * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  10335:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   10336:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.225     brouard  10337:       
                   10338:       
1.187     brouard  10339:       /*   Design
                   10340:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   10341:        *  <          ncovcol=8                >
                   10342:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   10343:        *   k=  1    2      3       4     5       6      7        8
                   10344:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   10345:        *  covar[k,i], value of kth covariate if not including age for individual i:
1.224     brouard  10346:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   10347:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  10348:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   10349:        *  Tage[++cptcovage]=k
                   10350:        *       if products, new covar are created after ncovcol with k1
                   10351:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   10352:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   10353:        *  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
                   10354:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   10355:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   10356:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   10357:        *  <          ncovcol=8                >
                   10358:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   10359:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   10360:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
1.319     brouard  10361:        * p Tvar[1]@12={2,   1,     3,      3,  11,     10,     8,       8,   7,   8,   5,  6}
1.187     brouard  10362:        * p Tprod[1]@2={                         6, 5}
                   10363:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   10364:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   10365:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1.319     brouard  10366:        *How to reorganize? Tvars(orted)
1.187     brouard  10367:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   10368:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   10369:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   10370:        * Struct []
                   10371:        */
1.225     brouard  10372:       
1.187     brouard  10373:       /* This loop fills the array Tvar from the string 'model'.*/
                   10374:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   10375:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   10376:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   10377:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   10378:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   10379:       /*       k=1 Tvar[1]=2 (from V2) */
                   10380:       /*       k=5 Tvar[5] */
                   10381:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  10382:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  10383:       /*       } */
1.198     brouard  10384:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  10385:       /*
                   10386:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  10387:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   10388:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   10389:       }
1.187     brouard  10390:       cptcovage=0;
1.319     brouard  10391:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model line */
                   10392:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' cutl from left to right
                   10393:                                         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" */
                   10394:        if (nbocc(modelsav,'+')==0)
                   10395:          strcpy(strb,modelsav); /* and analyzes it */
1.234     brouard  10396:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   10397:        /*scanf("%d",i);*/
1.319     brouard  10398:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V5*age+ V4+V3*age strb=V3*age */
                   10399:          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  10400:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   10401:            /* covar is not filled and then is empty */
                   10402:            cptcovprod--;
                   10403:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
1.319     brouard  10404:            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  10405:            Typevar[k]=1;  /* 1 for age product */
1.319     brouard  10406:            cptcovage++; /* Counts the number of covariates which include age as a product */
                   10407:            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  10408:            /*printf("stre=%s ", stre);*/
                   10409:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   10410:            cptcovprod--;
                   10411:            cutl(stre,strb,strc,'V');
                   10412:            Tvar[k]=atoi(stre);
                   10413:            Typevar[k]=1;  /* 1 for age product */
                   10414:            cptcovage++;
                   10415:            Tage[cptcovage]=k;
                   10416:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   10417:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   10418:            cptcovn++;
                   10419:            cptcovprodnoage++;k1++;
                   10420:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   10421:            Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* For model-covariate k tells which data-covariate to use but
                   10422:                                                because this model-covariate is a construction we invent a new column
                   10423:                                                which is after existing variables ncovcol+nqv+ntv+nqtv + k1
1.319     brouard  10424:                                                If already ncovcol=4 and model=V2 + V1 +V1*V4 +age*V3 +V3*V2
                   10425:                                                thus after V4 we invent V5 and V6 because age*V3 will be computed in 4
                   10426:                                                Tvar[3=V1*V4]=4+1=5 Tvar[5=V3*V2]=4 + 2= 6, Tvar[4=age*V3]=4 etc */
1.234     brouard  10427:            Typevar[k]=2;  /* 2 for double fixed dummy covariates */
                   10428:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   10429:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
1.319     brouard  10430:            Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 */
1.234     brouard  10431:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
1.330     brouard  10432:            Tvardk[k][1] =atoi(strc); /* m 1 for V1*/
1.234     brouard  10433:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
1.330     brouard  10434:            Tvardk[k][2] =atoi(stre); /* n 4 for V4*/
1.234     brouard  10435:            k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   10436:            /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   10437:            /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
1.225     brouard  10438:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
1.234     brouard  10439:            /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   10440:            for (i=1; i<=lastobs;i++){
                   10441:              /* Computes the new covariate which is a product of
                   10442:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   10443:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   10444:            }
                   10445:          } /* End age is not in the model */
                   10446:        } /* End if model includes a product */
1.319     brouard  10447:        else { /* not a product */
1.234     brouard  10448:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   10449:          /*  scanf("%d",i);*/
                   10450:          cutl(strd,strc,strb,'V');
                   10451:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   10452:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   10453:          Tvar[k]=atoi(strd);
                   10454:          Typevar[k]=0;  /* 0 for simple covariates */
                   10455:        }
                   10456:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  10457:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  10458:                                  scanf("%d",i);*/
1.187     brouard  10459:       } /* end of loop + on total covariates */
                   10460:     } /* end if strlen(modelsave == 0) age*age might exist */
                   10461:   } /* end if strlen(model == 0) */
1.136     brouard  10462:   
                   10463:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   10464:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  10465:   
1.136     brouard  10466:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  10467:      printf("cptcovprod=%d ", cptcovprod);
                   10468:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   10469:      scanf("%d ",i);*/
                   10470: 
                   10471: 
1.230     brouard  10472: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   10473:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  10474: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   10475:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   10476:    k =           1    2   3     4       5       6      7      8        9
                   10477:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
1.319     brouard  10478:    Typevar[k]=   0    0   0     2       1       0      2      1        0
1.227     brouard  10479:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   10480:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   10481:          Tmodelind[combination of covar]=k;
1.225     brouard  10482: */  
                   10483: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  10484:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  10485:   /* 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  10486:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.318     brouard  10487:   printf("Model=1+age+%s\n\
1.227     brouard  10488: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   10489: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   10490: 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  10491:   fprintf(ficlog,"Model=1+age+%s\n\
1.227     brouard  10492: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   10493: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   10494: 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  10495:   for(k=-1;k<=cptcovt; k++){ Fixed[k]=0; Dummy[k]=0;}
1.234     brouard  10496:   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 */
                   10497:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  10498:       Fixed[k]= 0;
                   10499:       Dummy[k]= 0;
1.225     brouard  10500:       ncoveff++;
1.232     brouard  10501:       ncovf++;
1.234     brouard  10502:       nsd++;
                   10503:       modell[k].maintype= FTYPE;
                   10504:       TvarsD[nsd]=Tvar[k];
                   10505:       TvarsDind[nsd]=k;
1.330     brouard  10506:       TnsdVar[Tvar[k]]=nsd;
1.234     brouard  10507:       TvarF[ncovf]=Tvar[k];
                   10508:       TvarFind[ncovf]=k;
                   10509:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   10510:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   10511:     }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /* Product of fixed dummy (<=ncovcol) covariates */
                   10512:       Fixed[k]= 0;
                   10513:       Dummy[k]= 0;
                   10514:       ncoveff++;
                   10515:       ncovf++;
                   10516:       modell[k].maintype= FTYPE;
                   10517:       TvarF[ncovf]=Tvar[k];
1.330     brouard  10518:       /* TnsdVar[Tvar[k]]=nsd; */ /* To be done */
1.234     brouard  10519:       TvarFind[ncovf]=k;
1.230     brouard  10520:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  10521:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.240     brouard  10522:     }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  10523:       Fixed[k]= 0;
                   10524:       Dummy[k]= 1;
1.230     brouard  10525:       nqfveff++;
1.234     brouard  10526:       modell[k].maintype= FTYPE;
                   10527:       modell[k].subtype= FQ;
                   10528:       nsq++;
                   10529:       TvarsQ[nsq]=Tvar[k];
                   10530:       TvarsQind[nsq]=k;
1.232     brouard  10531:       ncovf++;
1.234     brouard  10532:       TvarF[ncovf]=Tvar[k];
                   10533:       TvarFind[ncovf]=k;
1.231     brouard  10534:       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  10535:       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  10536:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.227     brouard  10537:       Fixed[k]= 1;
                   10538:       Dummy[k]= 0;
1.225     brouard  10539:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  10540:       modell[k].maintype= VTYPE;
                   10541:       modell[k].subtype= VD;
                   10542:       nsd++;
                   10543:       TvarsD[nsd]=Tvar[k];
                   10544:       TvarsDind[nsd]=k;
1.330     brouard  10545:       TnsdVar[Tvar[k]]=nsd; /* To be verified */
1.234     brouard  10546:       ncovv++; /* Only simple time varying variables */
                   10547:       TvarV[ncovv]=Tvar[k];
1.242     brouard  10548:       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  10549:       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 */
                   10550:       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  10551:       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);
                   10552:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  10553:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.234     brouard  10554:       Fixed[k]= 1;
                   10555:       Dummy[k]= 1;
                   10556:       nqtveff++;
                   10557:       modell[k].maintype= VTYPE;
                   10558:       modell[k].subtype= VQ;
                   10559:       ncovv++; /* Only simple time varying variables */
                   10560:       nsq++;
1.319     brouard  10561:       TvarsQ[nsq]=Tvar[k]; /* k=1 Tvar=5 nsq=1 TvarsQ[1]=5 */
1.234     brouard  10562:       TvarsQind[nsq]=k;
                   10563:       TvarV[ncovv]=Tvar[k];
1.242     brouard  10564:       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  10565:       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 */
                   10566:       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  10567:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   10568:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
                   10569:       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  10570:       printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv);
1.227     brouard  10571:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  10572:       ncova++;
                   10573:       TvarA[ncova]=Tvar[k];
                   10574:       TvarAind[ncova]=k;
1.231     brouard  10575:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  10576:        Fixed[k]= 2;
                   10577:        Dummy[k]= 2;
                   10578:        modell[k].maintype= ATYPE;
                   10579:        modell[k].subtype= APFD;
                   10580:        /* ncoveff++; */
1.227     brouard  10581:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  10582:        Fixed[k]= 2;
                   10583:        Dummy[k]= 3;
                   10584:        modell[k].maintype= ATYPE;
                   10585:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   10586:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  10587:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  10588:        Fixed[k]= 3;
                   10589:        Dummy[k]= 2;
                   10590:        modell[k].maintype= ATYPE;
                   10591:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   10592:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  10593:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  10594:        Fixed[k]= 3;
                   10595:        Dummy[k]= 3;
                   10596:        modell[k].maintype= ATYPE;
                   10597:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   10598:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  10599:       }
                   10600:     }else if (Typevar[k] == 2) {  /* product without age */
                   10601:       k1=Tposprod[k];
                   10602:       if(Tvard[k1][1] <=ncovcol){
1.240     brouard  10603:        if(Tvard[k1][2] <=ncovcol){
                   10604:          Fixed[k]= 1;
                   10605:          Dummy[k]= 0;
                   10606:          modell[k].maintype= FTYPE;
                   10607:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
                   10608:          ncovf++; /* Fixed variables without age */
                   10609:          TvarF[ncovf]=Tvar[k];
                   10610:          TvarFind[ncovf]=k;
                   10611:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10612:          Fixed[k]= 0;  /* or 2 ?*/
                   10613:          Dummy[k]= 1;
                   10614:          modell[k].maintype= FTYPE;
                   10615:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
                   10616:          ncovf++; /* Varying variables without age */
                   10617:          TvarF[ncovf]=Tvar[k];
                   10618:          TvarFind[ncovf]=k;
                   10619:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10620:          Fixed[k]= 1;
                   10621:          Dummy[k]= 0;
                   10622:          modell[k].maintype= VTYPE;
                   10623:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
                   10624:          ncovv++; /* Varying variables without age */
                   10625:          TvarV[ncovv]=Tvar[k];
                   10626:          TvarVind[ncovv]=k;
                   10627:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10628:          Fixed[k]= 1;
                   10629:          Dummy[k]= 1;
                   10630:          modell[k].maintype= VTYPE;
                   10631:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
                   10632:          ncovv++; /* Varying variables without age */
                   10633:          TvarV[ncovv]=Tvar[k];
                   10634:          TvarVind[ncovv]=k;
                   10635:        }
1.227     brouard  10636:       }else if(Tvard[k1][1] <=ncovcol+nqv){
1.240     brouard  10637:        if(Tvard[k1][2] <=ncovcol){
                   10638:          Fixed[k]= 0;  /* or 2 ?*/
                   10639:          Dummy[k]= 1;
                   10640:          modell[k].maintype= FTYPE;
                   10641:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
                   10642:          ncovf++; /* Fixed variables without age */
                   10643:          TvarF[ncovf]=Tvar[k];
                   10644:          TvarFind[ncovf]=k;
                   10645:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10646:          Fixed[k]= 1;
                   10647:          Dummy[k]= 1;
                   10648:          modell[k].maintype= VTYPE;
                   10649:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
                   10650:          ncovv++; /* Varying variables without age */
                   10651:          TvarV[ncovv]=Tvar[k];
                   10652:          TvarVind[ncovv]=k;
                   10653:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10654:          Fixed[k]= 1;
                   10655:          Dummy[k]= 1;
                   10656:          modell[k].maintype= VTYPE;
                   10657:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
                   10658:          ncovv++; /* Varying variables without age */
                   10659:          TvarV[ncovv]=Tvar[k];
                   10660:          TvarVind[ncovv]=k;
                   10661:          ncovv++; /* Varying variables without age */
                   10662:          TvarV[ncovv]=Tvar[k];
                   10663:          TvarVind[ncovv]=k;
                   10664:        }
1.227     brouard  10665:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){
1.240     brouard  10666:        if(Tvard[k1][2] <=ncovcol){
                   10667:          Fixed[k]= 1;
                   10668:          Dummy[k]= 1;
                   10669:          modell[k].maintype= VTYPE;
                   10670:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
                   10671:          ncovv++; /* Varying variables without age */
                   10672:          TvarV[ncovv]=Tvar[k];
                   10673:          TvarVind[ncovv]=k;
                   10674:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10675:          Fixed[k]= 1;
                   10676:          Dummy[k]= 1;
                   10677:          modell[k].maintype= VTYPE;
                   10678:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
                   10679:          ncovv++; /* Varying variables without age */
                   10680:          TvarV[ncovv]=Tvar[k];
                   10681:          TvarVind[ncovv]=k;
                   10682:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10683:          Fixed[k]= 1;
                   10684:          Dummy[k]= 0;
                   10685:          modell[k].maintype= VTYPE;
                   10686:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
                   10687:          ncovv++; /* Varying variables without age */
                   10688:          TvarV[ncovv]=Tvar[k];
                   10689:          TvarVind[ncovv]=k;
                   10690:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10691:          Fixed[k]= 1;
                   10692:          Dummy[k]= 1;
                   10693:          modell[k].maintype= VTYPE;
                   10694:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
                   10695:          ncovv++; /* Varying variables without age */
                   10696:          TvarV[ncovv]=Tvar[k];
                   10697:          TvarVind[ncovv]=k;
                   10698:        }
1.227     brouard  10699:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  10700:        if(Tvard[k1][2] <=ncovcol){
                   10701:          Fixed[k]= 1;
                   10702:          Dummy[k]= 1;
                   10703:          modell[k].maintype= VTYPE;
                   10704:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
                   10705:          ncovv++; /* Varying variables without age */
                   10706:          TvarV[ncovv]=Tvar[k];
                   10707:          TvarVind[ncovv]=k;
                   10708:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10709:          Fixed[k]= 1;
                   10710:          Dummy[k]= 1;
                   10711:          modell[k].maintype= VTYPE;
                   10712:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
                   10713:          ncovv++; /* Varying variables without age */
                   10714:          TvarV[ncovv]=Tvar[k];
                   10715:          TvarVind[ncovv]=k;
                   10716:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10717:          Fixed[k]= 1;
                   10718:          Dummy[k]= 1;
                   10719:          modell[k].maintype= VTYPE;
                   10720:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
                   10721:          ncovv++; /* Varying variables without age */
                   10722:          TvarV[ncovv]=Tvar[k];
                   10723:          TvarVind[ncovv]=k;
                   10724:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10725:          Fixed[k]= 1;
                   10726:          Dummy[k]= 1;
                   10727:          modell[k].maintype= VTYPE;
                   10728:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
                   10729:          ncovv++; /* Varying variables without age */
                   10730:          TvarV[ncovv]=Tvar[k];
                   10731:          TvarVind[ncovv]=k;
                   10732:        }
1.227     brouard  10733:       }else{
1.240     brouard  10734:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   10735:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   10736:       } /*end k1*/
1.225     brouard  10737:     }else{
1.226     brouard  10738:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   10739:       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  10740:     }
1.227     brouard  10741:     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  10742:     printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype);
1.227     brouard  10743:     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]);
                   10744:   }
                   10745:   /* Searching for doublons in the model */
                   10746:   for(k1=1; k1<= cptcovt;k1++){
                   10747:     for(k2=1; k2 <k1;k2++){
1.285     brouard  10748:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   10749:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  10750:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   10751:          if(Tvar[k1]==Tvar[k2]){
1.285     brouard  10752:            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]);
                   10753:            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  10754:            return(1);
                   10755:          }
                   10756:        }else if (Typevar[k1] ==2){
                   10757:          k3=Tposprod[k1];
                   10758:          k4=Tposprod[k2];
                   10759:          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])) ){
                   10760:            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]]);
                   10761:            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);
                   10762:            return(1);
                   10763:          }
                   10764:        }
1.227     brouard  10765:       }
                   10766:     }
1.225     brouard  10767:   }
                   10768:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   10769:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  10770:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   10771:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.137     brouard  10772:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  10773:   /*endread:*/
1.225     brouard  10774:   printf("Exiting decodemodel: ");
                   10775:   return (1);
1.136     brouard  10776: }
                   10777: 
1.169     brouard  10778: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  10779: {/* Check ages at death */
1.136     brouard  10780:   int i, m;
1.218     brouard  10781:   int firstone=0;
                   10782:   
1.136     brouard  10783:   for (i=1; i<=imx; i++) {
                   10784:     for(m=2; (m<= maxwav); m++) {
                   10785:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   10786:        anint[m][i]=9999;
1.216     brouard  10787:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   10788:          s[m][i]=-1;
1.136     brouard  10789:       }
                   10790:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  10791:        *nberr = *nberr + 1;
1.218     brouard  10792:        if(firstone == 0){
                   10793:          firstone=1;
1.260     brouard  10794:        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  10795:        }
1.262     brouard  10796:        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  10797:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  10798:       }
                   10799:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  10800:        (*nberr)++;
1.259     brouard  10801:        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  10802:        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  10803:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  10804:       }
                   10805:     }
                   10806:   }
                   10807: 
                   10808:   for (i=1; i<=imx; i++)  {
                   10809:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   10810:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  10811:       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  10812:        if (s[m][i] >= nlstate+1) {
1.169     brouard  10813:          if(agedc[i]>0){
                   10814:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  10815:              agev[m][i]=agedc[i];
1.214     brouard  10816:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  10817:            }else {
1.136     brouard  10818:              if ((int)andc[i]!=9999){
                   10819:                nbwarn++;
                   10820:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   10821:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   10822:                agev[m][i]=-1;
                   10823:              }
                   10824:            }
1.169     brouard  10825:          } /* agedc > 0 */
1.214     brouard  10826:        } /* end if */
1.136     brouard  10827:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   10828:                                 years but with the precision of a month */
                   10829:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   10830:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   10831:            agev[m][i]=1;
                   10832:          else if(agev[m][i] < *agemin){ 
                   10833:            *agemin=agev[m][i];
                   10834:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   10835:          }
                   10836:          else if(agev[m][i] >*agemax){
                   10837:            *agemax=agev[m][i];
1.156     brouard  10838:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  10839:          }
                   10840:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   10841:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  10842:        } /* en if 9*/
1.136     brouard  10843:        else { /* =9 */
1.214     brouard  10844:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  10845:          agev[m][i]=1;
                   10846:          s[m][i]=-1;
                   10847:        }
                   10848:       }
1.214     brouard  10849:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  10850:        agev[m][i]=1;
1.214     brouard  10851:       else{
                   10852:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   10853:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   10854:        agev[m][i]=0;
                   10855:       }
                   10856:     } /* End for lastpass */
                   10857:   }
1.136     brouard  10858:     
                   10859:   for (i=1; i<=imx; i++)  {
                   10860:     for(m=firstpass; (m<=lastpass); m++){
                   10861:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  10862:        (*nberr)++;
1.136     brouard  10863:        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);     
                   10864:        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);     
                   10865:        return 1;
                   10866:       }
                   10867:     }
                   10868:   }
                   10869: 
                   10870:   /*for (i=1; i<=imx; i++){
                   10871:   for (m=firstpass; (m<lastpass); m++){
                   10872:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   10873: }
                   10874: 
                   10875: }*/
                   10876: 
                   10877: 
1.139     brouard  10878:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   10879:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  10880: 
                   10881:   return (0);
1.164     brouard  10882:  /* endread:*/
1.136     brouard  10883:     printf("Exiting calandcheckages: ");
                   10884:     return (1);
                   10885: }
                   10886: 
1.172     brouard  10887: #if defined(_MSC_VER)
                   10888: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   10889: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   10890: //#include "stdafx.h"
                   10891: //#include <stdio.h>
                   10892: //#include <tchar.h>
                   10893: //#include <windows.h>
                   10894: //#include <iostream>
                   10895: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   10896: 
                   10897: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   10898: 
                   10899: BOOL IsWow64()
                   10900: {
                   10901:        BOOL bIsWow64 = FALSE;
                   10902: 
                   10903:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   10904:        //  (HANDLE, PBOOL);
                   10905: 
                   10906:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   10907: 
                   10908:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   10909:        const char funcName[] = "IsWow64Process";
                   10910:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   10911:                GetProcAddress(module, funcName);
                   10912: 
                   10913:        if (NULL != fnIsWow64Process)
                   10914:        {
                   10915:                if (!fnIsWow64Process(GetCurrentProcess(),
                   10916:                        &bIsWow64))
                   10917:                        //throw std::exception("Unknown error");
                   10918:                        printf("Unknown error\n");
                   10919:        }
                   10920:        return bIsWow64 != FALSE;
                   10921: }
                   10922: #endif
1.177     brouard  10923: 
1.191     brouard  10924: void syscompilerinfo(int logged)
1.292     brouard  10925: {
                   10926: #include <stdint.h>
                   10927: 
                   10928:   /* #include "syscompilerinfo.h"*/
1.185     brouard  10929:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   10930:    /* /GS /W3 /Gy
                   10931:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   10932:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   10933:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  10934:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   10935:    */ 
                   10936:    /* 64 bits */
1.185     brouard  10937:    /*
                   10938:      /GS /W3 /Gy
                   10939:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   10940:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   10941:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   10942:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   10943:    /* Optimization are useless and O3 is slower than O2 */
                   10944:    /*
                   10945:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   10946:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   10947:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   10948:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   10949:    */
1.186     brouard  10950:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  10951:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   10952:       /PDB:"visual studio
                   10953:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   10954:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   10955:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   10956:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   10957:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   10958:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   10959:       uiAccess='false'"
                   10960:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   10961:       /NOLOGO /TLBID:1
                   10962:    */
1.292     brouard  10963: 
                   10964: 
1.177     brouard  10965: #if defined __INTEL_COMPILER
1.178     brouard  10966: #if defined(__GNUC__)
                   10967:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   10968: #endif
1.177     brouard  10969: #elif defined(__GNUC__) 
1.179     brouard  10970: #ifndef  __APPLE__
1.174     brouard  10971: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  10972: #endif
1.177     brouard  10973:    struct utsname sysInfo;
1.178     brouard  10974:    int cross = CROSS;
                   10975:    if (cross){
                   10976:           printf("Cross-");
1.191     brouard  10977:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  10978:    }
1.174     brouard  10979: #endif
                   10980: 
1.191     brouard  10981:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  10982: #if defined(__clang__)
1.191     brouard  10983:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  10984: #endif
                   10985: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  10986:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  10987: #endif
                   10988: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  10989:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  10990: #endif
                   10991: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  10992:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  10993: #endif
                   10994: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  10995:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  10996: #endif
                   10997: #if defined(_MSC_VER)
1.191     brouard  10998:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  10999: #endif
                   11000: #if defined(__PGI)
1.191     brouard  11001:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  11002: #endif
                   11003: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  11004:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  11005: #endif
1.191     brouard  11006:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  11007:    
1.167     brouard  11008: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   11009: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   11010:     // Windows (x64 and x86)
1.191     brouard  11011:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  11012: #elif __unix__ // all unices, not all compilers
                   11013:     // Unix
1.191     brouard  11014:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  11015: #elif __linux__
                   11016:     // linux
1.191     brouard  11017:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  11018: #elif __APPLE__
1.174     brouard  11019:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  11020:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  11021: #endif
                   11022: 
                   11023: /*  __MINGW32__          */
                   11024: /*  __CYGWIN__  */
                   11025: /* __MINGW64__  */
                   11026: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   11027: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   11028: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   11029: /* _WIN64  // Defined for applications for Win64. */
                   11030: /* _M_X64 // Defined for compilations that target x64 processors. */
                   11031: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  11032: 
1.167     brouard  11033: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  11034:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  11035: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  11036:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  11037: #else
1.191     brouard  11038:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  11039: #endif
                   11040: 
1.169     brouard  11041: #if defined(__GNUC__)
                   11042: # if defined(__GNUC_PATCHLEVEL__)
                   11043: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   11044:                             + __GNUC_MINOR__ * 100 \
                   11045:                             + __GNUC_PATCHLEVEL__)
                   11046: # else
                   11047: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   11048:                             + __GNUC_MINOR__ * 100)
                   11049: # endif
1.174     brouard  11050:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  11051:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  11052: 
                   11053:    if (uname(&sysInfo) != -1) {
                   11054:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  11055:         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  11056:    }
                   11057:    else
                   11058:       perror("uname() error");
1.179     brouard  11059:    //#ifndef __INTEL_COMPILER 
                   11060: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  11061:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  11062:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  11063: #endif
1.169     brouard  11064: #endif
1.172     brouard  11065: 
1.286     brouard  11066:    //   void main ()
1.172     brouard  11067:    //   {
1.169     brouard  11068: #if defined(_MSC_VER)
1.174     brouard  11069:    if (IsWow64()){
1.191     brouard  11070:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   11071:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  11072:    }
                   11073:    else{
1.191     brouard  11074:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   11075:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  11076:    }
1.172     brouard  11077:    //     printf("\nPress Enter to continue...");
                   11078:    //     getchar();
                   11079:    //   }
                   11080: 
1.169     brouard  11081: #endif
                   11082:    
1.167     brouard  11083: 
1.219     brouard  11084: }
1.136     brouard  11085: 
1.219     brouard  11086: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  11087:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.235     brouard  11088:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  11089:   /* double ftolpl = 1.e-10; */
1.180     brouard  11090:   double age, agebase, agelim;
1.203     brouard  11091:   double tot;
1.180     brouard  11092: 
1.202     brouard  11093:   strcpy(filerespl,"PL_");
                   11094:   strcat(filerespl,fileresu);
                   11095:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  11096:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   11097:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  11098:   }
1.288     brouard  11099:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   11100:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  11101:   pstamp(ficrespl);
1.288     brouard  11102:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  11103:   fprintf(ficrespl,"#Age ");
                   11104:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   11105:   fprintf(ficrespl,"\n");
1.180     brouard  11106:   
1.219     brouard  11107:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  11108: 
1.219     brouard  11109:   agebase=ageminpar;
                   11110:   agelim=agemaxpar;
1.180     brouard  11111: 
1.227     brouard  11112:   /* i1=pow(2,ncoveff); */
1.234     brouard  11113:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  11114:   if (cptcovn < 1){i1=1;}
1.180     brouard  11115: 
1.238     brouard  11116:   for(k=1; k<=i1;k++){ /* For each combination k of dummy covariates in the model */
                   11117:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  11118:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  11119:        continue;
1.235     brouard  11120: 
1.238     brouard  11121:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11122:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   11123:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   11124:       /* k=k+1; */
                   11125:       /* to clean */
                   11126:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   11127:       fprintf(ficrespl,"#******");
                   11128:       printf("#******");
                   11129:       fprintf(ficlog,"#******");
                   11130:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
1.330     brouard  11131:        fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /* Here problem for varying dummy*/
                   11132:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
                   11133:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
1.238     brouard  11134:       }
                   11135:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   11136:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   11137:        fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   11138:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   11139:       }
                   11140:       fprintf(ficrespl,"******\n");
                   11141:       printf("******\n");
                   11142:       fprintf(ficlog,"******\n");
                   11143:       if(invalidvarcomb[k]){
                   11144:        printf("\nCombination (%d) ignored because no case \n",k); 
                   11145:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   11146:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   11147:        continue;
                   11148:       }
1.219     brouard  11149: 
1.238     brouard  11150:       fprintf(ficrespl,"#Age ");
                   11151:       for(j=1;j<=cptcoveff;j++) {
1.330     brouard  11152:        fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
1.238     brouard  11153:       }
                   11154:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   11155:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  11156:     
1.238     brouard  11157:       for (age=agebase; age<=agelim; age++){
                   11158:        /* for (age=agebase; age<=agebase; age++){ */
                   11159:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres);
                   11160:        fprintf(ficrespl,"%.0f ",age );
                   11161:        for(j=1;j<=cptcoveff;j++)
1.330     brouard  11162:          fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
1.238     brouard  11163:        tot=0.;
                   11164:        for(i=1; i<=nlstate;i++){
                   11165:          tot +=  prlim[i][i];
                   11166:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   11167:        }
                   11168:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   11169:       } /* Age */
                   11170:       /* was end of cptcod */
                   11171:     } /* cptcov */
                   11172:   } /* nres */
1.219     brouard  11173:   return 0;
1.180     brouard  11174: }
                   11175: 
1.218     brouard  11176: 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  11177:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  11178:        
                   11179:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   11180:    * at any age between ageminpar and agemaxpar
                   11181:         */
1.235     brouard  11182:   int i, j, k, i1, nres=0 ;
1.217     brouard  11183:   /* double ftolpl = 1.e-10; */
                   11184:   double age, agebase, agelim;
                   11185:   double tot;
1.218     brouard  11186:   /* double ***mobaverage; */
                   11187:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  11188: 
                   11189:   strcpy(fileresplb,"PLB_");
                   11190:   strcat(fileresplb,fileresu);
                   11191:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  11192:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   11193:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  11194:   }
1.288     brouard  11195:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   11196:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  11197:   pstamp(ficresplb);
1.288     brouard  11198:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  11199:   fprintf(ficresplb,"#Age ");
                   11200:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   11201:   fprintf(ficresplb,"\n");
                   11202:   
1.218     brouard  11203:   
                   11204:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   11205:   
                   11206:   agebase=ageminpar;
                   11207:   agelim=agemaxpar;
                   11208:   
                   11209:   
1.227     brouard  11210:   i1=pow(2,cptcoveff);
1.218     brouard  11211:   if (cptcovn < 1){i1=1;}
1.227     brouard  11212:   
1.238     brouard  11213:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11214:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  11215:      if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  11216:        continue;
                   11217:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   11218:       fprintf(ficresplb,"#******");
                   11219:       printf("#******");
                   11220:       fprintf(ficlog,"#******");
                   11221:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
1.330     brouard  11222:        fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
                   11223:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
                   11224:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
1.238     brouard  11225:       }
                   11226:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11227:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11228:        fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11229:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11230:       }
                   11231:       fprintf(ficresplb,"******\n");
                   11232:       printf("******\n");
                   11233:       fprintf(ficlog,"******\n");
                   11234:       if(invalidvarcomb[k]){
                   11235:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   11236:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   11237:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   11238:        continue;
                   11239:       }
1.218     brouard  11240:     
1.238     brouard  11241:       fprintf(ficresplb,"#Age ");
                   11242:       for(j=1;j<=cptcoveff;j++) {
1.330     brouard  11243:        fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
1.238     brouard  11244:       }
                   11245:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   11246:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  11247:     
                   11248:     
1.238     brouard  11249:       for (age=agebase; age<=agelim; age++){
                   11250:        /* for (age=agebase; age<=agebase; age++){ */
                   11251:        if(mobilavproj > 0){
                   11252:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   11253:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  11254:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  11255:        }else if (mobilavproj == 0){
                   11256:          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);
                   11257:          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);
                   11258:          exit(1);
                   11259:        }else{
                   11260:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  11261:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  11262:          /* printf("TOTOT\n"); */
                   11263:           /* exit(1); */
1.238     brouard  11264:        }
                   11265:        fprintf(ficresplb,"%.0f ",age );
                   11266:        for(j=1;j<=cptcoveff;j++)
1.330     brouard  11267:          fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
1.238     brouard  11268:        tot=0.;
                   11269:        for(i=1; i<=nlstate;i++){
                   11270:          tot +=  bprlim[i][i];
                   11271:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   11272:        }
                   11273:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   11274:       } /* Age */
                   11275:       /* was end of cptcod */
1.255     brouard  11276:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.238     brouard  11277:     } /* end of any combination */
                   11278:   } /* end of nres */  
1.218     brouard  11279:   /* hBijx(p, bage, fage); */
                   11280:   /* fclose(ficrespijb); */
                   11281:   
                   11282:   return 0;
1.217     brouard  11283: }
1.218     brouard  11284:  
1.180     brouard  11285: int hPijx(double *p, int bage, int fage){
                   11286:     /*------------- h Pij x at various ages ------------*/
                   11287: 
                   11288:   int stepsize;
                   11289:   int agelim;
                   11290:   int hstepm;
                   11291:   int nhstepm;
1.235     brouard  11292:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  11293: 
                   11294:   double agedeb;
                   11295:   double ***p3mat;
                   11296: 
1.201     brouard  11297:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  11298:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   11299:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   11300:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   11301:     }
                   11302:     printf("Computing pij: result on file '%s' \n", filerespij);
                   11303:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   11304:   
                   11305:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   11306:     /*if (stepm<=24) stepsize=2;*/
                   11307: 
                   11308:     agelim=AGESUP;
                   11309:     hstepm=stepsize*YEARM; /* Every year of age */
                   11310:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
1.218     brouard  11311:                
1.180     brouard  11312:     /* hstepm=1;   aff par mois*/
                   11313:     pstamp(ficrespij);
                   11314:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
1.227     brouard  11315:     i1= pow(2,cptcoveff);
1.218     brouard  11316:                /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11317:                /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   11318:                /*      k=k+1;  */
1.235     brouard  11319:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   11320:     for(k=1; k<=i1;k++){
1.253     brouard  11321:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  11322:        continue;
1.183     brouard  11323:       fprintf(ficrespij,"\n#****** ");
1.227     brouard  11324:       for(j=1;j<=cptcoveff;j++) 
1.330     brouard  11325:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
1.235     brouard  11326:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   11327:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   11328:        fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   11329:       }
1.183     brouard  11330:       fprintf(ficrespij,"******\n");
                   11331:       
                   11332:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   11333:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   11334:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   11335:        
                   11336:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  11337:        
1.183     brouard  11338:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11339:        oldm=oldms;savm=savms;
1.235     brouard  11340:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
1.183     brouard  11341:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   11342:        for(i=1; i<=nlstate;i++)
                   11343:          for(j=1; j<=nlstate+ndeath;j++)
                   11344:            fprintf(ficrespij," %1d-%1d",i,j);
                   11345:        fprintf(ficrespij,"\n");
                   11346:        for (h=0; h<=nhstepm; h++){
                   11347:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   11348:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  11349:          for(i=1; i<=nlstate;i++)
                   11350:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  11351:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  11352:          fprintf(ficrespij,"\n");
                   11353:        }
1.183     brouard  11354:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11355:        fprintf(ficrespij,"\n");
                   11356:       }
1.180     brouard  11357:       /*}*/
                   11358:     }
1.218     brouard  11359:     return 0;
1.180     brouard  11360: }
1.218     brouard  11361:  
                   11362:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  11363:     /*------------- h Bij x at various ages ------------*/
                   11364: 
                   11365:   int stepsize;
1.218     brouard  11366:   /* int agelim; */
                   11367:        int ageminl;
1.217     brouard  11368:   int hstepm;
                   11369:   int nhstepm;
1.238     brouard  11370:   int h, i, i1, j, k, nres;
1.218     brouard  11371:        
1.217     brouard  11372:   double agedeb;
                   11373:   double ***p3mat;
1.218     brouard  11374:        
                   11375:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   11376:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   11377:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   11378:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   11379:   }
                   11380:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   11381:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   11382:   
                   11383:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   11384:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  11385:   
1.218     brouard  11386:   /* agelim=AGESUP; */
1.289     brouard  11387:   ageminl=AGEINF; /* was 30 */
1.218     brouard  11388:   hstepm=stepsize*YEARM; /* Every year of age */
                   11389:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   11390:   
                   11391:   /* hstepm=1;   aff par mois*/
                   11392:   pstamp(ficrespijb);
1.255     brouard  11393:   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  11394:   i1= pow(2,cptcoveff);
1.218     brouard  11395:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11396:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   11397:   /*   k=k+1;  */
1.238     brouard  11398:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11399:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  11400:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  11401:        continue;
                   11402:       fprintf(ficrespijb,"\n#****** ");
                   11403:       for(j=1;j<=cptcoveff;j++)
1.330     brouard  11404:        fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
1.238     brouard  11405:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11406:        fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11407:       }
                   11408:       fprintf(ficrespijb,"******\n");
1.264     brouard  11409:       if(invalidvarcomb[k]){  /* Is it necessary here? */
1.238     brouard  11410:        fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   11411:        continue;
                   11412:       }
                   11413:       
                   11414:       /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   11415:       for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   11416:        /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
1.297     brouard  11417:        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 */
                   11418:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
1.238     brouard  11419:        
                   11420:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
                   11421:        
1.266     brouard  11422:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   11423:        /* and memory limitations if stepm is small */
                   11424: 
1.238     brouard  11425:        /* oldm=oldms;savm=savms; */
                   11426:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.325     brouard  11427:        hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);/* Bug valgrind */
1.238     brouard  11428:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
1.255     brouard  11429:        fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
1.217     brouard  11430:        for(i=1; i<=nlstate;i++)
                   11431:          for(j=1; j<=nlstate+ndeath;j++)
1.238     brouard  11432:            fprintf(ficrespijb," %1d-%1d",i,j);
1.217     brouard  11433:        fprintf(ficrespijb,"\n");
1.238     brouard  11434:        for (h=0; h<=nhstepm; h++){
                   11435:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   11436:          fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   11437:          /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
                   11438:          for(i=1; i<=nlstate;i++)
                   11439:            for(j=1; j<=nlstate+ndeath;j++)
1.325     brouard  11440:              fprintf(ficrespijb," %.5f", p3mat[i][j][h]);/* Bug valgrind */
1.238     brouard  11441:          fprintf(ficrespijb,"\n");
                   11442:        }
                   11443:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11444:        fprintf(ficrespijb,"\n");
                   11445:       } /* end age deb */
                   11446:     } /* end combination */
                   11447:   } /* end nres */
1.218     brouard  11448:   return 0;
                   11449:  } /*  hBijx */
1.217     brouard  11450: 
1.180     brouard  11451: 
1.136     brouard  11452: /***********************************************/
                   11453: /**************** Main Program *****************/
                   11454: /***********************************************/
                   11455: 
                   11456: int main(int argc, char *argv[])
                   11457: {
                   11458: #ifdef GSL
                   11459:   const gsl_multimin_fminimizer_type *T;
                   11460:   size_t iteri = 0, it;
                   11461:   int rval = GSL_CONTINUE;
                   11462:   int status = GSL_SUCCESS;
                   11463:   double ssval;
                   11464: #endif
                   11465:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  11466:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   11467:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  11468:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  11469:   int jj, ll, li, lj, lk;
1.136     brouard  11470:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  11471:   int num_filled;
1.136     brouard  11472:   int itimes;
                   11473:   int NDIM=2;
                   11474:   int vpopbased=0;
1.235     brouard  11475:   int nres=0;
1.258     brouard  11476:   int endishere=0;
1.277     brouard  11477:   int noffset=0;
1.274     brouard  11478:   int ncurrv=0; /* Temporary variable */
                   11479:   
1.164     brouard  11480:   char ca[32], cb[32];
1.136     brouard  11481:   /*  FILE *fichtm; *//* Html File */
                   11482:   /* FILE *ficgp;*/ /*Gnuplot File */
                   11483:   struct stat info;
1.191     brouard  11484:   double agedeb=0.;
1.194     brouard  11485: 
                   11486:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  11487:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  11488: 
1.165     brouard  11489:   double fret;
1.191     brouard  11490:   double dum=0.; /* Dummy variable */
1.136     brouard  11491:   double ***p3mat;
1.218     brouard  11492:   /* double ***mobaverage; */
1.319     brouard  11493:   double wald;
1.164     brouard  11494: 
                   11495:   char line[MAXLINE];
1.197     brouard  11496:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   11497: 
1.234     brouard  11498:   char  modeltemp[MAXLINE];
1.230     brouard  11499:   char resultline[MAXLINE];
                   11500:   
1.136     brouard  11501:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  11502:   char *tok, *val; /* pathtot */
1.290     brouard  11503:   int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs declared globally ;*/
1.195     brouard  11504:   int c,  h , cpt, c2;
1.191     brouard  11505:   int jl=0;
                   11506:   int i1, j1, jk, stepsize=0;
1.194     brouard  11507:   int count=0;
                   11508: 
1.164     brouard  11509:   int *tab; 
1.136     brouard  11510:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  11511:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   11512:   /* double anprojf, mprojf, jprojf; */
                   11513:   /* double jintmean,mintmean,aintmean;   */
                   11514:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   11515:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   11516:   double yrfproj= 10.0; /* Number of years of forward projections */
                   11517:   double yrbproj= 10.0; /* Number of years of backward projections */
                   11518:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  11519:   int mobilav=0,popforecast=0;
1.191     brouard  11520:   int hstepm=0, nhstepm=0;
1.136     brouard  11521:   int agemortsup;
                   11522:   float  sumlpop=0.;
                   11523:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   11524:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   11525: 
1.191     brouard  11526:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  11527:   double ftolpl=FTOL;
                   11528:   double **prlim;
1.217     brouard  11529:   double **bprlim;
1.317     brouard  11530:   double ***param; /* Matrix of parameters, param[i][j][k] param=ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel) 
                   11531:                     state of origin, state of destination including death, for each covariate: constante, age, and V1 V2 etc. */
1.251     brouard  11532:   double ***paramstart; /* Matrix of starting parameter values */
                   11533:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  11534:   double **matcov; /* Matrix of covariance */
1.203     brouard  11535:   double **hess; /* Hessian matrix */
1.136     brouard  11536:   double ***delti3; /* Scale */
                   11537:   double *delti; /* Scale */
                   11538:   double ***eij, ***vareij;
                   11539:   double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  11540: 
1.136     brouard  11541:   double *epj, vepp;
1.164     brouard  11542: 
1.273     brouard  11543:   double dateprev1, dateprev2;
1.296     brouard  11544:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   11545:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   11546: 
1.217     brouard  11547: 
1.136     brouard  11548:   double **ximort;
1.145     brouard  11549:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  11550:   int *dcwave;
                   11551: 
1.164     brouard  11552:   char z[1]="c";
1.136     brouard  11553: 
                   11554:   /*char  *strt;*/
                   11555:   char strtend[80];
1.126     brouard  11556: 
1.164     brouard  11557: 
1.126     brouard  11558: /*   setlocale (LC_ALL, ""); */
                   11559: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   11560: /*   textdomain (PACKAGE); */
                   11561: /*   setlocale (LC_CTYPE, ""); */
                   11562: /*   setlocale (LC_MESSAGES, ""); */
                   11563: 
                   11564:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  11565:   rstart_time = time(NULL);  
                   11566:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   11567:   start_time = *localtime(&rstart_time);
1.126     brouard  11568:   curr_time=start_time;
1.157     brouard  11569:   /*tml = *localtime(&start_time.tm_sec);*/
                   11570:   /* strcpy(strstart,asctime(&tml)); */
                   11571:   strcpy(strstart,asctime(&start_time));
1.126     brouard  11572: 
                   11573: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  11574: /*  tp.tm_sec = tp.tm_sec +86400; */
                   11575: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  11576: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   11577: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   11578: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  11579: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  11580: /*   strt=asctime(&tmg); */
                   11581: /*   printf("Time(after) =%s",strstart);  */
                   11582: /*  (void) time (&time_value);
                   11583: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   11584: *  tm = *localtime(&time_value);
                   11585: *  strstart=asctime(&tm);
                   11586: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   11587: */
                   11588: 
                   11589:   nberr=0; /* Number of errors and warnings */
                   11590:   nbwarn=0;
1.184     brouard  11591: #ifdef WIN32
                   11592:   _getcwd(pathcd, size);
                   11593: #else
1.126     brouard  11594:   getcwd(pathcd, size);
1.184     brouard  11595: #endif
1.191     brouard  11596:   syscompilerinfo(0);
1.196     brouard  11597:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  11598:   if(argc <=1){
                   11599:     printf("\nEnter the parameter file name: ");
1.205     brouard  11600:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   11601:       printf("ERROR Empty parameter file name\n");
                   11602:       goto end;
                   11603:     }
1.126     brouard  11604:     i=strlen(pathr);
                   11605:     if(pathr[i-1]=='\n')
                   11606:       pathr[i-1]='\0';
1.156     brouard  11607:     i=strlen(pathr);
1.205     brouard  11608:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  11609:       pathr[i-1]='\0';
1.205     brouard  11610:     }
                   11611:     i=strlen(pathr);
                   11612:     if( i==0 ){
                   11613:       printf("ERROR Empty parameter file name\n");
                   11614:       goto end;
                   11615:     }
                   11616:     for (tok = pathr; tok != NULL; ){
1.126     brouard  11617:       printf("Pathr |%s|\n",pathr);
                   11618:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   11619:       printf("val= |%s| pathr=%s\n",val,pathr);
                   11620:       strcpy (pathtot, val);
                   11621:       if(pathr[0] == '\0') break; /* Dirty */
                   11622:     }
                   11623:   }
1.281     brouard  11624:   else if (argc<=2){
                   11625:     strcpy(pathtot,argv[1]);
                   11626:   }
1.126     brouard  11627:   else{
                   11628:     strcpy(pathtot,argv[1]);
1.281     brouard  11629:     strcpy(z,argv[2]);
                   11630:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  11631:   }
                   11632:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   11633:   /*cygwin_split_path(pathtot,path,optionfile);
                   11634:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   11635:   /* cutv(path,optionfile,pathtot,'\\');*/
                   11636: 
                   11637:   /* Split argv[0], imach program to get pathimach */
                   11638:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   11639:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   11640:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   11641:  /*   strcpy(pathimach,argv[0]); */
                   11642:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   11643:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   11644:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  11645: #ifdef WIN32
                   11646:   _chdir(path); /* Can be a relative path */
                   11647:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   11648: #else
1.126     brouard  11649:   chdir(path); /* Can be a relative path */
1.184     brouard  11650:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   11651: #endif
                   11652:   printf("Current directory %s!\n",pathcd);
1.126     brouard  11653:   strcpy(command,"mkdir ");
                   11654:   strcat(command,optionfilefiname);
                   11655:   if((outcmd=system(command)) != 0){
1.169     brouard  11656:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  11657:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   11658:     /* fclose(ficlog); */
                   11659: /*     exit(1); */
                   11660:   }
                   11661: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   11662: /*     perror("mkdir"); */
                   11663: /*   } */
                   11664: 
                   11665:   /*-------- arguments in the command line --------*/
                   11666: 
1.186     brouard  11667:   /* Main Log file */
1.126     brouard  11668:   strcat(filelog, optionfilefiname);
                   11669:   strcat(filelog,".log");    /* */
                   11670:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   11671:     printf("Problem with logfile %s\n",filelog);
                   11672:     goto end;
                   11673:   }
                   11674:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  11675:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  11676:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   11677:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   11678:  path=%s \n\
                   11679:  optionfile=%s\n\
                   11680:  optionfilext=%s\n\
1.156     brouard  11681:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  11682: 
1.197     brouard  11683:   syscompilerinfo(1);
1.167     brouard  11684: 
1.126     brouard  11685:   printf("Local time (at start):%s",strstart);
                   11686:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   11687:   fflush(ficlog);
                   11688: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  11689: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  11690: 
                   11691:   /* */
                   11692:   strcpy(fileres,"r");
                   11693:   strcat(fileres, optionfilefiname);
1.201     brouard  11694:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  11695:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  11696:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  11697: 
1.186     brouard  11698:   /* Main ---------arguments file --------*/
1.126     brouard  11699: 
                   11700:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  11701:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   11702:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  11703:     fflush(ficlog);
1.149     brouard  11704:     /* goto end; */
                   11705:     exit(70); 
1.126     brouard  11706:   }
                   11707: 
                   11708:   strcpy(filereso,"o");
1.201     brouard  11709:   strcat(filereso,fileresu);
1.126     brouard  11710:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   11711:     printf("Problem with Output resultfile: %s\n", filereso);
                   11712:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   11713:     fflush(ficlog);
                   11714:     goto end;
                   11715:   }
1.278     brouard  11716:       /*-------- Rewriting parameter file ----------*/
                   11717:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   11718:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   11719:   strcat(rfileres,".");    /* */
                   11720:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   11721:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   11722:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   11723:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   11724:     fflush(ficlog);
                   11725:     goto end;
                   11726:   }
                   11727:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  11728: 
1.278     brouard  11729:                                      
1.126     brouard  11730:   /* Reads comments: lines beginning with '#' */
                   11731:   numlinepar=0;
1.277     brouard  11732:   /* Is it a BOM UTF-8 Windows file? */
                   11733:   /* First parameter line */
1.197     brouard  11734:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  11735:     noffset=0;
                   11736:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   11737:     {
                   11738:       noffset=noffset+3;
                   11739:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   11740:     }
1.302     brouard  11741: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   11742:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
1.277     brouard  11743:     {
                   11744:       noffset=noffset+2;
                   11745:       printf("# File is an UTF16BE BOM file\n");
                   11746:     }
                   11747:     else if( line[0] == 0 && line[1] == 0)
                   11748:     {
                   11749:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   11750:        noffset=noffset+4;
                   11751:        printf("# File is an UTF16BE BOM file\n");
                   11752:       }
                   11753:     } else{
                   11754:       ;/*printf(" Not a BOM file\n");*/
                   11755:     }
                   11756:   
1.197     brouard  11757:     /* If line starts with a # it is a comment */
1.277     brouard  11758:     if (line[noffset] == '#') {
1.197     brouard  11759:       numlinepar++;
                   11760:       fputs(line,stdout);
                   11761:       fputs(line,ficparo);
1.278     brouard  11762:       fputs(line,ficres);
1.197     brouard  11763:       fputs(line,ficlog);
                   11764:       continue;
                   11765:     }else
                   11766:       break;
                   11767:   }
                   11768:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   11769:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   11770:     if (num_filled != 5) {
                   11771:       printf("Should be 5 parameters\n");
1.283     brouard  11772:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  11773:     }
1.126     brouard  11774:     numlinepar++;
1.197     brouard  11775:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  11776:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   11777:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   11778:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  11779:   }
                   11780:   /* Second parameter line */
                   11781:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  11782:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   11783:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  11784:     if (line[0] == '#') {
                   11785:       numlinepar++;
1.283     brouard  11786:       printf("%s",line);
                   11787:       fprintf(ficres,"%s",line);
                   11788:       fprintf(ficparo,"%s",line);
                   11789:       fprintf(ficlog,"%s",line);
1.197     brouard  11790:       continue;
                   11791:     }else
                   11792:       break;
                   11793:   }
1.223     brouard  11794:   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", \
                   11795:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   11796:     if (num_filled != 11) {
                   11797:       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  11798:       printf("but line=%s\n",line);
1.283     brouard  11799:       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");
                   11800:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  11801:     }
1.286     brouard  11802:     if( lastpass > maxwav){
                   11803:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   11804:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   11805:       fflush(ficlog);
                   11806:       goto end;
                   11807:     }
                   11808:       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  11809:     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  11810:     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  11811:     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  11812:   }
1.203     brouard  11813:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  11814:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  11815:   /* Third parameter line */
                   11816:   while(fgets(line, MAXLINE, ficpar)) {
                   11817:     /* If line starts with a # it is a comment */
                   11818:     if (line[0] == '#') {
                   11819:       numlinepar++;
1.283     brouard  11820:       printf("%s",line);
                   11821:       fprintf(ficres,"%s",line);
                   11822:       fprintf(ficparo,"%s",line);
                   11823:       fprintf(ficlog,"%s",line);
1.197     brouard  11824:       continue;
                   11825:     }else
                   11826:       break;
                   11827:   }
1.201     brouard  11828:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
1.279     brouard  11829:     if (num_filled != 1){
1.302     brouard  11830:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   11831:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
1.197     brouard  11832:       model[0]='\0';
                   11833:       goto end;
                   11834:     }
                   11835:     else{
                   11836:       if (model[0]=='+'){
                   11837:        for(i=1; i<=strlen(model);i++)
                   11838:          modeltemp[i-1]=model[i];
1.201     brouard  11839:        strcpy(model,modeltemp); 
1.197     brouard  11840:       }
                   11841:     }
1.199     brouard  11842:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  11843:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  11844:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   11845:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   11846:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  11847:   }
                   11848:   /* 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); */
                   11849:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   11850:   /* 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  11851:   /* 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); */
                   11852:   /* 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  11853:   fflush(ficlog);
1.190     brouard  11854:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   11855:   if(model[0]=='#'){
1.279     brouard  11856:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   11857:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   11858:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  11859:     if(mle != -1){
1.279     brouard  11860:       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  11861:       exit(1);
                   11862:     }
                   11863:   }
1.126     brouard  11864:   while((c=getc(ficpar))=='#' && c!= EOF){
                   11865:     ungetc(c,ficpar);
                   11866:     fgets(line, MAXLINE, ficpar);
                   11867:     numlinepar++;
1.195     brouard  11868:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   11869:       z[0]=line[1];
                   11870:     }
                   11871:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  11872:     fputs(line, stdout);
                   11873:     //puts(line);
1.126     brouard  11874:     fputs(line,ficparo);
                   11875:     fputs(line,ficlog);
                   11876:   }
                   11877:   ungetc(c,ficpar);
                   11878: 
                   11879:    
1.290     brouard  11880:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   11881:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   11882:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
                   11883:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /**< Time varying covariate (dummy and quantitative)*/
1.136     brouard  11884:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   11885:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   11886:      v1+v2*age+v2*v3 makes cptcovn = 3
                   11887:   */
                   11888:   if (strlen(model)>1) 
1.187     brouard  11889:     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  11890:   else
1.187     brouard  11891:     ncovmodel=2; /* Constant and age */
1.133     brouard  11892:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   11893:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  11894:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   11895:     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);
                   11896:     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);
                   11897:     fflush(stdout);
                   11898:     fclose (ficlog);
                   11899:     goto end;
                   11900:   }
1.126     brouard  11901:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   11902:   delti=delti3[1][1];
                   11903:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   11904:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  11905: /* We could also provide initial parameters values giving by simple logistic regression 
                   11906:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   11907:       /* for(i=1;i<nlstate;i++){ */
                   11908:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   11909:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   11910:       /* } */
1.126     brouard  11911:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  11912:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   11913:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  11914:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   11915:     fclose (ficparo);
                   11916:     fclose (ficlog);
                   11917:     goto end;
                   11918:     exit(0);
1.220     brouard  11919:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  11920:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  11921:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   11922:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  11923:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   11924:     matcov=matrix(1,npar,1,npar);
1.203     brouard  11925:     hess=matrix(1,npar,1,npar);
1.220     brouard  11926:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  11927:     /* Read guessed parameters */
1.126     brouard  11928:     /* Reads comments: lines beginning with '#' */
                   11929:     while((c=getc(ficpar))=='#' && c!= EOF){
                   11930:       ungetc(c,ficpar);
                   11931:       fgets(line, MAXLINE, ficpar);
                   11932:       numlinepar++;
1.141     brouard  11933:       fputs(line,stdout);
1.126     brouard  11934:       fputs(line,ficparo);
                   11935:       fputs(line,ficlog);
                   11936:     }
                   11937:     ungetc(c,ficpar);
                   11938:     
                   11939:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  11940:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  11941:     for(i=1; i <=nlstate; i++){
1.234     brouard  11942:       j=0;
1.126     brouard  11943:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  11944:        if(jj==i) continue;
                   11945:        j++;
1.292     brouard  11946:        while((c=getc(ficpar))=='#' && c!= EOF){
                   11947:          ungetc(c,ficpar);
                   11948:          fgets(line, MAXLINE, ficpar);
                   11949:          numlinepar++;
                   11950:          fputs(line,stdout);
                   11951:          fputs(line,ficparo);
                   11952:          fputs(line,ficlog);
                   11953:        }
                   11954:        ungetc(c,ficpar);
1.234     brouard  11955:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   11956:        if ((i1 != i) || (j1 != jj)){
                   11957:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  11958: It might be a problem of design; if ncovcol and the model are correct\n \
                   11959: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  11960:          exit(1);
                   11961:        }
                   11962:        fprintf(ficparo,"%1d%1d",i1,j1);
                   11963:        if(mle==1)
                   11964:          printf("%1d%1d",i,jj);
                   11965:        fprintf(ficlog,"%1d%1d",i,jj);
                   11966:        for(k=1; k<=ncovmodel;k++){
                   11967:          fscanf(ficpar," %lf",&param[i][j][k]);
                   11968:          if(mle==1){
                   11969:            printf(" %lf",param[i][j][k]);
                   11970:            fprintf(ficlog," %lf",param[i][j][k]);
                   11971:          }
                   11972:          else
                   11973:            fprintf(ficlog," %lf",param[i][j][k]);
                   11974:          fprintf(ficparo," %lf",param[i][j][k]);
                   11975:        }
                   11976:        fscanf(ficpar,"\n");
                   11977:        numlinepar++;
                   11978:        if(mle==1)
                   11979:          printf("\n");
                   11980:        fprintf(ficlog,"\n");
                   11981:        fprintf(ficparo,"\n");
1.126     brouard  11982:       }
                   11983:     }  
                   11984:     fflush(ficlog);
1.234     brouard  11985:     
1.251     brouard  11986:     /* Reads parameters values */
1.126     brouard  11987:     p=param[1][1];
1.251     brouard  11988:     pstart=paramstart[1][1];
1.126     brouard  11989:     
                   11990:     /* Reads comments: lines beginning with '#' */
                   11991:     while((c=getc(ficpar))=='#' && c!= EOF){
                   11992:       ungetc(c,ficpar);
                   11993:       fgets(line, MAXLINE, ficpar);
                   11994:       numlinepar++;
1.141     brouard  11995:       fputs(line,stdout);
1.126     brouard  11996:       fputs(line,ficparo);
                   11997:       fputs(line,ficlog);
                   11998:     }
                   11999:     ungetc(c,ficpar);
                   12000: 
                   12001:     for(i=1; i <=nlstate; i++){
                   12002:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  12003:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   12004:        if ( (i1-i) * (j1-j) != 0){
                   12005:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   12006:          exit(1);
                   12007:        }
                   12008:        printf("%1d%1d",i,j);
                   12009:        fprintf(ficparo,"%1d%1d",i1,j1);
                   12010:        fprintf(ficlog,"%1d%1d",i1,j1);
                   12011:        for(k=1; k<=ncovmodel;k++){
                   12012:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   12013:          printf(" %le",delti3[i][j][k]);
                   12014:          fprintf(ficparo," %le",delti3[i][j][k]);
                   12015:          fprintf(ficlog," %le",delti3[i][j][k]);
                   12016:        }
                   12017:        fscanf(ficpar,"\n");
                   12018:        numlinepar++;
                   12019:        printf("\n");
                   12020:        fprintf(ficparo,"\n");
                   12021:        fprintf(ficlog,"\n");
1.126     brouard  12022:       }
                   12023:     }
                   12024:     fflush(ficlog);
1.234     brouard  12025:     
1.145     brouard  12026:     /* Reads covariance matrix */
1.126     brouard  12027:     delti=delti3[1][1];
1.220     brouard  12028:                
                   12029:                
1.126     brouard  12030:     /* 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  12031:                
1.126     brouard  12032:     /* Reads comments: lines beginning with '#' */
                   12033:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12034:       ungetc(c,ficpar);
                   12035:       fgets(line, MAXLINE, ficpar);
                   12036:       numlinepar++;
1.141     brouard  12037:       fputs(line,stdout);
1.126     brouard  12038:       fputs(line,ficparo);
                   12039:       fputs(line,ficlog);
                   12040:     }
                   12041:     ungetc(c,ficpar);
1.220     brouard  12042:                
1.126     brouard  12043:     matcov=matrix(1,npar,1,npar);
1.203     brouard  12044:     hess=matrix(1,npar,1,npar);
1.131     brouard  12045:     for(i=1; i <=npar; i++)
                   12046:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  12047:                
1.194     brouard  12048:     /* Scans npar lines */
1.126     brouard  12049:     for(i=1; i <=npar; i++){
1.226     brouard  12050:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  12051:       if(count != 3){
1.226     brouard  12052:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  12053: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   12054: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  12055:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  12056: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   12057: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  12058:        exit(1);
1.220     brouard  12059:       }else{
1.226     brouard  12060:        if(mle==1)
                   12061:          printf("%1d%1d%d",i1,j1,jk);
                   12062:       }
                   12063:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   12064:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  12065:       for(j=1; j <=i; j++){
1.226     brouard  12066:        fscanf(ficpar," %le",&matcov[i][j]);
                   12067:        if(mle==1){
                   12068:          printf(" %.5le",matcov[i][j]);
                   12069:        }
                   12070:        fprintf(ficlog," %.5le",matcov[i][j]);
                   12071:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  12072:       }
                   12073:       fscanf(ficpar,"\n");
                   12074:       numlinepar++;
                   12075:       if(mle==1)
1.220     brouard  12076:                                printf("\n");
1.126     brouard  12077:       fprintf(ficlog,"\n");
                   12078:       fprintf(ficparo,"\n");
                   12079:     }
1.194     brouard  12080:     /* End of read covariance matrix npar lines */
1.126     brouard  12081:     for(i=1; i <=npar; i++)
                   12082:       for(j=i+1;j<=npar;j++)
1.226     brouard  12083:        matcov[i][j]=matcov[j][i];
1.126     brouard  12084:     
                   12085:     if(mle==1)
                   12086:       printf("\n");
                   12087:     fprintf(ficlog,"\n");
                   12088:     
                   12089:     fflush(ficlog);
                   12090:     
                   12091:   }    /* End of mle != -3 */
1.218     brouard  12092:   
1.186     brouard  12093:   /*  Main data
                   12094:    */
1.290     brouard  12095:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   12096:   /* num=lvector(1,n); */
                   12097:   /* moisnais=vector(1,n); */
                   12098:   /* annais=vector(1,n); */
                   12099:   /* moisdc=vector(1,n); */
                   12100:   /* andc=vector(1,n); */
                   12101:   /* weight=vector(1,n); */
                   12102:   /* agedc=vector(1,n); */
                   12103:   /* cod=ivector(1,n); */
                   12104:   /* for(i=1;i<=n;i++){ */
                   12105:   num=lvector(firstobs,lastobs);
                   12106:   moisnais=vector(firstobs,lastobs);
                   12107:   annais=vector(firstobs,lastobs);
                   12108:   moisdc=vector(firstobs,lastobs);
                   12109:   andc=vector(firstobs,lastobs);
                   12110:   weight=vector(firstobs,lastobs);
                   12111:   agedc=vector(firstobs,lastobs);
                   12112:   cod=ivector(firstobs,lastobs);
                   12113:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  12114:     num[i]=0;
                   12115:     moisnais[i]=0;
                   12116:     annais[i]=0;
                   12117:     moisdc[i]=0;
                   12118:     andc[i]=0;
                   12119:     agedc[i]=0;
                   12120:     cod[i]=0;
                   12121:     weight[i]=1.0; /* Equal weights, 1 by default */
                   12122:   }
1.290     brouard  12123:   mint=matrix(1,maxwav,firstobs,lastobs);
                   12124:   anint=matrix(1,maxwav,firstobs,lastobs);
1.325     brouard  12125:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */
                   12126:   printf("BUG ncovmodel=%d NCOVMAX=%d 2**ncovmodel=%f BUG\n",ncovmodel,NCOVMAX,pow(2,ncovmodel));
1.126     brouard  12127:   tab=ivector(1,NCOVMAX);
1.144     brouard  12128:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  12129:   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  12130: 
1.136     brouard  12131:   /* Reads data from file datafile */
                   12132:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   12133:     goto end;
                   12134: 
                   12135:   /* Calculation of the number of parameters from char model */
1.234     brouard  12136:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  12137:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   12138:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   12139:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   12140:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  12141:   */
                   12142:   
                   12143:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   12144:   TvarsDind=ivector(1,NCOVMAX); /*  */
1.330     brouard  12145:   TnsdVar=ivector(1,NCOVMAX); /*  */
1.234     brouard  12146:   TvarsD=ivector(1,NCOVMAX); /*  */
                   12147:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   12148:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  12149:   TvarF=ivector(1,NCOVMAX); /*  */
                   12150:   TvarFind=ivector(1,NCOVMAX); /*  */
                   12151:   TvarV=ivector(1,NCOVMAX); /*  */
                   12152:   TvarVind=ivector(1,NCOVMAX); /*  */
                   12153:   TvarA=ivector(1,NCOVMAX); /*  */
                   12154:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  12155:   TvarFD=ivector(1,NCOVMAX); /*  */
                   12156:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   12157:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   12158:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   12159:   TvarVD=ivector(1,NCOVMAX); /*  */
                   12160:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   12161:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   12162:   TvarVQind=ivector(1,NCOVMAX); /*  */
                   12163: 
1.230     brouard  12164:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  12165:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  12166:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   12167:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   12168:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.137     brouard  12169:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   12170:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   12171:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   12172:   */
                   12173:   /* For model-covariate k tells which data-covariate to use but
                   12174:     because this model-covariate is a construction we invent a new column
                   12175:     ncovcol + k1
                   12176:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   12177:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  12178:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   12179:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  12180:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   12181:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  12182:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  12183:   */
1.145     brouard  12184:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   12185:   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  12186:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   12187:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.330     brouard  12188:   Tvardk=imatrix(1,NCOVMAX,1,2);
1.145     brouard  12189:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  12190:                         4 covariates (3 plus signs)
                   12191:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
1.328     brouard  12192:                           */  
                   12193:   for(i=1;i<NCOVMAX;i++)
                   12194:     Tage[i]=0;
1.230     brouard  12195:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  12196:                                * individual dummy, fixed or varying:
                   12197:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   12198:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  12199:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   12200:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   12201:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   12202:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   12203:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  12204:                                * individual quantitative, fixed or varying:
                   12205:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   12206:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   12207:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.186     brouard  12208: /* Main decodemodel */
                   12209: 
1.187     brouard  12210: 
1.223     brouard  12211:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  12212:     goto end;
                   12213: 
1.137     brouard  12214:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   12215:     nbwarn++;
                   12216:     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); 
                   12217:     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); 
                   12218:   }
1.136     brouard  12219:     /*  if(mle==1){*/
1.137     brouard  12220:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   12221:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  12222:   }
                   12223: 
                   12224:     /*-calculation of age at interview from date of interview and age at death -*/
                   12225:   agev=matrix(1,maxwav,1,imx);
                   12226: 
                   12227:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   12228:     goto end;
                   12229: 
1.126     brouard  12230: 
1.136     brouard  12231:   agegomp=(int)agemin;
1.290     brouard  12232:   free_vector(moisnais,firstobs,lastobs);
                   12233:   free_vector(annais,firstobs,lastobs);
1.126     brouard  12234:   /* free_matrix(mint,1,maxwav,1,n);
                   12235:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  12236:   /* free_vector(moisdc,1,n); */
                   12237:   /* free_vector(andc,1,n); */
1.145     brouard  12238:   /* */
                   12239:   
1.126     brouard  12240:   wav=ivector(1,imx);
1.214     brouard  12241:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   12242:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   12243:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   12244:   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.*/
                   12245:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   12246:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  12247:    
                   12248:   /* Concatenates waves */
1.214     brouard  12249:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   12250:      Death is a valid wave (if date is known).
                   12251:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   12252:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   12253:      and mw[mi+1][i]. dh depends on stepm.
                   12254:   */
                   12255: 
1.126     brouard  12256:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  12257:   /* Concatenates waves */
1.145     brouard  12258:  
1.290     brouard  12259:   free_vector(moisdc,firstobs,lastobs);
                   12260:   free_vector(andc,firstobs,lastobs);
1.215     brouard  12261: 
1.126     brouard  12262:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   12263:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   12264:   ncodemax[1]=1;
1.145     brouard  12265:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  12266:   cptcoveff=0;
1.220     brouard  12267:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
                   12268:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.227     brouard  12269:   }
                   12270:   
                   12271:   ncovcombmax=pow(2,cptcoveff);
                   12272:   invalidvarcomb=ivector(1, ncovcombmax); 
                   12273:   for(i=1;i<ncovcombmax;i++)
                   12274:     invalidvarcomb[i]=0;
                   12275:   
1.211     brouard  12276:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  12277:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  12278:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  12279:   
1.200     brouard  12280:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  12281:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  12282:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  12283:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   12284:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   12285:    * (currently 0 or 1) in the data.
                   12286:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   12287:    * corresponding modality (h,j).
                   12288:    */
                   12289: 
1.145     brouard  12290:   h=0;
                   12291:   /*if (cptcovn > 0) */
1.126     brouard  12292:   m=pow(2,cptcoveff);
                   12293:  
1.144     brouard  12294:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  12295:           * For k=4 covariates, h goes from 1 to m=2**k
                   12296:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   12297:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.329     brouard  12298:           *     h\k   1     2     3     4   *  h-1\k-1  4  3  2  1          
                   12299:           *______________________________   *______________________
                   12300:           *     1 i=1 1 i=1 1 i=1 1 i=1 1   *     0     0  0  0  0 
                   12301:           *     2     2     1     1     1   *     1     0  0  0  1 
                   12302:           *     3 i=2 1     2     1     1   *     2     0  0  1  0 
                   12303:           *     4     2     2     1     1   *     3     0  0  1  1 
                   12304:           *     5 i=3 1 i=2 1     2     1   *     4     0  1  0  0 
                   12305:           *     6     2     1     2     1   *     5     0  1  0  1 
                   12306:           *     7 i=4 1     2     2     1   *     6     0  1  1  0 
                   12307:           *     8     2     2     2     1   *     7     0  1  1  1 
                   12308:           *     9 i=5 1 i=3 1 i=2 1     2   *     8     1  0  0  0 
                   12309:           *    10     2     1     1     2   *     9     1  0  0  1 
                   12310:           *    11 i=6 1     2     1     2   *    10     1  0  1  0 
                   12311:           *    12     2     2     1     2   *    11     1  0  1  1 
                   12312:           *    13 i=7 1 i=4 1     2     2   *    12     1  1  0  0  
                   12313:           *    14     2     1     2     2   *    13     1  1  0  1 
                   12314:           *    15 i=8 1     2     2     2   *    14     1  1  1  0 
                   12315:           *    16     2     2     2     2   *    15     1  1  1  1          
                   12316:           */                                     
1.212     brouard  12317:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  12318:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   12319:      * and the value of each covariate?
                   12320:      * V1=1, V2=1, V3=2, V4=1 ?
                   12321:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   12322:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   12323:      * In order to get the real value in the data, we use nbcode
                   12324:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   12325:      * We are keeping this crazy system in order to be able (in the future?) 
                   12326:      * to have more than 2 values (0 or 1) for a covariate.
                   12327:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   12328:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   12329:      *              bbbbbbbb
                   12330:      *              76543210     
                   12331:      *   h-1        00000101 (6-1=5)
1.219     brouard  12332:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  12333:      *           &
                   12334:      *     1        00000001 (1)
1.219     brouard  12335:      *              00000000        = 1 & ((h-1) >> (k-1))
                   12336:      *          +1= 00000001 =1 
1.211     brouard  12337:      *
                   12338:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   12339:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   12340:      *    >>k'            11
                   12341:      *          &   00000001
                   12342:      *            = 00000001
                   12343:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   12344:      * Reverse h=6 and m=16?
                   12345:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   12346:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   12347:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   12348:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   12349:      * V3=decodtabm(14,3,2**4)=2
                   12350:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   12351:      *(h-1) >> (j-1)    0011 =13 >> 2
                   12352:      *          &1 000000001
                   12353:      *           = 000000001
                   12354:      *         +1= 000000010 =2
                   12355:      *                  2211
                   12356:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   12357:      *                  V3=2
1.220     brouard  12358:                 * codtabm and decodtabm are identical
1.211     brouard  12359:      */
                   12360: 
1.145     brouard  12361: 
                   12362:  free_ivector(Ndum,-1,NCOVMAX);
                   12363: 
                   12364: 
1.126     brouard  12365:     
1.186     brouard  12366:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  12367:   strcpy(optionfilegnuplot,optionfilefiname);
                   12368:   if(mle==-3)
1.201     brouard  12369:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  12370:   strcat(optionfilegnuplot,".gp");
                   12371: 
                   12372:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   12373:     printf("Problem with file %s",optionfilegnuplot);
                   12374:   }
                   12375:   else{
1.204     brouard  12376:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  12377:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  12378:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   12379:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  12380:   }
                   12381:   /*  fclose(ficgp);*/
1.186     brouard  12382: 
                   12383: 
                   12384:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  12385: 
                   12386:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   12387:   if(mle==-3)
1.201     brouard  12388:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  12389:   strcat(optionfilehtm,".htm");
                   12390:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  12391:     printf("Problem with %s \n",optionfilehtm);
                   12392:     exit(0);
1.126     brouard  12393:   }
                   12394: 
                   12395:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   12396:   strcat(optionfilehtmcov,"-cov.htm");
                   12397:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   12398:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   12399:   }
                   12400:   else{
                   12401:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   12402: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  12403: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  12404:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   12405:   }
                   12406: 
1.324     brouard  12407:   fprintf(fichtm,"<html><head>\n<head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n<title>IMaCh %s</title></head>\n <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n<font size=\"3\">Sponsored by Copyright (C)  2002-2015 <a href=http://www.ined.fr>INED</a>-EUROREVES-Institut de longévité-2013-2016-Japan Society for the Promotion of Sciences 日本学術振興会 (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - <a href=https://software.intel.com/en-us>Intel Software 2015-2018</a></font><br>  \
1.204     brouard  12408: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   12409: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  12410: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  12411: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  12412: \n\
                   12413: <hr  size=\"2\" color=\"#EC5E5E\">\
                   12414:  <ul><li><h4>Parameter files</h4>\n\
                   12415:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   12416:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   12417:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   12418:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   12419:  - Date and time at start: %s</ul>\n",\
                   12420:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   12421:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   12422:          fileres,fileres,\
                   12423:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   12424:   fflush(fichtm);
                   12425: 
                   12426:   strcpy(pathr,path);
                   12427:   strcat(pathr,optionfilefiname);
1.184     brouard  12428: #ifdef WIN32
                   12429:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   12430: #else
1.126     brouard  12431:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  12432: #endif
                   12433:          
1.126     brouard  12434:   
1.220     brouard  12435:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   12436:                 and for any valid combination of covariates
1.126     brouard  12437:      and prints on file fileres'p'. */
1.251     brouard  12438:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  12439:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  12440: 
                   12441:   fprintf(fichtm,"\n");
1.286     brouard  12442:   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  12443:          ftol, stepm);
                   12444:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   12445:   ncurrv=1;
                   12446:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   12447:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   12448:   ncurrv=i;
                   12449:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  12450:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  12451:   ncurrv=i;
                   12452:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  12453:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  12454:   ncurrv=i;
                   12455:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   12456:   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", \
                   12457:           nlstate, ndeath, maxwav, mle, weightopt);
                   12458: 
                   12459:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   12460: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   12461: 
                   12462:   
1.317     brouard  12463:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Number of (used) observations=%d <br>\n\
1.126     brouard  12464: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   12465: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  12466:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  12467:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  12468:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   12469:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   12470:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   12471:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  12472: 
1.126     brouard  12473:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   12474:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   12475:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   12476: 
                   12477:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  12478:   /* For mortality only */
1.126     brouard  12479:   if (mle==-3){
1.136     brouard  12480:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  12481:     for(i=1;i<=NDIM;i++)
                   12482:       for(j=1;j<=NDIM;j++)
                   12483:        ximort[i][j]=0.;
1.186     brouard  12484:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  12485:     cens=ivector(firstobs,lastobs);
                   12486:     ageexmed=vector(firstobs,lastobs);
                   12487:     agecens=vector(firstobs,lastobs);
                   12488:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  12489:                
1.126     brouard  12490:     for (i=1; i<=imx; i++){
                   12491:       dcwave[i]=-1;
                   12492:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  12493:        if (s[m][i]>nlstate) {
                   12494:          dcwave[i]=m;
                   12495:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   12496:          break;
                   12497:        }
1.126     brouard  12498:     }
1.226     brouard  12499:     
1.126     brouard  12500:     for (i=1; i<=imx; i++) {
                   12501:       if (wav[i]>0){
1.226     brouard  12502:        ageexmed[i]=agev[mw[1][i]][i];
                   12503:        j=wav[i];
                   12504:        agecens[i]=1.; 
                   12505:        
                   12506:        if (ageexmed[i]> 1 && wav[i] > 0){
                   12507:          agecens[i]=agev[mw[j][i]][i];
                   12508:          cens[i]= 1;
                   12509:        }else if (ageexmed[i]< 1) 
                   12510:          cens[i]= -1;
                   12511:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   12512:          cens[i]=0 ;
1.126     brouard  12513:       }
                   12514:       else cens[i]=-1;
                   12515:     }
                   12516:     
                   12517:     for (i=1;i<=NDIM;i++) {
                   12518:       for (j=1;j<=NDIM;j++)
1.226     brouard  12519:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  12520:     }
                   12521:     
1.302     brouard  12522:     p[1]=0.0268; p[NDIM]=0.083;
                   12523:     /* printf("%lf %lf", p[1], p[2]); */
1.126     brouard  12524:     
                   12525:     
1.136     brouard  12526: #ifdef GSL
                   12527:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  12528: #else
1.126     brouard  12529:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  12530: #endif
1.201     brouard  12531:     strcpy(filerespow,"POW-MORT_"); 
                   12532:     strcat(filerespow,fileresu);
1.126     brouard  12533:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   12534:       printf("Problem with resultfile: %s\n", filerespow);
                   12535:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   12536:     }
1.136     brouard  12537: #ifdef GSL
                   12538:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  12539: #else
1.126     brouard  12540:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  12541: #endif
1.126     brouard  12542:     /*  for (i=1;i<=nlstate;i++)
                   12543:        for(j=1;j<=nlstate+ndeath;j++)
                   12544:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   12545:     */
                   12546:     fprintf(ficrespow,"\n");
1.136     brouard  12547: #ifdef GSL
                   12548:     /* gsl starts here */ 
                   12549:     T = gsl_multimin_fminimizer_nmsimplex;
                   12550:     gsl_multimin_fminimizer *sfm = NULL;
                   12551:     gsl_vector *ss, *x;
                   12552:     gsl_multimin_function minex_func;
                   12553: 
                   12554:     /* Initial vertex size vector */
                   12555:     ss = gsl_vector_alloc (NDIM);
                   12556:     
                   12557:     if (ss == NULL){
                   12558:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   12559:     }
                   12560:     /* Set all step sizes to 1 */
                   12561:     gsl_vector_set_all (ss, 0.001);
                   12562: 
                   12563:     /* Starting point */
1.126     brouard  12564:     
1.136     brouard  12565:     x = gsl_vector_alloc (NDIM);
                   12566:     
                   12567:     if (x == NULL){
                   12568:       gsl_vector_free(ss);
                   12569:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   12570:     }
                   12571:   
                   12572:     /* Initialize method and iterate */
                   12573:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  12574:     /*     gsl_vector_set(x, 0, 0.0268); */
                   12575:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  12576:     gsl_vector_set(x, 0, p[1]);
                   12577:     gsl_vector_set(x, 1, p[2]);
                   12578: 
                   12579:     minex_func.f = &gompertz_f;
                   12580:     minex_func.n = NDIM;
                   12581:     minex_func.params = (void *)&p; /* ??? */
                   12582:     
                   12583:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   12584:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   12585:     
                   12586:     printf("Iterations beginning .....\n\n");
                   12587:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   12588: 
                   12589:     iteri=0;
                   12590:     while (rval == GSL_CONTINUE){
                   12591:       iteri++;
                   12592:       status = gsl_multimin_fminimizer_iterate(sfm);
                   12593:       
                   12594:       if (status) printf("error: %s\n", gsl_strerror (status));
                   12595:       fflush(0);
                   12596:       
                   12597:       if (status) 
                   12598:         break;
                   12599:       
                   12600:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   12601:       ssval = gsl_multimin_fminimizer_size (sfm);
                   12602:       
                   12603:       if (rval == GSL_SUCCESS)
                   12604:         printf ("converged to a local maximum at\n");
                   12605:       
                   12606:       printf("%5d ", iteri);
                   12607:       for (it = 0; it < NDIM; it++){
                   12608:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   12609:       }
                   12610:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   12611:     }
                   12612:     
                   12613:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   12614:     
                   12615:     gsl_vector_free(x); /* initial values */
                   12616:     gsl_vector_free(ss); /* inital step size */
                   12617:     for (it=0; it<NDIM; it++){
                   12618:       p[it+1]=gsl_vector_get(sfm->x,it);
                   12619:       fprintf(ficrespow," %.12lf", p[it]);
                   12620:     }
                   12621:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   12622: #endif
                   12623: #ifdef POWELL
                   12624:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   12625: #endif  
1.126     brouard  12626:     fclose(ficrespow);
                   12627:     
1.203     brouard  12628:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  12629: 
                   12630:     for(i=1; i <=NDIM; i++)
                   12631:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  12632:                                matcov[i][j]=matcov[j][i];
1.126     brouard  12633:     
                   12634:     printf("\nCovariance matrix\n ");
1.203     brouard  12635:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  12636:     for(i=1; i <=NDIM; i++) {
                   12637:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  12638:                                printf("%f ",matcov[i][j]);
                   12639:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  12640:       }
1.203     brouard  12641:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  12642:     }
                   12643:     
                   12644:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  12645:     for (i=1;i<=NDIM;i++) {
1.126     brouard  12646:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  12647:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   12648:     }
1.302     brouard  12649:     lsurv=vector(agegomp,AGESUP);
                   12650:     lpop=vector(agegomp,AGESUP);
                   12651:     tpop=vector(agegomp,AGESUP);
1.126     brouard  12652:     lsurv[agegomp]=100000;
                   12653:     
                   12654:     for (k=agegomp;k<=AGESUP;k++) {
                   12655:       agemortsup=k;
                   12656:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   12657:     }
                   12658:     
                   12659:     for (k=agegomp;k<agemortsup;k++)
                   12660:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   12661:     
                   12662:     for (k=agegomp;k<agemortsup;k++){
                   12663:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   12664:       sumlpop=sumlpop+lpop[k];
                   12665:     }
                   12666:     
                   12667:     tpop[agegomp]=sumlpop;
                   12668:     for (k=agegomp;k<(agemortsup-3);k++){
                   12669:       /*  tpop[k+1]=2;*/
                   12670:       tpop[k+1]=tpop[k]-lpop[k];
                   12671:     }
                   12672:     
                   12673:     
                   12674:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   12675:     for (k=agegomp;k<(agemortsup-2);k++) 
                   12676:       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]);
                   12677:     
                   12678:     
                   12679:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  12680:                ageminpar=50;
                   12681:                agemaxpar=100;
1.194     brouard  12682:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   12683:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   12684: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12685: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   12686:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   12687: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12688: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  12689:     }else{
                   12690:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   12691:                        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  12692:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  12693:                }
1.201     brouard  12694:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  12695:                     stepm, weightopt,\
                   12696:                     model,imx,p,matcov,agemortsup);
                   12697:     
1.302     brouard  12698:     free_vector(lsurv,agegomp,AGESUP);
                   12699:     free_vector(lpop,agegomp,AGESUP);
                   12700:     free_vector(tpop,agegomp,AGESUP);
1.220     brouard  12701:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  12702:     free_ivector(dcwave,firstobs,lastobs);
                   12703:     free_vector(agecens,firstobs,lastobs);
                   12704:     free_vector(ageexmed,firstobs,lastobs);
                   12705:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  12706: #ifdef GSL
1.136     brouard  12707: #endif
1.186     brouard  12708:   } /* Endof if mle==-3 mortality only */
1.205     brouard  12709:   /* Standard  */
                   12710:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   12711:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   12712:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  12713:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  12714:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   12715:     for (k=1; k<=npar;k++)
                   12716:       printf(" %d %8.5f",k,p[k]);
                   12717:     printf("\n");
1.205     brouard  12718:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   12719:       /* mlikeli uses func not funcone */
1.247     brouard  12720:       /* for(i=1;i<nlstate;i++){ */
                   12721:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   12722:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   12723:       /* } */
1.205     brouard  12724:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   12725:     }
                   12726:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   12727:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   12728:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   12729:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   12730:     }
                   12731:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  12732:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   12733:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   12734:     for (k=1; k<=npar;k++)
                   12735:       printf(" %d %8.5f",k,p[k]);
                   12736:     printf("\n");
                   12737:     
                   12738:     /*--------- results files --------------*/
1.283     brouard  12739:     /* 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  12740:     
                   12741:     
                   12742:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  12743:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); /* Printing model equation */
1.126     brouard  12744:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  12745: 
                   12746:     printf("#model=  1      +     age ");
                   12747:     fprintf(ficres,"#model=  1      +     age ");
                   12748:     fprintf(ficlog,"#model=  1      +     age ");
                   12749:     fprintf(fichtm,"\n<ul><li> model=1+age+%s\n \
                   12750: </ul>", model);
                   12751: 
                   12752:     fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">\n");
                   12753:     fprintf(fichtm, "<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   12754:     if(nagesqr==1){
                   12755:       printf("  + age*age  ");
                   12756:       fprintf(ficres,"  + age*age  ");
                   12757:       fprintf(ficlog,"  + age*age  ");
                   12758:       fprintf(fichtm, "<th>+ age*age</th>");
                   12759:     }
                   12760:     for(j=1;j <=ncovmodel-2;j++){
                   12761:       if(Typevar[j]==0) {
                   12762:        printf("  +      V%d  ",Tvar[j]);
                   12763:        fprintf(ficres,"  +      V%d  ",Tvar[j]);
                   12764:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   12765:        fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   12766:       }else if(Typevar[j]==1) {
                   12767:        printf("  +    V%d*age ",Tvar[j]);
                   12768:        fprintf(ficres,"  +    V%d*age ",Tvar[j]);
                   12769:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   12770:        fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   12771:       }else if(Typevar[j]==2) {
                   12772:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   12773:        fprintf(ficres,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   12774:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   12775:        fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   12776:       }
                   12777:     }
                   12778:     printf("\n");
                   12779:     fprintf(ficres,"\n");
                   12780:     fprintf(ficlog,"\n");
                   12781:     fprintf(fichtm, "</tr>");
                   12782:     fprintf(fichtm, "\n");
                   12783:     
                   12784:     
1.126     brouard  12785:     for(i=1,jk=1; i <=nlstate; i++){
                   12786:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  12787:        if (k != i) {
1.319     brouard  12788:          fprintf(fichtm, "<tr>");
1.225     brouard  12789:          printf("%d%d ",i,k);
                   12790:          fprintf(ficlog,"%d%d ",i,k);
                   12791:          fprintf(ficres,"%1d%1d ",i,k);
1.319     brouard  12792:          fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  12793:          for(j=1; j <=ncovmodel; j++){
                   12794:            printf("%12.7f ",p[jk]);
                   12795:            fprintf(ficlog,"%12.7f ",p[jk]);
                   12796:            fprintf(ficres,"%12.7f ",p[jk]);
1.319     brouard  12797:            fprintf(fichtm, "<td>%12.7f</td>",p[jk]);
1.225     brouard  12798:            jk++; 
                   12799:          }
                   12800:          printf("\n");
                   12801:          fprintf(ficlog,"\n");
                   12802:          fprintf(ficres,"\n");
1.319     brouard  12803:          fprintf(fichtm, "</tr>\n");
1.225     brouard  12804:        }
1.126     brouard  12805:       }
                   12806:     }
1.319     brouard  12807:     /* fprintf(fichtm,"</tr>\n"); */
                   12808:     fprintf(fichtm,"</table>\n");
                   12809:     fprintf(fichtm, "\n");
                   12810: 
1.203     brouard  12811:     if(mle != 0){
                   12812:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  12813:       ftolhess=ftol; /* Usually correct */
1.203     brouard  12814:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   12815:       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");
                   12816:       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  12817:       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  12818:       fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">");
                   12819:       fprintf(fichtm, "\n<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   12820:       if(nagesqr==1){
                   12821:        printf("  + age*age  ");
                   12822:        fprintf(ficres,"  + age*age  ");
                   12823:        fprintf(ficlog,"  + age*age  ");
                   12824:        fprintf(fichtm, "<th>+ age*age</th>");
                   12825:       }
                   12826:       for(j=1;j <=ncovmodel-2;j++){
                   12827:        if(Typevar[j]==0) {
                   12828:          printf("  +      V%d  ",Tvar[j]);
                   12829:          fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   12830:        }else if(Typevar[j]==1) {
                   12831:          printf("  +    V%d*age ",Tvar[j]);
                   12832:          fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   12833:        }else if(Typevar[j]==2) {
                   12834:          fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   12835:        }
                   12836:       }
                   12837:       fprintf(fichtm, "</tr>\n");
                   12838:  
1.203     brouard  12839:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  12840:        for(k=1; k <=(nlstate+ndeath); k++){
                   12841:          if (k != i) {
1.319     brouard  12842:            fprintf(fichtm, "<tr valign=top>");
1.225     brouard  12843:            printf("%d%d ",i,k);
                   12844:            fprintf(ficlog,"%d%d ",i,k);
1.319     brouard  12845:            fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  12846:            for(j=1; j <=ncovmodel; j++){
1.319     brouard  12847:              wald=p[jk]/sqrt(matcov[jk][jk]);
1.324     brouard  12848:              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]));
                   12849:              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  12850:              if(fabs(wald) > 1.96){
1.321     brouard  12851:                fprintf(fichtm, "<td><b>%12.7f</b></br> (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
1.319     brouard  12852:              }else{
                   12853:                fprintf(fichtm, "<td>%12.7f (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
                   12854:              }
1.324     brouard  12855:              fprintf(fichtm,"W=%8.3f</br>",wald);
1.319     brouard  12856:              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  12857:              jk++; 
                   12858:            }
                   12859:            printf("\n");
                   12860:            fprintf(ficlog,"\n");
1.319     brouard  12861:            fprintf(fichtm, "</tr>\n");
1.225     brouard  12862:          }
                   12863:        }
1.193     brouard  12864:       }
1.203     brouard  12865:     } /* end of hesscov and Wald tests */
1.319     brouard  12866:     fprintf(fichtm,"</table>\n");
1.225     brouard  12867:     
1.203     brouard  12868:     /*  */
1.126     brouard  12869:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   12870:     printf("# Scales (for hessian or gradient estimation)\n");
                   12871:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   12872:     for(i=1,jk=1; i <=nlstate; i++){
                   12873:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  12874:        if (j!=i) {
                   12875:          fprintf(ficres,"%1d%1d",i,j);
                   12876:          printf("%1d%1d",i,j);
                   12877:          fprintf(ficlog,"%1d%1d",i,j);
                   12878:          for(k=1; k<=ncovmodel;k++){
                   12879:            printf(" %.5e",delti[jk]);
                   12880:            fprintf(ficlog," %.5e",delti[jk]);
                   12881:            fprintf(ficres," %.5e",delti[jk]);
                   12882:            jk++;
                   12883:          }
                   12884:          printf("\n");
                   12885:          fprintf(ficlog,"\n");
                   12886:          fprintf(ficres,"\n");
                   12887:        }
1.126     brouard  12888:       }
                   12889:     }
                   12890:     
                   12891:     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  12892:     if(mle >= 1) /* To big for the screen */
1.126     brouard  12893:       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");
                   12894:     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");
                   12895:     /* # 121 Var(a12)\n\ */
                   12896:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   12897:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   12898:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   12899:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   12900:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   12901:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   12902:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   12903:     
                   12904:     
                   12905:     /* Just to have a covariance matrix which will be more understandable
                   12906:        even is we still don't want to manage dictionary of variables
                   12907:     */
                   12908:     for(itimes=1;itimes<=2;itimes++){
                   12909:       jj=0;
                   12910:       for(i=1; i <=nlstate; i++){
1.225     brouard  12911:        for(j=1; j <=nlstate+ndeath; j++){
                   12912:          if(j==i) continue;
                   12913:          for(k=1; k<=ncovmodel;k++){
                   12914:            jj++;
                   12915:            ca[0]= k+'a'-1;ca[1]='\0';
                   12916:            if(itimes==1){
                   12917:              if(mle>=1)
                   12918:                printf("#%1d%1d%d",i,j,k);
                   12919:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   12920:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   12921:            }else{
                   12922:              if(mle>=1)
                   12923:                printf("%1d%1d%d",i,j,k);
                   12924:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   12925:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   12926:            }
                   12927:            ll=0;
                   12928:            for(li=1;li <=nlstate; li++){
                   12929:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   12930:                if(lj==li) continue;
                   12931:                for(lk=1;lk<=ncovmodel;lk++){
                   12932:                  ll++;
                   12933:                  if(ll<=jj){
                   12934:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   12935:                    if(ll<jj){
                   12936:                      if(itimes==1){
                   12937:                        if(mle>=1)
                   12938:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12939:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12940:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12941:                      }else{
                   12942:                        if(mle>=1)
                   12943:                          printf(" %.5e",matcov[jj][ll]); 
                   12944:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   12945:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   12946:                      }
                   12947:                    }else{
                   12948:                      if(itimes==1){
                   12949:                        if(mle>=1)
                   12950:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   12951:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   12952:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   12953:                      }else{
                   12954:                        if(mle>=1)
                   12955:                          printf(" %.7e",matcov[jj][ll]); 
                   12956:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   12957:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   12958:                      }
                   12959:                    }
                   12960:                  }
                   12961:                } /* end lk */
                   12962:              } /* end lj */
                   12963:            } /* end li */
                   12964:            if(mle>=1)
                   12965:              printf("\n");
                   12966:            fprintf(ficlog,"\n");
                   12967:            fprintf(ficres,"\n");
                   12968:            numlinepar++;
                   12969:          } /* end k*/
                   12970:        } /*end j */
1.126     brouard  12971:       } /* end i */
                   12972:     } /* end itimes */
                   12973:     
                   12974:     fflush(ficlog);
                   12975:     fflush(ficres);
1.225     brouard  12976:     while(fgets(line, MAXLINE, ficpar)) {
                   12977:       /* If line starts with a # it is a comment */
                   12978:       if (line[0] == '#') {
                   12979:        numlinepar++;
                   12980:        fputs(line,stdout);
                   12981:        fputs(line,ficparo);
                   12982:        fputs(line,ficlog);
1.299     brouard  12983:        fputs(line,ficres);
1.225     brouard  12984:        continue;
                   12985:       }else
                   12986:        break;
                   12987:     }
                   12988:     
1.209     brouard  12989:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   12990:     /*   ungetc(c,ficpar); */
                   12991:     /*   fgets(line, MAXLINE, ficpar); */
                   12992:     /*   fputs(line,stdout); */
                   12993:     /*   fputs(line,ficparo); */
                   12994:     /* } */
                   12995:     /* ungetc(c,ficpar); */
1.126     brouard  12996:     
                   12997:     estepm=0;
1.209     brouard  12998:     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  12999:       
                   13000:       if (num_filled != 6) {
                   13001:        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);
                   13002:        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);
                   13003:        goto end;
                   13004:       }
                   13005:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   13006:     }
                   13007:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   13008:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   13009:     
1.209     brouard  13010:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  13011:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   13012:     if (fage <= 2) {
                   13013:       bage = ageminpar;
                   13014:       fage = agemaxpar;
                   13015:     }
                   13016:     
                   13017:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  13018:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   13019:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  13020:                
1.186     brouard  13021:     /* Other stuffs, more or less useful */    
1.254     brouard  13022:     while(fgets(line, MAXLINE, ficpar)) {
                   13023:       /* If line starts with a # it is a comment */
                   13024:       if (line[0] == '#') {
                   13025:        numlinepar++;
                   13026:        fputs(line,stdout);
                   13027:        fputs(line,ficparo);
                   13028:        fputs(line,ficlog);
1.299     brouard  13029:        fputs(line,ficres);
1.254     brouard  13030:        continue;
                   13031:       }else
                   13032:        break;
                   13033:     }
                   13034: 
                   13035:     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){
                   13036:       
                   13037:       if (num_filled != 7) {
                   13038:        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);
                   13039:        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);
                   13040:        goto end;
                   13041:       }
                   13042:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   13043:       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);
                   13044:       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);
                   13045:       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  13046:     }
1.254     brouard  13047: 
                   13048:     while(fgets(line, MAXLINE, ficpar)) {
                   13049:       /* If line starts with a # it is a comment */
                   13050:       if (line[0] == '#') {
                   13051:        numlinepar++;
                   13052:        fputs(line,stdout);
                   13053:        fputs(line,ficparo);
                   13054:        fputs(line,ficlog);
1.299     brouard  13055:        fputs(line,ficres);
1.254     brouard  13056:        continue;
                   13057:       }else
                   13058:        break;
1.126     brouard  13059:     }
                   13060:     
                   13061:     
                   13062:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   13063:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   13064:     
1.254     brouard  13065:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   13066:       if (num_filled != 1) {
                   13067:        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);
                   13068:        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);
                   13069:        goto end;
                   13070:       }
                   13071:       printf("pop_based=%d\n",popbased);
                   13072:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   13073:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   13074:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   13075:     }
                   13076:      
1.258     brouard  13077:     /* Results */
1.307     brouard  13078:     endishere=0;
1.258     brouard  13079:     nresult=0;
1.308     brouard  13080:     parameterline=0;
1.258     brouard  13081:     do{
                   13082:       if(!fgets(line, MAXLINE, ficpar)){
                   13083:        endishere=1;
1.308     brouard  13084:        parameterline=15;
1.258     brouard  13085:       }else if (line[0] == '#') {
                   13086:        /* If line starts with a # it is a comment */
1.254     brouard  13087:        numlinepar++;
                   13088:        fputs(line,stdout);
                   13089:        fputs(line,ficparo);
                   13090:        fputs(line,ficlog);
1.299     brouard  13091:        fputs(line,ficres);
1.254     brouard  13092:        continue;
1.258     brouard  13093:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   13094:        parameterline=11;
1.296     brouard  13095:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  13096:        parameterline=12;
1.307     brouard  13097:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
1.258     brouard  13098:        parameterline=13;
1.307     brouard  13099:       }
1.258     brouard  13100:       else{
                   13101:        parameterline=14;
1.254     brouard  13102:       }
1.308     brouard  13103:       switch (parameterline){ /* =0 only if only comments */
1.258     brouard  13104:       case 11:
1.296     brouard  13105:        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)){
                   13106:                  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  13107:          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);
                   13108:          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);
                   13109:          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);
                   13110:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  13111:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   13112:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  13113:           prvforecast = 1;
                   13114:        } 
                   13115:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.313     brouard  13116:          printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   13117:          fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   13118:          fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  13119:           prvforecast = 2;
                   13120:        }
                   13121:        else {
                   13122:          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);
                   13123:          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);
                   13124:          goto end;
1.258     brouard  13125:        }
1.254     brouard  13126:        break;
1.258     brouard  13127:       case 12:
1.296     brouard  13128:        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)){
                   13129:           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);
                   13130:          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);
                   13131:          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);
                   13132:          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);
                   13133:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  13134:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   13135:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  13136:           prvbackcast = 1;
                   13137:        } 
                   13138:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.313     brouard  13139:          printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   13140:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   13141:          fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  13142:           prvbackcast = 2;
                   13143:        }
                   13144:        else {
                   13145:          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);
                   13146:          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);
                   13147:          goto end;
1.258     brouard  13148:        }
1.230     brouard  13149:        break;
1.258     brouard  13150:       case 13:
1.307     brouard  13151:        num_filled=sscanf(line,"result:%[^\n]\n",resultline);
                   13152:        nresult++; /* Sum of resultlines */
                   13153:        printf("Result %d: result:%s\n",nresult, resultline);
1.318     brouard  13154:        if(nresult > MAXRESULTLINESPONE-1){
                   13155:          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);
                   13156:          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  13157:          goto end;
                   13158:        }
1.310     brouard  13159:        if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.314     brouard  13160:          fprintf(ficparo,"result: %s\n",resultline);
                   13161:          fprintf(ficres,"result: %s\n",resultline);
                   13162:          fprintf(ficlog,"result: %s\n",resultline);
1.310     brouard  13163:        } else
                   13164:          goto end;
1.307     brouard  13165:        break;
                   13166:       case 14:
                   13167:        printf("Error: Unknown command '%s'\n",line);
                   13168:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
1.314     brouard  13169:        if(line[0] == ' ' || line[0] == '\n'){
                   13170:          printf("It should not be an empty line '%s'\n",line);
                   13171:          fprintf(ficlog,"It should not be an empty line '%s'\n",line);
                   13172:        }         
1.307     brouard  13173:        if(ncovmodel >=2 && nresult==0 ){
                   13174:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   13175:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  13176:        }
1.307     brouard  13177:        /* goto end; */
                   13178:        break;
1.308     brouard  13179:       case 15:
                   13180:        printf("End of resultlines.\n");
                   13181:        fprintf(ficlog,"End of resultlines.\n");
                   13182:        break;
                   13183:       default: /* parameterline =0 */
1.307     brouard  13184:        nresult=1;
                   13185:        decoderesult(".",nresult ); /* No covariate */
1.258     brouard  13186:       } /* End switch parameterline */
                   13187:     }while(endishere==0); /* End do */
1.126     brouard  13188:     
1.230     brouard  13189:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  13190:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  13191:     
                   13192:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  13193:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  13194:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  13195: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13196: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  13197:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  13198: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13199: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  13200:     }else{
1.270     brouard  13201:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  13202:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   13203:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   13204:       if(prvforecast==1){
                   13205:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   13206:         jprojd=jproj1;
                   13207:         mprojd=mproj1;
                   13208:         anprojd=anproj1;
                   13209:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   13210:         jprojf=jproj2;
                   13211:         mprojf=mproj2;
                   13212:         anprojf=anproj2;
                   13213:       } else if(prvforecast == 2){
                   13214:         dateprojd=dateintmean;
                   13215:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   13216:         dateprojf=dateintmean+yrfproj;
                   13217:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   13218:       }
                   13219:       if(prvbackcast==1){
                   13220:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   13221:         jbackd=jback1;
                   13222:         mbackd=mback1;
                   13223:         anbackd=anback1;
                   13224:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   13225:         jbackf=jback2;
                   13226:         mbackf=mback2;
                   13227:         anbackf=anback2;
                   13228:       } else if(prvbackcast == 2){
                   13229:         datebackd=dateintmean;
                   13230:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   13231:         datebackf=dateintmean-yrbproj;
                   13232:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   13233:       }
                   13234:       
                   13235:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);
1.220     brouard  13236:     }
                   13237:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  13238:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   13239:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  13240:                
1.225     brouard  13241:     /*------------ free_vector  -------------*/
                   13242:     /*  chdir(path); */
1.220     brouard  13243:                
1.215     brouard  13244:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   13245:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   13246:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   13247:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  13248:     free_lvector(num,firstobs,lastobs);
                   13249:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  13250:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   13251:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   13252:     fclose(ficparo);
                   13253:     fclose(ficres);
1.220     brouard  13254:                
                   13255:                
1.186     brouard  13256:     /* Other results (useful)*/
1.220     brouard  13257:                
                   13258:                
1.126     brouard  13259:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  13260:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   13261:     prlim=matrix(1,nlstate,1,nlstate);
1.209     brouard  13262:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  13263:     fclose(ficrespl);
                   13264: 
                   13265:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  13266:     /*#include "hpijx.h"*/
                   13267:     hPijx(p, bage, fage);
1.145     brouard  13268:     fclose(ficrespij);
1.227     brouard  13269:     
1.220     brouard  13270:     /* ncovcombmax=  pow(2,cptcoveff); */
1.219     brouard  13271:     /*-------------- Variance of one-step probabilities---*/
1.145     brouard  13272:     k=1;
1.126     brouard  13273:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  13274:     
1.269     brouard  13275:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   13276:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   13277:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  13278:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  13279:        for(k=1;k<=ncovcombmax;k++)
                   13280:          probs[i][j][k]=0.;
1.269     brouard  13281:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   13282:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  13283:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  13284:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   13285:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  13286:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  13287:          for(k=1;k<=ncovcombmax;k++)
                   13288:            mobaverages[i][j][k]=0.;
1.219     brouard  13289:       mobaverage=mobaverages;
                   13290:       if (mobilav!=0) {
1.235     brouard  13291:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  13292:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  13293:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   13294:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   13295:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   13296:        }
1.269     brouard  13297:       } else if (mobilavproj !=0) {
1.235     brouard  13298:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  13299:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  13300:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   13301:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   13302:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   13303:        }
1.269     brouard  13304:       }else{
                   13305:        printf("Internal error moving average\n");
                   13306:        fflush(stdout);
                   13307:        exit(1);
1.219     brouard  13308:       }
                   13309:     }/* end if moving average */
1.227     brouard  13310:     
1.126     brouard  13311:     /*---------- Forecasting ------------------*/
1.296     brouard  13312:     if(prevfcast==1){ 
                   13313:       /*   /\*    if(stepm ==1){*\/ */
                   13314:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   13315:       /*This done previously after freqsummary.*/
                   13316:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   13317:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   13318:       
                   13319:       /* } else if (prvforecast==2){ */
                   13320:       /*   /\*    if(stepm ==1){*\/ */
                   13321:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   13322:       /* } */
                   13323:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   13324:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  13325:     }
1.269     brouard  13326: 
1.296     brouard  13327:     /* Prevbcasting */
                   13328:     if(prevbcast==1){
1.219     brouard  13329:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   13330:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   13331:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   13332: 
                   13333:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   13334: 
                   13335:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  13336: 
1.219     brouard  13337:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   13338:       fclose(ficresplb);
                   13339: 
1.222     brouard  13340:       hBijx(p, bage, fage, mobaverage);
                   13341:       fclose(ficrespijb);
1.219     brouard  13342: 
1.296     brouard  13343:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   13344:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   13345:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   13346:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   13347:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   13348:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   13349: 
                   13350:       
1.269     brouard  13351:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  13352: 
                   13353:       
1.269     brouard  13354:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  13355:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   13356:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   13357:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  13358:     }    /* end  Prevbcasting */
1.268     brouard  13359:  
1.186     brouard  13360:  
                   13361:     /* ------ Other prevalence ratios------------ */
1.126     brouard  13362: 
1.215     brouard  13363:     free_ivector(wav,1,imx);
                   13364:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   13365:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   13366:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  13367:                
                   13368:                
1.127     brouard  13369:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  13370:                
1.201     brouard  13371:     strcpy(filerese,"E_");
                   13372:     strcat(filerese,fileresu);
1.126     brouard  13373:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   13374:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   13375:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   13376:     }
1.208     brouard  13377:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   13378:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  13379: 
                   13380:     pstamp(ficreseij);
1.219     brouard  13381:                
1.235     brouard  13382:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   13383:     if (cptcovn < 1){i1=1;}
                   13384:     
                   13385:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   13386:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  13387:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  13388:        continue;
1.219     brouard  13389:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  13390:       printf("\n#****** ");
1.225     brouard  13391:       for(j=1;j<=cptcoveff;j++) {
1.330     brouard  13392:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
                   13393:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
1.235     brouard  13394:       }
                   13395:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   13396:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   13397:        fprintf(ficreseij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
1.219     brouard  13398:       }
                   13399:       fprintf(ficreseij,"******\n");
1.235     brouard  13400:       printf("******\n");
1.219     brouard  13401:       
                   13402:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   13403:       oldm=oldms;savm=savms;
1.330     brouard  13404:       /* 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  13405:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  13406:       
1.219     brouard  13407:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  13408:     }
                   13409:     fclose(ficreseij);
1.208     brouard  13410:     printf("done evsij\n");fflush(stdout);
                   13411:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  13412: 
1.218     brouard  13413:                
1.227     brouard  13414:     /*---------- State-specific expectancies and variances ------------*/
1.218     brouard  13415:                
1.201     brouard  13416:     strcpy(filerest,"T_");
                   13417:     strcat(filerest,fileresu);
1.127     brouard  13418:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   13419:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   13420:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   13421:     }
1.208     brouard  13422:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   13423:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  13424:     strcpy(fileresstde,"STDE_");
                   13425:     strcat(fileresstde,fileresu);
1.126     brouard  13426:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  13427:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   13428:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  13429:     }
1.227     brouard  13430:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   13431:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  13432: 
1.201     brouard  13433:     strcpy(filerescve,"CVE_");
                   13434:     strcat(filerescve,fileresu);
1.126     brouard  13435:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  13436:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   13437:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  13438:     }
1.227     brouard  13439:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   13440:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  13441: 
1.201     brouard  13442:     strcpy(fileresv,"V_");
                   13443:     strcat(fileresv,fileresu);
1.126     brouard  13444:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   13445:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   13446:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   13447:     }
1.227     brouard  13448:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   13449:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  13450: 
1.235     brouard  13451:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   13452:     if (cptcovn < 1){i1=1;}
                   13453:     
                   13454:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   13455:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  13456:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  13457:        continue;
1.321     brouard  13458:       printf("\n# model %s \n#****** Result for:", model);
                   13459:       fprintf(ficrest,"\n# model %s \n#****** Result for:", model);
                   13460:       fprintf(ficlog,"\n# model %s \n#****** Result for:", model);
1.227     brouard  13461:       for(j=1;j<=cptcoveff;j++){ 
1.330     brouard  13462:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
                   13463:        fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
                   13464:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
1.227     brouard  13465:       }
1.235     brouard  13466:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   13467:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   13468:        fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   13469:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   13470:       }        
1.208     brouard  13471:       fprintf(ficrest,"******\n");
1.227     brouard  13472:       fprintf(ficlog,"******\n");
                   13473:       printf("******\n");
1.208     brouard  13474:       
                   13475:       fprintf(ficresstdeij,"\n#****** ");
                   13476:       fprintf(ficrescveij,"\n#****** ");
1.225     brouard  13477:       for(j=1;j<=cptcoveff;j++) {
1.330     brouard  13478:        fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
                   13479:        fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
1.208     brouard  13480:       }
1.235     brouard  13481:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   13482:        fprintf(ficresstdeij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   13483:        fprintf(ficrescveij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   13484:       }        
1.208     brouard  13485:       fprintf(ficresstdeij,"******\n");
                   13486:       fprintf(ficrescveij,"******\n");
                   13487:       
                   13488:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  13489:       /* pstamp(ficresvij); */
1.225     brouard  13490:       for(j=1;j<=cptcoveff;j++) 
1.330     brouard  13491:        fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
1.235     brouard  13492:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   13493:        fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   13494:       }        
1.208     brouard  13495:       fprintf(ficresvij,"******\n");
                   13496:       
                   13497:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   13498:       oldm=oldms;savm=savms;
1.235     brouard  13499:       printf(" cvevsij ");
                   13500:       fprintf(ficlog, " cvevsij ");
                   13501:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  13502:       printf(" end cvevsij \n ");
                   13503:       fprintf(ficlog, " end cvevsij \n ");
                   13504:       
                   13505:       /*
                   13506:        */
                   13507:       /* goto endfree; */
                   13508:       
                   13509:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   13510:       pstamp(ficrest);
                   13511:       
1.269     brouard  13512:       epj=vector(1,nlstate+1);
1.208     brouard  13513:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  13514:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   13515:        cptcod= 0; /* To be deleted */
                   13516:        printf("varevsij vpopbased=%d \n",vpopbased);
                   13517:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  13518:        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  13519:        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 ");
                   13520:        if(vpopbased==1)
                   13521:          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);
                   13522:        else
1.288     brouard  13523:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  13524:        fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
                   13525:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   13526:        fprintf(ficrest,"\n");
                   13527:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  13528:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   13529:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  13530:        for(age=bage; age <=fage ;age++){
1.235     brouard  13531:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  13532:          if (vpopbased==1) {
                   13533:            if(mobilav ==0){
                   13534:              for(i=1; i<=nlstate;i++)
                   13535:                prlim[i][i]=probs[(int)age][i][k];
                   13536:            }else{ /* mobilav */ 
                   13537:              for(i=1; i<=nlstate;i++)
                   13538:                prlim[i][i]=mobaverage[(int)age][i][k];
                   13539:            }
                   13540:          }
1.219     brouard  13541:          
1.227     brouard  13542:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   13543:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   13544:          /* printf(" age %4.0f ",age); */
                   13545:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   13546:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   13547:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   13548:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   13549:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   13550:            }
                   13551:            epj[nlstate+1] +=epj[j];
                   13552:          }
                   13553:          /* printf(" age %4.0f \n",age); */
1.219     brouard  13554:          
1.227     brouard  13555:          for(i=1, vepp=0.;i <=nlstate;i++)
                   13556:            for(j=1;j <=nlstate;j++)
                   13557:              vepp += vareij[i][j][(int)age];
                   13558:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   13559:          for(j=1;j <=nlstate;j++){
                   13560:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   13561:          }
                   13562:          fprintf(ficrest,"\n");
                   13563:        }
1.208     brouard  13564:       } /* End vpopbased */
1.269     brouard  13565:       free_vector(epj,1,nlstate+1);
1.208     brouard  13566:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   13567:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  13568:       printf("done selection\n");fflush(stdout);
                   13569:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  13570:       
1.235     brouard  13571:     } /* End k selection */
1.227     brouard  13572: 
                   13573:     printf("done State-specific expectancies\n");fflush(stdout);
                   13574:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   13575: 
1.288     brouard  13576:     /* variance-covariance of forward period prevalence*/
1.269     brouard  13577:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  13578: 
1.227     brouard  13579:     
1.290     brouard  13580:     free_vector(weight,firstobs,lastobs);
1.330     brouard  13581:     free_imatrix(Tvardk,1,NCOVMAX,1,2);
1.227     brouard  13582:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  13583:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   13584:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   13585:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   13586:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  13587:     free_ivector(tab,1,NCOVMAX);
                   13588:     fclose(ficresstdeij);
                   13589:     fclose(ficrescveij);
                   13590:     fclose(ficresvij);
                   13591:     fclose(ficrest);
                   13592:     fclose(ficpar);
                   13593:     
                   13594:     
1.126     brouard  13595:     /*---------- End : free ----------------*/
1.219     brouard  13596:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  13597:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   13598:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  13599:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   13600:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  13601:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  13602:   /* endfree:*/
                   13603:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   13604:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   13605:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.290     brouard  13606:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs);
                   13607:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   13608:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   13609:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  13610:   free_matrix(matcov,1,npar,1,npar);
                   13611:   free_matrix(hess,1,npar,1,npar);
                   13612:   /*free_vector(delti,1,npar);*/
                   13613:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   13614:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  13615:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  13616:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   13617:   
                   13618:   free_ivector(ncodemax,1,NCOVMAX);
                   13619:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   13620:   free_ivector(Dummy,-1,NCOVMAX);
                   13621:   free_ivector(Fixed,-1,NCOVMAX);
1.238     brouard  13622:   free_ivector(DummyV,1,NCOVMAX);
                   13623:   free_ivector(FixedV,1,NCOVMAX);
1.227     brouard  13624:   free_ivector(Typevar,-1,NCOVMAX);
                   13625:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  13626:   free_ivector(TvarsQ,1,NCOVMAX);
                   13627:   free_ivector(TvarsQind,1,NCOVMAX);
                   13628:   free_ivector(TvarsD,1,NCOVMAX);
1.330     brouard  13629:   free_ivector(TnsdVar,1,NCOVMAX);
1.234     brouard  13630:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  13631:   free_ivector(TvarFD,1,NCOVMAX);
                   13632:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  13633:   free_ivector(TvarF,1,NCOVMAX);
                   13634:   free_ivector(TvarFind,1,NCOVMAX);
                   13635:   free_ivector(TvarV,1,NCOVMAX);
                   13636:   free_ivector(TvarVind,1,NCOVMAX);
                   13637:   free_ivector(TvarA,1,NCOVMAX);
                   13638:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  13639:   free_ivector(TvarFQ,1,NCOVMAX);
                   13640:   free_ivector(TvarFQind,1,NCOVMAX);
                   13641:   free_ivector(TvarVD,1,NCOVMAX);
                   13642:   free_ivector(TvarVDind,1,NCOVMAX);
                   13643:   free_ivector(TvarVQ,1,NCOVMAX);
                   13644:   free_ivector(TvarVQind,1,NCOVMAX);
1.230     brouard  13645:   free_ivector(Tvarsel,1,NCOVMAX);
                   13646:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  13647:   free_ivector(Tposprod,1,NCOVMAX);
                   13648:   free_ivector(Tprod,1,NCOVMAX);
                   13649:   free_ivector(Tvaraff,1,NCOVMAX);
                   13650:   free_ivector(invalidvarcomb,1,ncovcombmax);
                   13651:   free_ivector(Tage,1,NCOVMAX);
                   13652:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  13653:   free_ivector(TmodelInvind,1,NCOVMAX);
                   13654:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.227     brouard  13655:   
                   13656:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   13657:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  13658:   fflush(fichtm);
                   13659:   fflush(ficgp);
                   13660:   
1.227     brouard  13661:   
1.126     brouard  13662:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  13663:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   13664:     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  13665:   }else{
                   13666:     printf("End of Imach\n");
                   13667:     fprintf(ficlog,"End of Imach\n");
                   13668:   }
                   13669:   printf("See log file on %s\n",filelog);
                   13670:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  13671:   /*(void) gettimeofday(&end_time,&tzp);*/
                   13672:   rend_time = time(NULL);  
                   13673:   end_time = *localtime(&rend_time);
                   13674:   /* tml = *localtime(&end_time.tm_sec); */
                   13675:   strcpy(strtend,asctime(&end_time));
1.126     brouard  13676:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   13677:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  13678:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  13679:   
1.157     brouard  13680:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   13681:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   13682:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  13683:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   13684: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   13685:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   13686:   fclose(fichtm);
                   13687:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   13688:   fclose(fichtmcov);
                   13689:   fclose(ficgp);
                   13690:   fclose(ficlog);
                   13691:   /*------ End -----------*/
1.227     brouard  13692:   
1.281     brouard  13693: 
                   13694: /* Executes gnuplot */
1.227     brouard  13695:   
                   13696:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  13697: #ifdef WIN32
1.227     brouard  13698:   if (_chdir(pathcd) != 0)
                   13699:     printf("Can't move to directory %s!\n",path);
                   13700:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  13701: #else
1.227     brouard  13702:     if(chdir(pathcd) != 0)
                   13703:       printf("Can't move to directory %s!\n", path);
                   13704:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  13705: #endif 
1.126     brouard  13706:     printf("Current directory %s!\n",pathcd);
                   13707:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   13708:   sprintf(plotcmd,"gnuplot");
1.157     brouard  13709: #ifdef _WIN32
1.126     brouard  13710:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   13711: #endif
                   13712:   if(!stat(plotcmd,&info)){
1.158     brouard  13713:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  13714:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  13715:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  13716:     }else
                   13717:       strcpy(pplotcmd,plotcmd);
1.157     brouard  13718: #ifdef __unix
1.126     brouard  13719:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   13720:     if(!stat(plotcmd,&info)){
1.158     brouard  13721:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  13722:     }else
                   13723:       strcpy(pplotcmd,plotcmd);
                   13724: #endif
                   13725:   }else
                   13726:     strcpy(pplotcmd,plotcmd);
                   13727:   
                   13728:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  13729:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  13730:   strcpy(pplotcmd,plotcmd);
1.227     brouard  13731:   
1.126     brouard  13732:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  13733:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  13734:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  13735:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  13736:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  13737:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  13738:       strcpy(plotcmd,pplotcmd);
                   13739:     }
1.126     brouard  13740:   }
1.158     brouard  13741:   printf(" Successful, please wait...");
1.126     brouard  13742:   while (z[0] != 'q') {
                   13743:     /* chdir(path); */
1.154     brouard  13744:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  13745:     scanf("%s",z);
                   13746: /*     if (z[0] == 'c') system("./imach"); */
                   13747:     if (z[0] == 'e') {
1.158     brouard  13748: #ifdef __APPLE__
1.152     brouard  13749:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  13750: #elif __linux
                   13751:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  13752: #else
1.152     brouard  13753:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  13754: #endif
                   13755:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   13756:       system(pplotcmd);
1.126     brouard  13757:     }
                   13758:     else if (z[0] == 'g') system(plotcmd);
                   13759:     else if (z[0] == 'q') exit(0);
                   13760:   }
1.227     brouard  13761: end:
1.126     brouard  13762:   while (z[0] != 'q') {
1.195     brouard  13763:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  13764:     scanf("%s",z);
                   13765:   }
1.283     brouard  13766:   printf("End\n");
1.282     brouard  13767:   exit(0);
1.126     brouard  13768: }

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