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

1.332   ! brouard     1: /* $Id: imach.c,v 1.331 2022/08/07 05:40:09 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.332   ! brouard     4:   Revision 1.331  2022/08/07 05:40:09  brouard
        !             5:   *** empty log message ***
        !             6: 
1.331     brouard     7:   Revision 1.330  2022/08/06 07:18:25  brouard
                      8:   Summary: last 0.99r31
                      9: 
                     10:   *  imach.c (Module): Version of imach using partly decoderesult to rebuild xpxij function
                     11: 
1.330     brouard    12:   Revision 1.329  2022/08/03 17:29:54  brouard
                     13:   *  imach.c (Module): Many errors in graphs fixed with Vn*age covariates.
                     14: 
1.329     brouard    15:   Revision 1.328  2022/07/27 17:40:48  brouard
                     16:   Summary: valgrind bug fixed by initializing to zero DummyV as well as Tage
                     17: 
1.328     brouard    18:   Revision 1.327  2022/07/27 14:47:35  brouard
                     19:   Summary: Still a problem for one-step probabilities in case of quantitative variables
                     20: 
1.327     brouard    21:   Revision 1.326  2022/07/26 17:33:55  brouard
                     22:   Summary: some test with nres=1
                     23: 
1.326     brouard    24:   Revision 1.325  2022/07/25 14:27:23  brouard
                     25:   Summary: r30
                     26: 
                     27:   * imach.c (Module): Error cptcovn instead of nsd in bmij (was
                     28:   coredumped, revealed by Feiuno, thank you.
                     29: 
1.325     brouard    30:   Revision 1.324  2022/07/23 17:44:26  brouard
                     31:   *** empty log message ***
                     32: 
1.324     brouard    33:   Revision 1.323  2022/07/22 12:30:08  brouard
                     34:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                     35: 
1.323     brouard    36:   Revision 1.322  2022/07/22 12:27:48  brouard
                     37:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                     38: 
1.322     brouard    39:   Revision 1.321  2022/07/22 12:04:24  brouard
                     40:   Summary: r28
                     41: 
                     42:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                     43: 
1.321     brouard    44:   Revision 1.320  2022/06/02 05:10:11  brouard
                     45:   *** empty log message ***
                     46: 
1.320     brouard    47:   Revision 1.319  2022/06/02 04:45:11  brouard
                     48:   * imach.c (Module): Adding the Wald tests from the log to the main
                     49:   htm for better display of the maximum likelihood estimators.
                     50: 
1.319     brouard    51:   Revision 1.318  2022/05/24 08:10:59  brouard
                     52:   * imach.c (Module): Some attempts to find a bug of wrong estimates
                     53:   of confidencce intervals with product in the equation modelC
                     54: 
1.318     brouard    55:   Revision 1.317  2022/05/15 15:06:23  brouard
                     56:   * imach.c (Module):  Some minor improvements
                     57: 
1.317     brouard    58:   Revision 1.316  2022/05/11 15:11:31  brouard
                     59:   Summary: r27
                     60: 
1.316     brouard    61:   Revision 1.315  2022/05/11 15:06:32  brouard
                     62:   *** empty log message ***
                     63: 
1.315     brouard    64:   Revision 1.314  2022/04/13 17:43:09  brouard
                     65:   * imach.c (Module): Adding link to text data files
                     66: 
1.314     brouard    67:   Revision 1.313  2022/04/11 15:57:42  brouard
                     68:   * imach.c (Module): Error in rewriting the 'r' file with yearsfproj or yearsbproj fixed
                     69: 
1.313     brouard    70:   Revision 1.312  2022/04/05 21:24:39  brouard
                     71:   *** empty log message ***
                     72: 
1.312     brouard    73:   Revision 1.311  2022/04/05 21:03:51  brouard
                     74:   Summary: Fixed quantitative covariates
                     75: 
                     76:          Fixed covariates (dummy or quantitative)
                     77:        with missing values have never been allowed but are ERRORS and
                     78:        program quits. Standard deviations of fixed covariates were
                     79:        wrongly computed. Mean and standard deviations of time varying
                     80:        covariates are still not computed.
                     81: 
1.311     brouard    82:   Revision 1.310  2022/03/17 08:45:53  brouard
                     83:   Summary: 99r25
                     84: 
                     85:   Improving detection of errors: result lines should be compatible with
                     86:   the model.
                     87: 
1.310     brouard    88:   Revision 1.309  2021/05/20 12:39:14  brouard
                     89:   Summary: Version 0.99r24
                     90: 
1.309     brouard    91:   Revision 1.308  2021/03/31 13:11:57  brouard
                     92:   Summary: Version 0.99r23
                     93: 
                     94: 
                     95:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
                     96: 
1.308     brouard    97:   Revision 1.307  2021/03/08 18:11:32  brouard
                     98:   Summary: 0.99r22 fixed bug on result:
                     99: 
1.307     brouard   100:   Revision 1.306  2021/02/20 15:44:02  brouard
                    101:   Summary: Version 0.99r21
                    102: 
                    103:   * imach.c (Module): Fix bug on quitting after result lines!
                    104:   (Module): Version 0.99r21
                    105: 
1.306     brouard   106:   Revision 1.305  2021/02/20 15:28:30  brouard
                    107:   * imach.c (Module): Fix bug on quitting after result lines!
                    108: 
1.305     brouard   109:   Revision 1.304  2021/02/12 11:34:20  brouard
                    110:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
                    111: 
1.304     brouard   112:   Revision 1.303  2021/02/11 19:50:15  brouard
                    113:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
                    114: 
1.303     brouard   115:   Revision 1.302  2020/02/22 21:00:05  brouard
                    116:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
                    117:   and life table from the data without any state)
                    118: 
1.302     brouard   119:   Revision 1.301  2019/06/04 13:51:20  brouard
                    120:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                    121: 
1.301     brouard   122:   Revision 1.300  2019/05/22 19:09:45  brouard
                    123:   Summary: version 0.99r19 of May 2019
                    124: 
1.300     brouard   125:   Revision 1.299  2019/05/22 18:37:08  brouard
                    126:   Summary: Cleaned 0.99r19
                    127: 
1.299     brouard   128:   Revision 1.298  2019/05/22 18:19:56  brouard
                    129:   *** empty log message ***
                    130: 
1.298     brouard   131:   Revision 1.297  2019/05/22 17:56:10  brouard
                    132:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                    133: 
1.297     brouard   134:   Revision 1.296  2019/05/20 13:03:18  brouard
                    135:   Summary: Projection syntax simplified
                    136: 
                    137: 
                    138:   We can now start projections, forward or backward, from the mean date
                    139:   of inteviews up to or down to a number of years of projection:
                    140:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                    141:   or
                    142:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                    143:   or
                    144:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                    145:   or
                    146:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                    147: 
1.296     brouard   148:   Revision 1.295  2019/05/18 09:52:50  brouard
                    149:   Summary: doxygen tex bug
                    150: 
1.295     brouard   151:   Revision 1.294  2019/05/16 14:54:33  brouard
                    152:   Summary: There was some wrong lines added
                    153: 
1.294     brouard   154:   Revision 1.293  2019/05/09 15:17:34  brouard
                    155:   *** empty log message ***
                    156: 
1.293     brouard   157:   Revision 1.292  2019/05/09 14:17:20  brouard
                    158:   Summary: Some updates
                    159: 
1.292     brouard   160:   Revision 1.291  2019/05/09 13:44:18  brouard
                    161:   Summary: Before ncovmax
                    162: 
1.291     brouard   163:   Revision 1.290  2019/05/09 13:39:37  brouard
                    164:   Summary: 0.99r18 unlimited number of individuals
                    165: 
                    166:   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.
                    167: 
1.290     brouard   168:   Revision 1.289  2018/12/13 09:16:26  brouard
                    169:   Summary: Bug for young ages (<-30) will be in r17
                    170: 
1.289     brouard   171:   Revision 1.288  2018/05/02 20:58:27  brouard
                    172:   Summary: Some bugs fixed
                    173: 
1.288     brouard   174:   Revision 1.287  2018/05/01 17:57:25  brouard
                    175:   Summary: Bug fixed by providing frequencies only for non missing covariates
                    176: 
1.287     brouard   177:   Revision 1.286  2018/04/27 14:27:04  brouard
                    178:   Summary: some minor bugs
                    179: 
1.286     brouard   180:   Revision 1.285  2018/04/21 21:02:16  brouard
                    181:   Summary: Some bugs fixed, valgrind tested
                    182: 
1.285     brouard   183:   Revision 1.284  2018/04/20 05:22:13  brouard
                    184:   Summary: Computing mean and stdeviation of fixed quantitative variables
                    185: 
1.284     brouard   186:   Revision 1.283  2018/04/19 14:49:16  brouard
                    187:   Summary: Some minor bugs fixed
                    188: 
1.283     brouard   189:   Revision 1.282  2018/02/27 22:50:02  brouard
                    190:   *** empty log message ***
                    191: 
1.282     brouard   192:   Revision 1.281  2018/02/27 19:25:23  brouard
                    193:   Summary: Adding second argument for quitting
                    194: 
1.281     brouard   195:   Revision 1.280  2018/02/21 07:58:13  brouard
                    196:   Summary: 0.99r15
                    197: 
                    198:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                    199: 
1.280     brouard   200:   Revision 1.279  2017/07/20 13:35:01  brouard
                    201:   Summary: temporary working
                    202: 
1.279     brouard   203:   Revision 1.278  2017/07/19 14:09:02  brouard
                    204:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                    205: 
1.278     brouard   206:   Revision 1.277  2017/07/17 08:53:49  brouard
                    207:   Summary: BOM files can be read now
                    208: 
1.277     brouard   209:   Revision 1.276  2017/06/30 15:48:31  brouard
                    210:   Summary: Graphs improvements
                    211: 
1.276     brouard   212:   Revision 1.275  2017/06/30 13:39:33  brouard
                    213:   Summary: Saito's color
                    214: 
1.275     brouard   215:   Revision 1.274  2017/06/29 09:47:08  brouard
                    216:   Summary: Version 0.99r14
                    217: 
1.274     brouard   218:   Revision 1.273  2017/06/27 11:06:02  brouard
                    219:   Summary: More documentation on projections
                    220: 
1.273     brouard   221:   Revision 1.272  2017/06/27 10:22:40  brouard
                    222:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    223: 
1.272     brouard   224:   Revision 1.271  2017/06/27 10:17:50  brouard
                    225:   Summary: Some bug with rint
                    226: 
1.271     brouard   227:   Revision 1.270  2017/05/24 05:45:29  brouard
                    228:   *** empty log message ***
                    229: 
1.270     brouard   230:   Revision 1.269  2017/05/23 08:39:25  brouard
                    231:   Summary: Code into subroutine, cleanings
                    232: 
1.269     brouard   233:   Revision 1.268  2017/05/18 20:09:32  brouard
                    234:   Summary: backprojection and confidence intervals of backprevalence
                    235: 
1.268     brouard   236:   Revision 1.267  2017/05/13 10:25:05  brouard
                    237:   Summary: temporary save for backprojection
                    238: 
1.267     brouard   239:   Revision 1.266  2017/05/13 07:26:12  brouard
                    240:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    241: 
1.266     brouard   242:   Revision 1.265  2017/04/26 16:22:11  brouard
                    243:   Summary: imach 0.99r13 Some bugs fixed
                    244: 
1.265     brouard   245:   Revision 1.264  2017/04/26 06:01:29  brouard
                    246:   Summary: Labels in graphs
                    247: 
1.264     brouard   248:   Revision 1.263  2017/04/24 15:23:15  brouard
                    249:   Summary: to save
                    250: 
1.263     brouard   251:   Revision 1.262  2017/04/18 16:48:12  brouard
                    252:   *** empty log message ***
                    253: 
1.262     brouard   254:   Revision 1.261  2017/04/05 10:14:09  brouard
                    255:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    256: 
1.261     brouard   257:   Revision 1.260  2017/04/04 17:46:59  brouard
                    258:   Summary: Gnuplot indexations fixed (humm)
                    259: 
1.260     brouard   260:   Revision 1.259  2017/04/04 13:01:16  brouard
                    261:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    262: 
1.259     brouard   263:   Revision 1.258  2017/04/03 10:17:47  brouard
                    264:   Summary: Version 0.99r12
                    265: 
                    266:   Some cleanings, conformed with updated documentation.
                    267: 
1.258     brouard   268:   Revision 1.257  2017/03/29 16:53:30  brouard
                    269:   Summary: Temp
                    270: 
1.257     brouard   271:   Revision 1.256  2017/03/27 05:50:23  brouard
                    272:   Summary: Temporary
                    273: 
1.256     brouard   274:   Revision 1.255  2017/03/08 16:02:28  brouard
                    275:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    276: 
1.255     brouard   277:   Revision 1.254  2017/03/08 07:13:00  brouard
                    278:   Summary: Fixing data parameter line
                    279: 
1.254     brouard   280:   Revision 1.253  2016/12/15 11:59:41  brouard
                    281:   Summary: 0.99 in progress
                    282: 
1.253     brouard   283:   Revision 1.252  2016/09/15 21:15:37  brouard
                    284:   *** empty log message ***
                    285: 
1.252     brouard   286:   Revision 1.251  2016/09/15 15:01:13  brouard
                    287:   Summary: not working
                    288: 
1.251     brouard   289:   Revision 1.250  2016/09/08 16:07:27  brouard
                    290:   Summary: continue
                    291: 
1.250     brouard   292:   Revision 1.249  2016/09/07 17:14:18  brouard
                    293:   Summary: Starting values from frequencies
                    294: 
1.249     brouard   295:   Revision 1.248  2016/09/07 14:10:18  brouard
                    296:   *** empty log message ***
                    297: 
1.248     brouard   298:   Revision 1.247  2016/09/02 11:11:21  brouard
                    299:   *** empty log message ***
                    300: 
1.247     brouard   301:   Revision 1.246  2016/09/02 08:49:22  brouard
                    302:   *** empty log message ***
                    303: 
1.246     brouard   304:   Revision 1.245  2016/09/02 07:25:01  brouard
                    305:   *** empty log message ***
                    306: 
1.245     brouard   307:   Revision 1.244  2016/09/02 07:17:34  brouard
                    308:   *** empty log message ***
                    309: 
1.244     brouard   310:   Revision 1.243  2016/09/02 06:45:35  brouard
                    311:   *** empty log message ***
                    312: 
1.243     brouard   313:   Revision 1.242  2016/08/30 15:01:20  brouard
                    314:   Summary: Fixing a lots
                    315: 
1.242     brouard   316:   Revision 1.241  2016/08/29 17:17:25  brouard
                    317:   Summary: gnuplot problem in Back projection to fix
                    318: 
1.241     brouard   319:   Revision 1.240  2016/08/29 07:53:18  brouard
                    320:   Summary: Better
                    321: 
1.240     brouard   322:   Revision 1.239  2016/08/26 15:51:03  brouard
                    323:   Summary: Improvement in Powell output in order to copy and paste
                    324: 
                    325:   Author:
                    326: 
1.239     brouard   327:   Revision 1.238  2016/08/26 14:23:35  brouard
                    328:   Summary: Starting tests of 0.99
                    329: 
1.238     brouard   330:   Revision 1.237  2016/08/26 09:20:19  brouard
                    331:   Summary: to valgrind
                    332: 
1.237     brouard   333:   Revision 1.236  2016/08/25 10:50:18  brouard
                    334:   *** empty log message ***
                    335: 
1.236     brouard   336:   Revision 1.235  2016/08/25 06:59:23  brouard
                    337:   *** empty log message ***
                    338: 
1.235     brouard   339:   Revision 1.234  2016/08/23 16:51:20  brouard
                    340:   *** empty log message ***
                    341: 
1.234     brouard   342:   Revision 1.233  2016/08/23 07:40:50  brouard
                    343:   Summary: not working
                    344: 
1.233     brouard   345:   Revision 1.232  2016/08/22 14:20:21  brouard
                    346:   Summary: not working
                    347: 
1.232     brouard   348:   Revision 1.231  2016/08/22 07:17:15  brouard
                    349:   Summary: not working
                    350: 
1.231     brouard   351:   Revision 1.230  2016/08/22 06:55:53  brouard
                    352:   Summary: Not working
                    353: 
1.230     brouard   354:   Revision 1.229  2016/07/23 09:45:53  brouard
                    355:   Summary: Completing for func too
                    356: 
1.229     brouard   357:   Revision 1.228  2016/07/22 17:45:30  brouard
                    358:   Summary: Fixing some arrays, still debugging
                    359: 
1.227     brouard   360:   Revision 1.226  2016/07/12 18:42:34  brouard
                    361:   Summary: temp
                    362: 
1.226     brouard   363:   Revision 1.225  2016/07/12 08:40:03  brouard
                    364:   Summary: saving but not running
                    365: 
1.225     brouard   366:   Revision 1.224  2016/07/01 13:16:01  brouard
                    367:   Summary: Fixes
                    368: 
1.224     brouard   369:   Revision 1.223  2016/02/19 09:23:35  brouard
                    370:   Summary: temporary
                    371: 
1.223     brouard   372:   Revision 1.222  2016/02/17 08:14:50  brouard
                    373:   Summary: Probably last 0.98 stable version 0.98r6
                    374: 
1.222     brouard   375:   Revision 1.221  2016/02/15 23:35:36  brouard
                    376:   Summary: minor bug
                    377: 
1.220     brouard   378:   Revision 1.219  2016/02/15 00:48:12  brouard
                    379:   *** empty log message ***
                    380: 
1.219     brouard   381:   Revision 1.218  2016/02/12 11:29:23  brouard
                    382:   Summary: 0.99 Back projections
                    383: 
1.218     brouard   384:   Revision 1.217  2015/12/23 17:18:31  brouard
                    385:   Summary: Experimental backcast
                    386: 
1.217     brouard   387:   Revision 1.216  2015/12/18 17:32:11  brouard
                    388:   Summary: 0.98r4 Warning and status=-2
                    389: 
                    390:   Version 0.98r4 is now:
                    391:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    392:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    393:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    394: 
1.216     brouard   395:   Revision 1.215  2015/12/16 08:52:24  brouard
                    396:   Summary: 0.98r4 working
                    397: 
1.215     brouard   398:   Revision 1.214  2015/12/16 06:57:54  brouard
                    399:   Summary: temporary not working
                    400: 
1.214     brouard   401:   Revision 1.213  2015/12/11 18:22:17  brouard
                    402:   Summary: 0.98r4
                    403: 
1.213     brouard   404:   Revision 1.212  2015/11/21 12:47:24  brouard
                    405:   Summary: minor typo
                    406: 
1.212     brouard   407:   Revision 1.211  2015/11/21 12:41:11  brouard
                    408:   Summary: 0.98r3 with some graph of projected cross-sectional
                    409: 
                    410:   Author: Nicolas Brouard
                    411: 
1.211     brouard   412:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   413:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   414:   Summary: Adding ftolpl parameter
                    415:   Author: N Brouard
                    416: 
                    417:   We had difficulties to get smoothed confidence intervals. It was due
                    418:   to the period prevalence which wasn't computed accurately. The inner
                    419:   parameter ftolpl is now an outer parameter of the .imach parameter
                    420:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    421:   computation are long.
                    422: 
1.209     brouard   423:   Revision 1.208  2015/11/17 14:31:57  brouard
                    424:   Summary: temporary
                    425: 
1.208     brouard   426:   Revision 1.207  2015/10/27 17:36:57  brouard
                    427:   *** empty log message ***
                    428: 
1.207     brouard   429:   Revision 1.206  2015/10/24 07:14:11  brouard
                    430:   *** empty log message ***
                    431: 
1.206     brouard   432:   Revision 1.205  2015/10/23 15:50:53  brouard
                    433:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    434: 
1.205     brouard   435:   Revision 1.204  2015/10/01 16:20:26  brouard
                    436:   Summary: Some new graphs of contribution to likelihood
                    437: 
1.204     brouard   438:   Revision 1.203  2015/09/30 17:45:14  brouard
                    439:   Summary: looking at better estimation of the hessian
                    440: 
                    441:   Also a better criteria for convergence to the period prevalence And
                    442:   therefore adding the number of years needed to converge. (The
                    443:   prevalence in any alive state shold sum to one
                    444: 
1.203     brouard   445:   Revision 1.202  2015/09/22 19:45:16  brouard
                    446:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    447: 
1.202     brouard   448:   Revision 1.201  2015/09/15 17:34:58  brouard
                    449:   Summary: 0.98r0
                    450: 
                    451:   - Some new graphs like suvival functions
                    452:   - Some bugs fixed like model=1+age+V2.
                    453: 
1.201     brouard   454:   Revision 1.200  2015/09/09 16:53:55  brouard
                    455:   Summary: Big bug thanks to Flavia
                    456: 
                    457:   Even model=1+age+V2. did not work anymore
                    458: 
1.200     brouard   459:   Revision 1.199  2015/09/07 14:09:23  brouard
                    460:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    461: 
1.199     brouard   462:   Revision 1.198  2015/09/03 07:14:39  brouard
                    463:   Summary: 0.98q5 Flavia
                    464: 
1.198     brouard   465:   Revision 1.197  2015/09/01 18:24:39  brouard
                    466:   *** empty log message ***
                    467: 
1.197     brouard   468:   Revision 1.196  2015/08/18 23:17:52  brouard
                    469:   Summary: 0.98q5
                    470: 
1.196     brouard   471:   Revision 1.195  2015/08/18 16:28:39  brouard
                    472:   Summary: Adding a hack for testing purpose
                    473: 
                    474:   After reading the title, ftol and model lines, if the comment line has
                    475:   a q, starting with #q, the answer at the end of the run is quit. It
                    476:   permits to run test files in batch with ctest. The former workaround was
                    477:   $ echo q | imach foo.imach
                    478: 
1.195     brouard   479:   Revision 1.194  2015/08/18 13:32:00  brouard
                    480:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    481: 
1.194     brouard   482:   Revision 1.193  2015/08/04 07:17:42  brouard
                    483:   Summary: 0.98q4
                    484: 
1.193     brouard   485:   Revision 1.192  2015/07/16 16:49:02  brouard
                    486:   Summary: Fixing some outputs
                    487: 
1.192     brouard   488:   Revision 1.191  2015/07/14 10:00:33  brouard
                    489:   Summary: Some fixes
                    490: 
1.191     brouard   491:   Revision 1.190  2015/05/05 08:51:13  brouard
                    492:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    493: 
                    494:   Fix 1+age+.
                    495: 
1.190     brouard   496:   Revision 1.189  2015/04/30 14:45:16  brouard
                    497:   Summary: 0.98q2
                    498: 
1.189     brouard   499:   Revision 1.188  2015/04/30 08:27:53  brouard
                    500:   *** empty log message ***
                    501: 
1.188     brouard   502:   Revision 1.187  2015/04/29 09:11:15  brouard
                    503:   *** empty log message ***
                    504: 
1.187     brouard   505:   Revision 1.186  2015/04/23 12:01:52  brouard
                    506:   Summary: V1*age is working now, version 0.98q1
                    507: 
                    508:   Some codes had been disabled in order to simplify and Vn*age was
                    509:   working in the optimization phase, ie, giving correct MLE parameters,
                    510:   but, as usual, outputs were not correct and program core dumped.
                    511: 
1.186     brouard   512:   Revision 1.185  2015/03/11 13:26:42  brouard
                    513:   Summary: Inclusion of compile and links command line for Intel Compiler
                    514: 
1.185     brouard   515:   Revision 1.184  2015/03/11 11:52:39  brouard
                    516:   Summary: Back from Windows 8. Intel Compiler
                    517: 
1.184     brouard   518:   Revision 1.183  2015/03/10 20:34:32  brouard
                    519:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    520: 
                    521:   We use directest instead of original Powell test; probably no
                    522:   incidence on the results, but better justifications;
                    523:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    524:   wrong results.
                    525: 
1.183     brouard   526:   Revision 1.182  2015/02/12 08:19:57  brouard
                    527:   Summary: Trying to keep directest which seems simpler and more general
                    528:   Author: Nicolas Brouard
                    529: 
1.182     brouard   530:   Revision 1.181  2015/02/11 23:22:24  brouard
                    531:   Summary: Comments on Powell added
                    532: 
                    533:   Author:
                    534: 
1.181     brouard   535:   Revision 1.180  2015/02/11 17:33:45  brouard
                    536:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    537: 
1.180     brouard   538:   Revision 1.179  2015/01/04 09:57:06  brouard
                    539:   Summary: back to OS/X
                    540: 
1.179     brouard   541:   Revision 1.178  2015/01/04 09:35:48  brouard
                    542:   *** empty log message ***
                    543: 
1.178     brouard   544:   Revision 1.177  2015/01/03 18:40:56  brouard
                    545:   Summary: Still testing ilc32 on OSX
                    546: 
1.177     brouard   547:   Revision 1.176  2015/01/03 16:45:04  brouard
                    548:   *** empty log message ***
                    549: 
1.176     brouard   550:   Revision 1.175  2015/01/03 16:33:42  brouard
                    551:   *** empty log message ***
                    552: 
1.175     brouard   553:   Revision 1.174  2015/01/03 16:15:49  brouard
                    554:   Summary: Still in cross-compilation
                    555: 
1.174     brouard   556:   Revision 1.173  2015/01/03 12:06:26  brouard
                    557:   Summary: trying to detect cross-compilation
                    558: 
1.173     brouard   559:   Revision 1.172  2014/12/27 12:07:47  brouard
                    560:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    561: 
1.172     brouard   562:   Revision 1.171  2014/12/23 13:26:59  brouard
                    563:   Summary: Back from Visual C
                    564: 
                    565:   Still problem with utsname.h on Windows
                    566: 
1.171     brouard   567:   Revision 1.170  2014/12/23 11:17:12  brouard
                    568:   Summary: Cleaning some \%% back to %%
                    569: 
                    570:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    571: 
1.170     brouard   572:   Revision 1.169  2014/12/22 23:08:31  brouard
                    573:   Summary: 0.98p
                    574: 
                    575:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    576: 
1.169     brouard   577:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   578:   Summary: update
1.169     brouard   579: 
1.168     brouard   580:   Revision 1.167  2014/12/22 13:50:56  brouard
                    581:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    582: 
                    583:   Testing on Linux 64
                    584: 
1.167     brouard   585:   Revision 1.166  2014/12/22 11:40:47  brouard
                    586:   *** empty log message ***
                    587: 
1.166     brouard   588:   Revision 1.165  2014/12/16 11:20:36  brouard
                    589:   Summary: After compiling on Visual C
                    590: 
                    591:   * imach.c (Module): Merging 1.61 to 1.162
                    592: 
1.165     brouard   593:   Revision 1.164  2014/12/16 10:52:11  brouard
                    594:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    595: 
                    596:   * imach.c (Module): Merging 1.61 to 1.162
                    597: 
1.164     brouard   598:   Revision 1.163  2014/12/16 10:30:11  brouard
                    599:   * imach.c (Module): Merging 1.61 to 1.162
                    600: 
1.163     brouard   601:   Revision 1.162  2014/09/25 11:43:39  brouard
                    602:   Summary: temporary backup 0.99!
                    603: 
1.162     brouard   604:   Revision 1.1  2014/09/16 11:06:58  brouard
                    605:   Summary: With some code (wrong) for nlopt
                    606: 
                    607:   Author:
                    608: 
                    609:   Revision 1.161  2014/09/15 20:41:41  brouard
                    610:   Summary: Problem with macro SQR on Intel compiler
                    611: 
1.161     brouard   612:   Revision 1.160  2014/09/02 09:24:05  brouard
                    613:   *** empty log message ***
                    614: 
1.160     brouard   615:   Revision 1.159  2014/09/01 10:34:10  brouard
                    616:   Summary: WIN32
                    617:   Author: Brouard
                    618: 
1.159     brouard   619:   Revision 1.158  2014/08/27 17:11:51  brouard
                    620:   *** empty log message ***
                    621: 
1.158     brouard   622:   Revision 1.157  2014/08/27 16:26:55  brouard
                    623:   Summary: Preparing windows Visual studio version
                    624:   Author: Brouard
                    625: 
                    626:   In order to compile on Visual studio, time.h is now correct and time_t
                    627:   and tm struct should be used. difftime should be used but sometimes I
                    628:   just make the differences in raw time format (time(&now).
                    629:   Trying to suppress #ifdef LINUX
                    630:   Add xdg-open for __linux in order to open default browser.
                    631: 
1.157     brouard   632:   Revision 1.156  2014/08/25 20:10:10  brouard
                    633:   *** empty log message ***
                    634: 
1.156     brouard   635:   Revision 1.155  2014/08/25 18:32:34  brouard
                    636:   Summary: New compile, minor changes
                    637:   Author: Brouard
                    638: 
1.155     brouard   639:   Revision 1.154  2014/06/20 17:32:08  brouard
                    640:   Summary: Outputs now all graphs of convergence to period prevalence
                    641: 
1.154     brouard   642:   Revision 1.153  2014/06/20 16:45:46  brouard
                    643:   Summary: If 3 live state, convergence to period prevalence on same graph
                    644:   Author: Brouard
                    645: 
1.153     brouard   646:   Revision 1.152  2014/06/18 17:54:09  brouard
                    647:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    648: 
1.152     brouard   649:   Revision 1.151  2014/06/18 16:43:30  brouard
                    650:   *** empty log message ***
                    651: 
1.151     brouard   652:   Revision 1.150  2014/06/18 16:42:35  brouard
                    653:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    654:   Author: brouard
                    655: 
1.150     brouard   656:   Revision 1.149  2014/06/18 15:51:14  brouard
                    657:   Summary: Some fixes in parameter files errors
                    658:   Author: Nicolas Brouard
                    659: 
1.149     brouard   660:   Revision 1.148  2014/06/17 17:38:48  brouard
                    661:   Summary: Nothing new
                    662:   Author: Brouard
                    663: 
                    664:   Just a new packaging for OS/X version 0.98nS
                    665: 
1.148     brouard   666:   Revision 1.147  2014/06/16 10:33:11  brouard
                    667:   *** empty log message ***
                    668: 
1.147     brouard   669:   Revision 1.146  2014/06/16 10:20:28  brouard
                    670:   Summary: Merge
                    671:   Author: Brouard
                    672: 
                    673:   Merge, before building revised version.
                    674: 
1.146     brouard   675:   Revision 1.145  2014/06/10 21:23:15  brouard
                    676:   Summary: Debugging with valgrind
                    677:   Author: Nicolas Brouard
                    678: 
                    679:   Lot of changes in order to output the results with some covariates
                    680:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    681:   improve the code.
                    682:   No more memory valgrind error but a lot has to be done in order to
                    683:   continue the work of splitting the code into subroutines.
                    684:   Also, decodemodel has been improved. Tricode is still not
                    685:   optimal. nbcode should be improved. Documentation has been added in
                    686:   the source code.
                    687: 
1.144     brouard   688:   Revision 1.143  2014/01/26 09:45:38  brouard
                    689:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    690: 
                    691:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    692:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    693: 
1.143     brouard   694:   Revision 1.142  2014/01/26 03:57:36  brouard
                    695:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    696: 
                    697:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    698: 
1.142     brouard   699:   Revision 1.141  2014/01/26 02:42:01  brouard
                    700:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    701: 
1.141     brouard   702:   Revision 1.140  2011/09/02 10:37:54  brouard
                    703:   Summary: times.h is ok with mingw32 now.
                    704: 
1.140     brouard   705:   Revision 1.139  2010/06/14 07:50:17  brouard
                    706:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    707:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    708: 
1.139     brouard   709:   Revision 1.138  2010/04/30 18:19:40  brouard
                    710:   *** empty log message ***
                    711: 
1.138     brouard   712:   Revision 1.137  2010/04/29 18:11:38  brouard
                    713:   (Module): Checking covariates for more complex models
                    714:   than V1+V2. A lot of change to be done. Unstable.
                    715: 
1.137     brouard   716:   Revision 1.136  2010/04/26 20:30:53  brouard
                    717:   (Module): merging some libgsl code. Fixing computation
                    718:   of likelione (using inter/intrapolation if mle = 0) in order to
                    719:   get same likelihood as if mle=1.
                    720:   Some cleaning of code and comments added.
                    721: 
1.136     brouard   722:   Revision 1.135  2009/10/29 15:33:14  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.135     brouard   725:   Revision 1.134  2009/10/29 13:18:53  brouard
                    726:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    727: 
1.134     brouard   728:   Revision 1.133  2009/07/06 10:21:25  brouard
                    729:   just nforces
                    730: 
1.133     brouard   731:   Revision 1.132  2009/07/06 08:22:05  brouard
                    732:   Many tings
                    733: 
1.132     brouard   734:   Revision 1.131  2009/06/20 16:22:47  brouard
                    735:   Some dimensions resccaled
                    736: 
1.131     brouard   737:   Revision 1.130  2009/05/26 06:44:34  brouard
                    738:   (Module): Max Covariate is now set to 20 instead of 8. A
                    739:   lot of cleaning with variables initialized to 0. Trying to make
                    740:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    741: 
1.130     brouard   742:   Revision 1.129  2007/08/31 13:49:27  lievre
                    743:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    744: 
1.129     lievre    745:   Revision 1.128  2006/06/30 13:02:05  brouard
                    746:   (Module): Clarifications on computing e.j
                    747: 
1.128     brouard   748:   Revision 1.127  2006/04/28 18:11:50  brouard
                    749:   (Module): Yes the sum of survivors was wrong since
                    750:   imach-114 because nhstepm was no more computed in the age
                    751:   loop. Now we define nhstepma in the age loop.
                    752:   (Module): In order to speed up (in case of numerous covariates) we
                    753:   compute health expectancies (without variances) in a first step
                    754:   and then all the health expectancies with variances or standard
                    755:   deviation (needs data from the Hessian matrices) which slows the
                    756:   computation.
                    757:   In the future we should be able to stop the program is only health
                    758:   expectancies and graph are needed without standard deviations.
                    759: 
1.127     brouard   760:   Revision 1.126  2006/04/28 17:23:28  brouard
                    761:   (Module): Yes the sum of survivors was wrong since
                    762:   imach-114 because nhstepm was no more computed in the age
                    763:   loop. Now we define nhstepma in the age loop.
                    764:   Version 0.98h
                    765: 
1.126     brouard   766:   Revision 1.125  2006/04/04 15:20:31  lievre
                    767:   Errors in calculation of health expectancies. Age was not initialized.
                    768:   Forecasting file added.
                    769: 
                    770:   Revision 1.124  2006/03/22 17:13:53  lievre
                    771:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    772:   The log-likelihood is printed in the log file
                    773: 
                    774:   Revision 1.123  2006/03/20 10:52:43  brouard
                    775:   * imach.c (Module): <title> changed, corresponds to .htm file
                    776:   name. <head> headers where missing.
                    777: 
                    778:   * imach.c (Module): Weights can have a decimal point as for
                    779:   English (a comma might work with a correct LC_NUMERIC environment,
                    780:   otherwise the weight is truncated).
                    781:   Modification of warning when the covariates values are not 0 or
                    782:   1.
                    783:   Version 0.98g
                    784: 
                    785:   Revision 1.122  2006/03/20 09:45:41  brouard
                    786:   (Module): Weights can have a decimal point as for
                    787:   English (a comma might work with a correct LC_NUMERIC environment,
                    788:   otherwise the weight is truncated).
                    789:   Modification of warning when the covariates values are not 0 or
                    790:   1.
                    791:   Version 0.98g
                    792: 
                    793:   Revision 1.121  2006/03/16 17:45:01  lievre
                    794:   * imach.c (Module): Comments concerning covariates added
                    795: 
                    796:   * imach.c (Module): refinements in the computation of lli if
                    797:   status=-2 in order to have more reliable computation if stepm is
                    798:   not 1 month. Version 0.98f
                    799: 
                    800:   Revision 1.120  2006/03/16 15:10:38  lievre
                    801:   (Module): refinements in the computation of lli if
                    802:   status=-2 in order to have more reliable computation if stepm is
                    803:   not 1 month. Version 0.98f
                    804: 
                    805:   Revision 1.119  2006/03/15 17:42:26  brouard
                    806:   (Module): Bug if status = -2, the loglikelihood was
                    807:   computed as likelihood omitting the logarithm. Version O.98e
                    808: 
                    809:   Revision 1.118  2006/03/14 18:20:07  brouard
                    810:   (Module): varevsij Comments added explaining the second
                    811:   table of variances if popbased=1 .
                    812:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    813:   (Module): Function pstamp added
                    814:   (Module): Version 0.98d
                    815: 
                    816:   Revision 1.117  2006/03/14 17:16:22  brouard
                    817:   (Module): varevsij Comments added explaining the second
                    818:   table of variances if popbased=1 .
                    819:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    820:   (Module): Function pstamp added
                    821:   (Module): Version 0.98d
                    822: 
                    823:   Revision 1.116  2006/03/06 10:29:27  brouard
                    824:   (Module): Variance-covariance wrong links and
                    825:   varian-covariance of ej. is needed (Saito).
                    826: 
                    827:   Revision 1.115  2006/02/27 12:17:45  brouard
                    828:   (Module): One freematrix added in mlikeli! 0.98c
                    829: 
                    830:   Revision 1.114  2006/02/26 12:57:58  brouard
                    831:   (Module): Some improvements in processing parameter
                    832:   filename with strsep.
                    833: 
                    834:   Revision 1.113  2006/02/24 14:20:24  brouard
                    835:   (Module): Memory leaks checks with valgrind and:
                    836:   datafile was not closed, some imatrix were not freed and on matrix
                    837:   allocation too.
                    838: 
                    839:   Revision 1.112  2006/01/30 09:55:26  brouard
                    840:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    841: 
                    842:   Revision 1.111  2006/01/25 20:38:18  brouard
                    843:   (Module): Lots of cleaning and bugs added (Gompertz)
                    844:   (Module): Comments can be added in data file. Missing date values
                    845:   can be a simple dot '.'.
                    846: 
                    847:   Revision 1.110  2006/01/25 00:51:50  brouard
                    848:   (Module): Lots of cleaning and bugs added (Gompertz)
                    849: 
                    850:   Revision 1.109  2006/01/24 19:37:15  brouard
                    851:   (Module): Comments (lines starting with a #) are allowed in data.
                    852: 
                    853:   Revision 1.108  2006/01/19 18:05:42  lievre
                    854:   Gnuplot problem appeared...
                    855:   To be fixed
                    856: 
                    857:   Revision 1.107  2006/01/19 16:20:37  brouard
                    858:   Test existence of gnuplot in imach path
                    859: 
                    860:   Revision 1.106  2006/01/19 13:24:36  brouard
                    861:   Some cleaning and links added in html output
                    862: 
                    863:   Revision 1.105  2006/01/05 20:23:19  lievre
                    864:   *** empty log message ***
                    865: 
                    866:   Revision 1.104  2005/09/30 16:11:43  lievre
                    867:   (Module): sump fixed, loop imx fixed, and simplifications.
                    868:   (Module): If the status is missing at the last wave but we know
                    869:   that the person is alive, then we can code his/her status as -2
                    870:   (instead of missing=-1 in earlier versions) and his/her
                    871:   contributions to the likelihood is 1 - Prob of dying from last
                    872:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    873:   the healthy state at last known wave). Version is 0.98
                    874: 
                    875:   Revision 1.103  2005/09/30 15:54:49  lievre
                    876:   (Module): sump fixed, loop imx fixed, and simplifications.
                    877: 
                    878:   Revision 1.102  2004/09/15 17:31:30  brouard
                    879:   Add the possibility to read data file including tab characters.
                    880: 
                    881:   Revision 1.101  2004/09/15 10:38:38  brouard
                    882:   Fix on curr_time
                    883: 
                    884:   Revision 1.100  2004/07/12 18:29:06  brouard
                    885:   Add version for Mac OS X. Just define UNIX in Makefile
                    886: 
                    887:   Revision 1.99  2004/06/05 08:57:40  brouard
                    888:   *** empty log message ***
                    889: 
                    890:   Revision 1.98  2004/05/16 15:05:56  brouard
                    891:   New version 0.97 . First attempt to estimate force of mortality
                    892:   directly from the data i.e. without the need of knowing the health
                    893:   state at each age, but using a Gompertz model: log u =a + b*age .
                    894:   This is the basic analysis of mortality and should be done before any
                    895:   other analysis, in order to test if the mortality estimated from the
                    896:   cross-longitudinal survey is different from the mortality estimated
                    897:   from other sources like vital statistic data.
                    898: 
                    899:   The same imach parameter file can be used but the option for mle should be -3.
                    900: 
1.324     brouard   901:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   902:   former routines in order to include the new code within the former code.
                    903: 
                    904:   The output is very simple: only an estimate of the intercept and of
                    905:   the slope with 95% confident intervals.
                    906: 
                    907:   Current limitations:
                    908:   A) Even if you enter covariates, i.e. with the
                    909:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    910:   B) There is no computation of Life Expectancy nor Life Table.
                    911: 
                    912:   Revision 1.97  2004/02/20 13:25:42  lievre
                    913:   Version 0.96d. Population forecasting command line is (temporarily)
                    914:   suppressed.
                    915: 
                    916:   Revision 1.96  2003/07/15 15:38:55  brouard
                    917:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    918:   rewritten within the same printf. Workaround: many printfs.
                    919: 
                    920:   Revision 1.95  2003/07/08 07:54:34  brouard
                    921:   * imach.c (Repository):
                    922:   (Repository): Using imachwizard code to output a more meaningful covariance
                    923:   matrix (cov(a12,c31) instead of numbers.
                    924: 
                    925:   Revision 1.94  2003/06/27 13:00:02  brouard
                    926:   Just cleaning
                    927: 
                    928:   Revision 1.93  2003/06/25 16:33:55  brouard
                    929:   (Module): On windows (cygwin) function asctime_r doesn't
                    930:   exist so I changed back to asctime which exists.
                    931:   (Module): Version 0.96b
                    932: 
                    933:   Revision 1.92  2003/06/25 16:30:45  brouard
                    934:   (Module): On windows (cygwin) function asctime_r doesn't
                    935:   exist so I changed back to asctime which exists.
                    936: 
                    937:   Revision 1.91  2003/06/25 15:30:29  brouard
                    938:   * imach.c (Repository): Duplicated warning errors corrected.
                    939:   (Repository): Elapsed time after each iteration is now output. It
                    940:   helps to forecast when convergence will be reached. Elapsed time
                    941:   is stamped in powell.  We created a new html file for the graphs
                    942:   concerning matrix of covariance. It has extension -cov.htm.
                    943: 
                    944:   Revision 1.90  2003/06/24 12:34:15  brouard
                    945:   (Module): Some bugs corrected for windows. Also, when
                    946:   mle=-1 a template is output in file "or"mypar.txt with the design
                    947:   of the covariance matrix to be input.
                    948: 
                    949:   Revision 1.89  2003/06/24 12:30:52  brouard
                    950:   (Module): Some bugs corrected for windows. Also, when
                    951:   mle=-1 a template is output in file "or"mypar.txt with the design
                    952:   of the covariance matrix to be input.
                    953: 
                    954:   Revision 1.88  2003/06/23 17:54:56  brouard
                    955:   * 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.
                    956: 
                    957:   Revision 1.87  2003/06/18 12:26:01  brouard
                    958:   Version 0.96
                    959: 
                    960:   Revision 1.86  2003/06/17 20:04:08  brouard
                    961:   (Module): Change position of html and gnuplot routines and added
                    962:   routine fileappend.
                    963: 
                    964:   Revision 1.85  2003/06/17 13:12:43  brouard
                    965:   * imach.c (Repository): Check when date of death was earlier that
                    966:   current date of interview. It may happen when the death was just
                    967:   prior to the death. In this case, dh was negative and likelihood
                    968:   was wrong (infinity). We still send an "Error" but patch by
                    969:   assuming that the date of death was just one stepm after the
                    970:   interview.
                    971:   (Repository): Because some people have very long ID (first column)
                    972:   we changed int to long in num[] and we added a new lvector for
                    973:   memory allocation. But we also truncated to 8 characters (left
                    974:   truncation)
                    975:   (Repository): No more line truncation errors.
                    976: 
                    977:   Revision 1.84  2003/06/13 21:44:43  brouard
                    978:   * imach.c (Repository): Replace "freqsummary" at a correct
                    979:   place. It differs from routine "prevalence" which may be called
                    980:   many times. Probs is memory consuming and must be used with
                    981:   parcimony.
                    982:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    983: 
                    984:   Revision 1.83  2003/06/10 13:39:11  lievre
                    985:   *** empty log message ***
                    986: 
                    987:   Revision 1.82  2003/06/05 15:57:20  brouard
                    988:   Add log in  imach.c and  fullversion number is now printed.
                    989: 
                    990: */
                    991: /*
                    992:    Interpolated Markov Chain
                    993: 
                    994:   Short summary of the programme:
                    995:   
1.227     brouard   996:   This program computes Healthy Life Expectancies or State-specific
                    997:   (if states aren't health statuses) Expectancies from
                    998:   cross-longitudinal data. Cross-longitudinal data consist in: 
                    999: 
                   1000:   -1- a first survey ("cross") where individuals from different ages
                   1001:   are interviewed on their health status or degree of disability (in
                   1002:   the case of a health survey which is our main interest)
                   1003: 
                   1004:   -2- at least a second wave of interviews ("longitudinal") which
                   1005:   measure each change (if any) in individual health status.  Health
                   1006:   expectancies are computed from the time spent in each health state
                   1007:   according to a model. More health states you consider, more time is
                   1008:   necessary to reach the Maximum Likelihood of the parameters involved
                   1009:   in the model.  The simplest model is the multinomial logistic model
                   1010:   where pij is the probability to be observed in state j at the second
                   1011:   wave conditional to be observed in state i at the first
                   1012:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                   1013:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                   1014:   have a more complex model than "constant and age", you should modify
                   1015:   the program where the markup *Covariates have to be included here
                   1016:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard  1017:   convergence.
                   1018: 
                   1019:   The advantage of this computer programme, compared to a simple
                   1020:   multinomial logistic model, is clear when the delay between waves is not
                   1021:   identical for each individual. Also, if a individual missed an
                   1022:   intermediate interview, the information is lost, but taken into
                   1023:   account using an interpolation or extrapolation.  
                   1024: 
                   1025:   hPijx is the probability to be observed in state i at age x+h
                   1026:   conditional to the observed state i at age x. The delay 'h' can be
                   1027:   split into an exact number (nh*stepm) of unobserved intermediate
                   1028:   states. This elementary transition (by month, quarter,
                   1029:   semester or year) is modelled as a multinomial logistic.  The hPx
                   1030:   matrix is simply the matrix product of nh*stepm elementary matrices
                   1031:   and the contribution of each individual to the likelihood is simply
                   1032:   hPijx.
                   1033: 
                   1034:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard  1035:   of the life expectancies. It also computes the period (stable) prevalence.
                   1036: 
                   1037: Back prevalence and projections:
1.227     brouard  1038: 
                   1039:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                   1040:    double agemaxpar, double ftolpl, int *ncvyearp, double
                   1041:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                   1042:    mobilavproj)
                   1043: 
                   1044:     Computes the back prevalence limit for any combination of
                   1045:     covariate values k at any age between ageminpar and agemaxpar and
                   1046:     returns it in **bprlim. In the loops,
                   1047: 
                   1048:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                   1049:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                   1050: 
                   1051:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard  1052:    Computes for any combination of covariates k and any age between bage and fage 
                   1053:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1054:                        oldm=oldms;savm=savms;
1.227     brouard  1055: 
1.267     brouard  1056:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard  1057:      Computes the transition matrix starting at age 'age' over
                   1058:      'nhstepm*hstepm*stepm' months (i.e. until
                   1059:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard  1060:      nhstepm*hstepm matrices. 
                   1061: 
                   1062:      Returns p3mat[i][j][h] after calling
                   1063:      p3mat[i][j][h]=matprod2(newm,
                   1064:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                   1065:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                   1066:      oldm);
1.226     brouard  1067: 
                   1068: Important routines
                   1069: 
                   1070: - func (or funcone), computes logit (pij) distinguishing
                   1071:   o fixed variables (single or product dummies or quantitative);
                   1072:   o varying variables by:
                   1073:    (1) wave (single, product dummies, quantitative), 
                   1074:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                   1075:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                   1076:        % varying dummy (not done) or quantitative (not done);
                   1077: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                   1078:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                   1079: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
1.325     brouard  1080:   o There are 2**cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
1.226     brouard  1081:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard  1082: 
1.226     brouard  1083: 
                   1084:   
1.324     brouard  1085:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                   1086:            Institut national d'études démographiques, Paris.
1.126     brouard  1087:   This software have been partly granted by Euro-REVES, a concerted action
                   1088:   from the European Union.
                   1089:   It is copyrighted identically to a GNU software product, ie programme and
                   1090:   software can be distributed freely for non commercial use. Latest version
                   1091:   can be accessed at http://euroreves.ined.fr/imach .
                   1092: 
                   1093:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                   1094:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                   1095:   
                   1096:   **********************************************************************/
                   1097: /*
                   1098:   main
                   1099:   read parameterfile
                   1100:   read datafile
                   1101:   concatwav
                   1102:   freqsummary
                   1103:   if (mle >= 1)
                   1104:     mlikeli
                   1105:   print results files
                   1106:   if mle==1 
                   1107:      computes hessian
                   1108:   read end of parameter file: agemin, agemax, bage, fage, estepm
                   1109:       begin-prev-date,...
                   1110:   open gnuplot file
                   1111:   open html file
1.145     brouard  1112:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1113:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1114:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1115:     freexexit2 possible for memory heap.
                   1116: 
                   1117:   h Pij x                         | pij_nom  ficrestpij
                   1118:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1119:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1120:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1121: 
                   1122:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1123:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1124:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1125:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1126:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1127: 
1.126     brouard  1128:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1129:   health expectancies
                   1130:   Variance-covariance of DFLE
                   1131:   prevalence()
                   1132:    movingaverage()
                   1133:   varevsij() 
                   1134:   if popbased==1 varevsij(,popbased)
                   1135:   total life expectancies
                   1136:   Variance of period (stable) prevalence
                   1137:  end
                   1138: */
                   1139: 
1.187     brouard  1140: /* #define DEBUG */
                   1141: /* #define DEBUGBRENT */
1.203     brouard  1142: /* #define DEBUGLINMIN */
                   1143: /* #define DEBUGHESS */
                   1144: #define DEBUGHESSIJ
1.224     brouard  1145: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1146: #define POWELL /* Instead of NLOPT */
1.224     brouard  1147: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1148: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1149: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.319     brouard  1150: /* #define FLATSUP  *//* Suppresses directions where likelihood is flat */
1.126     brouard  1151: 
                   1152: #include <math.h>
                   1153: #include <stdio.h>
                   1154: #include <stdlib.h>
                   1155: #include <string.h>
1.226     brouard  1156: #include <ctype.h>
1.159     brouard  1157: 
                   1158: #ifdef _WIN32
                   1159: #include <io.h>
1.172     brouard  1160: #include <windows.h>
                   1161: #include <tchar.h>
1.159     brouard  1162: #else
1.126     brouard  1163: #include <unistd.h>
1.159     brouard  1164: #endif
1.126     brouard  1165: 
                   1166: #include <limits.h>
                   1167: #include <sys/types.h>
1.171     brouard  1168: 
                   1169: #if defined(__GNUC__)
                   1170: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1171: #endif
                   1172: 
1.126     brouard  1173: #include <sys/stat.h>
                   1174: #include <errno.h>
1.159     brouard  1175: /* extern int errno; */
1.126     brouard  1176: 
1.157     brouard  1177: /* #ifdef LINUX */
                   1178: /* #include <time.h> */
                   1179: /* #include "timeval.h" */
                   1180: /* #else */
                   1181: /* #include <sys/time.h> */
                   1182: /* #endif */
                   1183: 
1.126     brouard  1184: #include <time.h>
                   1185: 
1.136     brouard  1186: #ifdef GSL
                   1187: #include <gsl/gsl_errno.h>
                   1188: #include <gsl/gsl_multimin.h>
                   1189: #endif
                   1190: 
1.167     brouard  1191: 
1.162     brouard  1192: #ifdef NLOPT
                   1193: #include <nlopt.h>
                   1194: typedef struct {
                   1195:   double (* function)(double [] );
                   1196: } myfunc_data ;
                   1197: #endif
                   1198: 
1.126     brouard  1199: /* #include <libintl.h> */
                   1200: /* #define _(String) gettext (String) */
                   1201: 
1.251     brouard  1202: #define MAXLINE 2048 /* Was 256 and 1024. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1203: 
                   1204: #define GNUPLOTPROGRAM "gnuplot"
                   1205: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
1.329     brouard  1206: #define FILENAMELENGTH 256
1.126     brouard  1207: 
                   1208: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1209: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1210: 
1.144     brouard  1211: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                   1212: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1213: 
                   1214: #define NINTERVMAX 8
1.144     brouard  1215: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1216: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.325     brouard  1217: #define NCOVMAX 30  /**< Maximum number of covariates used in the model, including generated covariates V1*V2 or V1*age */
1.197     brouard  1218: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1219: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1220: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1221: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1222: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1223: /* #define AGESUP 130 */
1.288     brouard  1224: /* #define AGESUP 150 */
                   1225: #define AGESUP 200
1.268     brouard  1226: #define AGEINF 0
1.218     brouard  1227: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1228: #define AGEBASE 40
1.194     brouard  1229: #define AGEOVERFLOW 1.e20
1.164     brouard  1230: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1231: #ifdef _WIN32
                   1232: #define DIRSEPARATOR '\\'
                   1233: #define CHARSEPARATOR "\\"
                   1234: #define ODIRSEPARATOR '/'
                   1235: #else
1.126     brouard  1236: #define DIRSEPARATOR '/'
                   1237: #define CHARSEPARATOR "/"
                   1238: #define ODIRSEPARATOR '\\'
                   1239: #endif
                   1240: 
1.332   ! brouard  1241: /* $Id: imach.c,v 1.331 2022/08/07 05:40:09 brouard Exp $ */
1.126     brouard  1242: /* $State: Exp $ */
1.196     brouard  1243: #include "version.h"
                   1244: char version[]=__IMACH_VERSION__;
1.332   ! brouard  1245: char copyright[]="August 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";
        !          1246: char fullversion[]="$Revision: 1.331 $ $Date: 2022/08/07 05:40:09 $"; 
1.126     brouard  1247: char strstart[80];
                   1248: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1249: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard  1250: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.330     brouard  1251: /* Number of covariates model (1)=V2+V1+ V3*age+V2*V4 */
                   1252: /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   1253: int cptcovn=0; /**< cptcovn decodemodel: number of covariates k of the models excluding age*products =6 and age*age */
                   1254: int cptcovt=0; /**< cptcovt: total number of covariates of the model (2) nbocc(+)+1 = 8 excepting constant and age and age*age */
                   1255: int cptcovs=0; /**< cptcovs number of simple covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
1.225     brouard  1256: int cptcovsnq=0; /**< cptcovsnq number of simple covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1257: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                   1258: int cptcovprodnoage=0; /**< Number of covariate products without age */   
1.330     brouard  1259: 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  1260: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1261: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.232     brouard  1262: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
1.234     brouard  1263: int nsd=0; /**< Total number of single dummy variables (output) */
                   1264: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1265: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1266: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1267: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1268: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1269: int cptcov=0; /* Working variable */
1.290     brouard  1270: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1271: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.302     brouard  1272: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
1.126     brouard  1273: int nlstate=2; /* Number of live states */
                   1274: int ndeath=1; /* Number of dead states */
1.130     brouard  1275: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.223     brouard  1276: int  nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable */ 
1.126     brouard  1277: int popbased=0;
                   1278: 
                   1279: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1280: int maxwav=0; /* Maxim number of waves */
                   1281: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1282: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1283: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard  1284:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1285: int mle=1, weightopt=0;
1.126     brouard  1286: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1287: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1288: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1289:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1290: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1291: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1292: 
1.130     brouard  1293: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1294: double **matprod2(); /* test */
1.126     brouard  1295: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1296: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1297: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1298: 
1.136     brouard  1299: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1300: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1301: FILE *ficlog, *ficrespow;
1.130     brouard  1302: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1303: double fretone; /* Only one call to likelihood */
1.130     brouard  1304: long ipmx=0; /* Number of contributions */
1.126     brouard  1305: double sw; /* Sum of weights */
                   1306: char filerespow[FILENAMELENGTH];
                   1307: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1308: FILE *ficresilk;
                   1309: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1310: FILE *ficresprobmorprev;
                   1311: FILE *fichtm, *fichtmcov; /* Html File */
                   1312: FILE *ficreseij;
                   1313: char filerese[FILENAMELENGTH];
                   1314: FILE *ficresstdeij;
                   1315: char fileresstde[FILENAMELENGTH];
                   1316: FILE *ficrescveij;
                   1317: char filerescve[FILENAMELENGTH];
                   1318: FILE  *ficresvij;
                   1319: char fileresv[FILENAMELENGTH];
1.269     brouard  1320: 
1.126     brouard  1321: char title[MAXLINE];
1.234     brouard  1322: char model[MAXLINE]; /**< The model line */
1.217     brouard  1323: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1324: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1325: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1326: char command[FILENAMELENGTH];
                   1327: int  outcmd=0;
                   1328: 
1.217     brouard  1329: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1330: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1331: char filelog[FILENAMELENGTH]; /* Log file */
                   1332: char filerest[FILENAMELENGTH];
                   1333: char fileregp[FILENAMELENGTH];
                   1334: char popfile[FILENAMELENGTH];
                   1335: 
                   1336: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1337: 
1.157     brouard  1338: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1339: /* struct timezone tzp; */
                   1340: /* extern int gettimeofday(); */
                   1341: struct tm tml, *gmtime(), *localtime();
                   1342: 
                   1343: extern time_t time();
                   1344: 
                   1345: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1346: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                   1347: struct tm tm;
                   1348: 
1.126     brouard  1349: char strcurr[80], strfor[80];
                   1350: 
                   1351: char *endptr;
                   1352: long lval;
                   1353: double dval;
                   1354: 
                   1355: #define NR_END 1
                   1356: #define FREE_ARG char*
                   1357: #define FTOL 1.0e-10
                   1358: 
                   1359: #define NRANSI 
1.240     brouard  1360: #define ITMAX 200
                   1361: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1362: 
                   1363: #define TOL 2.0e-4 
                   1364: 
                   1365: #define CGOLD 0.3819660 
                   1366: #define ZEPS 1.0e-10 
                   1367: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1368: 
                   1369: #define GOLD 1.618034 
                   1370: #define GLIMIT 100.0 
                   1371: #define TINY 1.0e-20 
                   1372: 
                   1373: static double maxarg1,maxarg2;
                   1374: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1375: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1376:   
                   1377: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1378: #define rint(a) floor(a+0.5)
1.166     brouard  1379: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1380: #define mytinydouble 1.0e-16
1.166     brouard  1381: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1382: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1383: /* static double dsqrarg; */
                   1384: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1385: static double sqrarg;
                   1386: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1387: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1388: int agegomp= AGEGOMP;
                   1389: 
                   1390: int imx; 
                   1391: int stepm=1;
                   1392: /* Stepm, step in month: minimum step interpolation*/
                   1393: 
                   1394: int estepm;
                   1395: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1396: 
                   1397: int m,nb;
                   1398: long *num;
1.197     brouard  1399: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1400: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1401:                   covariate for which somebody answered excluding 
                   1402:                   undefined. Usually 2: 0 and 1. */
                   1403: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1404:                             covariate for which somebody answered including 
                   1405:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1406: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1407: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1408: double ***mobaverage, ***mobaverages; /* New global variable */
1.332   ! brouard  1409: double **precov; /* New global variable to store for each resultline, values of model covariates given by the resultlines (in order to speed up)  */
1.126     brouard  1410: double *ageexmed,*agecens;
                   1411: double dateintmean=0;
1.296     brouard  1412:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1413:   double anprojf, mprojf, jprojf;
1.126     brouard  1414: 
1.296     brouard  1415:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1416:   double anbackf, mbackf, jbackf;
                   1417:   double jintmean,mintmean,aintmean;  
1.126     brouard  1418: double *weight;
                   1419: int **s; /* Status */
1.141     brouard  1420: double *agedc;
1.145     brouard  1421: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1422:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1423:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1424: double **coqvar; /* Fixed quantitative covariate nqv */
                   1425: double ***cotvar; /* Time varying covariate ntv */
1.225     brouard  1426: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1427: double  idx; 
                   1428: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.319     brouard  1429: /* Some documentation */
                   1430:       /*   Design original data
                   1431:        *  V1   V2   V3   V4  V5  V6  V7  V8  Weight ddb ddth d1st s1 V9 V10 V11 V12 s2 V9 V10 V11 V12 
                   1432:        *  <          ncovcol=6   >   nqv=2 (V7 V8)                   dv dv  dv  qtv    dv dv  dvv qtv
                   1433:        *                                                             ntv=3     nqtv=1
1.330     brouard  1434:        *  cptcovn number of covariates (not including constant and age or age*age) = number of plus sign + 1 = 10+1=11
1.319     brouard  1435:        * For time varying covariate, quanti or dummies
                   1436:        *       cotqvar[wav][iv(1 to nqtv)][i]= [1][12][i]=(V12) quanti
                   1437:        *       cotvar[wav][ntv+iv][i]= [3+(1 to nqtv)][i]=(V12) quanti
                   1438:        *       cotvar[wav][iv(1 to ntv)][i]= [1][1][i]=(V9) dummies at wav 1
                   1439:        *       cotvar[wav][iv(1 to ntv)][i]= [1][2][i]=(V10) dummies at wav 1
1.332   ! brouard  1440:        *       covar[Vk,i], value of the Vkth fixed covariate dummy or quanti for individual i:
1.319     brouard  1441:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   1442:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 + V9 + V9*age + V10
                   1443:        *   k=  1    2      3       4     5       6      7        8   9     10       11 
                   1444:        */
                   1445: /* According to the model, more columns can be added to covar by the product of covariates */
1.318     brouard  1446: /* 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
                   1447:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1448:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1449: */
1.319     brouard  1450: /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1451: /*    k        1  2   3   4     5    6    7     8    9 */
                   1452: /*Typevar[k]=  0  0   0   2     1    0    2     1    0 *//*0 for simple covariate (dummy, quantitative,*/
                   1453:                                                          /* fixed or varying), 1 for age product, 2 for*/
                   1454:                                                          /* product */
                   1455: /*Dummy[k]=    1  0   0   1     3    1    1     2    0 *//*Dummy[k] 0=dummy (0 1), 1 quantitative */
                   1456:                                                          /*(single or product without age), 2 dummy*/
                   1457:                                                          /* with age product, 3 quant with age product*/
                   1458: /*Tvar[k]=     5  4   3   6     5    2    7     1    1 */
                   1459: /*    nsd         1   2                              3 */ /* Counting single dummies covar fixed or tv */
1.330     brouard  1460: /*TnsdVar[Tvar]   1   2                              3 */ 
1.319     brouard  1461: /*TvarsD[nsd]     4   3                              1 */ /* ID of single dummy cova fixed or timevary*/
                   1462: /*TvarsDind[k]    2   3                              9 */ /* position K of single dummy cova */
                   1463: /*    nsq      1                     2                 */ /* Counting single quantit tv */
                   1464: /* TvarsQ[k]   5                     2                 */ /* Number of single quantitative cova */
                   1465: /* TvarsQind   1                     6                 */ /* position K of single quantitative cova */
                   1466: /* Tprod[i]=k             1               2            */ /* Position in model of the ith prod without age */
                   1467: /* cptcovage                    1               2      */ /* Counting cov*age in the model equation */
                   1468: /* Tage[cptcovage]=k            5               8      */ /* Position in the model of ith cov*age */
                   1469: /* Tvard[1][1]@4={4,3,1,2}    V4*V3 V1*V2              */ /* Position in model of the ith prod without age */
1.330     brouard  1470: /* 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  1471: /* 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  1472: /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.234     brouard  1473: /* Type                    */
                   1474: /* V         1  2  3  4  5 */
                   1475: /*           F  F  V  V  V */
                   1476: /*           D  Q  D  D  Q */
                   1477: /*                         */
                   1478: int *TvarsD;
1.330     brouard  1479: int *TnsdVar;
1.234     brouard  1480: int *TvarsDind;
                   1481: int *TvarsQ;
                   1482: int *TvarsQind;
                   1483: 
1.318     brouard  1484: #define MAXRESULTLINESPONE 10+1
1.235     brouard  1485: int nresult=0;
1.258     brouard  1486: int parameterline=0; /* # of the parameter (type) line */
1.318     brouard  1487: int TKresult[MAXRESULTLINESPONE];
1.330     brouard  1488: int resultmodel[MAXRESULTLINESPONE][NCOVMAX];/* resultmodel[k1]=k3: k1th position in the model correspond to the k3 position in the resultline */
1.318     brouard  1489: int Tresult[MAXRESULTLINESPONE][NCOVMAX];/* For dummy variable , value (output) */
1.332   ! brouard  1490: int Tinvresult[MAXRESULTLINESPONE][NCOVMAX];/* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line  */
        !          1491: double TinvDoQresult[MAXRESULTLINESPONE][NCOVMAX];/* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line */
1.318     brouard  1492: int Tvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For dummy variable , variable # (output) */
1.332   ! brouard  1493: double Tqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
1.318     brouard  1494: double Tqinvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
1.332   ! brouard  1495: int Tvqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline */
1.318     brouard  1496: 
                   1497: /* 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
                   1498:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1499:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1500: */
1.234     brouard  1501: /* 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  1502: 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 */
                   1503: 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 */
                   1504: 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 */
                   1505: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1506: 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 */
                   1507: 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  1508: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1509: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1510: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1511: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1512: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1513: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1514: 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 */
                   1515: 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 */
                   1516: 
1.230     brouard  1517: int *Tvarsel; /**< Selected covariates for output */
                   1518: double *Tvalsel; /**< Selected modality value of covariate for output */
1.226     brouard  1519: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.227     brouard  1520: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1521: 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  1522: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1523: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1524: int *Tage;
1.227     brouard  1525: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1526: 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  1527: 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*/ 
                   1528: 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  1529: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1530: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1531: int **Tvard;
1.330     brouard  1532: int **Tvardk;
1.227     brouard  1533: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1534: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1535: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1536:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1537:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1538: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1539: double *lsurv, *lpop, *tpop;
                   1540: 
1.231     brouard  1541: #define FD 1; /* Fixed dummy covariate */
                   1542: #define FQ 2; /* Fixed quantitative covariate */
                   1543: #define FP 3; /* Fixed product covariate */
                   1544: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1545: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1546: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1547: #define VD 10; /* Varying dummy covariate */
                   1548: #define VQ 11; /* Varying quantitative covariate */
                   1549: #define VP 12; /* Varying product covariate */
                   1550: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1551: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1552: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1553: #define APFD 16; /* Age product * fixed dummy covariate */
                   1554: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1555: #define APVD 18; /* Age product * varying dummy covariate */
                   1556: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1557: 
                   1558: #define FTYPE 1; /* Fixed covariate */
                   1559: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1560: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1561: 
                   1562: struct kmodel{
                   1563:        int maintype; /* main type */
                   1564:        int subtype; /* subtype */
                   1565: };
                   1566: struct kmodel modell[NCOVMAX];
                   1567: 
1.143     brouard  1568: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1569: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1570: 
                   1571: /**************** split *************************/
                   1572: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1573: {
                   1574:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1575:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1576:   */ 
                   1577:   char *ss;                            /* pointer */
1.186     brouard  1578:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1579: 
                   1580:   l1 = strlen(path );                  /* length of path */
                   1581:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1582:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1583:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1584:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1585:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1586:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1587:     /* get current working directory */
                   1588:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1589: #ifdef WIN32
                   1590:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1591: #else
                   1592:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1593: #endif
1.126     brouard  1594:       return( GLOCK_ERROR_GETCWD );
                   1595:     }
                   1596:     /* got dirc from getcwd*/
                   1597:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1598:   } else {                             /* strip directory from path */
1.126     brouard  1599:     ss++;                              /* after this, the filename */
                   1600:     l2 = strlen( ss );                 /* length of filename */
                   1601:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1602:     strcpy( name, ss );                /* save file name */
                   1603:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1604:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1605:     printf(" DIRC2 = %s \n",dirc);
                   1606:   }
                   1607:   /* We add a separator at the end of dirc if not exists */
                   1608:   l1 = strlen( dirc );                 /* length of directory */
                   1609:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1610:     dirc[l1] =  DIRSEPARATOR;
                   1611:     dirc[l1+1] = 0; 
                   1612:     printf(" DIRC3 = %s \n",dirc);
                   1613:   }
                   1614:   ss = strrchr( name, '.' );           /* find last / */
                   1615:   if (ss >0){
                   1616:     ss++;
                   1617:     strcpy(ext,ss);                    /* save extension */
                   1618:     l1= strlen( name);
                   1619:     l2= strlen(ss)+1;
                   1620:     strncpy( finame, name, l1-l2);
                   1621:     finame[l1-l2]= 0;
                   1622:   }
                   1623: 
                   1624:   return( 0 );                         /* we're done */
                   1625: }
                   1626: 
                   1627: 
                   1628: /******************************************/
                   1629: 
                   1630: void replace_back_to_slash(char *s, char*t)
                   1631: {
                   1632:   int i;
                   1633:   int lg=0;
                   1634:   i=0;
                   1635:   lg=strlen(t);
                   1636:   for(i=0; i<= lg; i++) {
                   1637:     (s[i] = t[i]);
                   1638:     if (t[i]== '\\') s[i]='/';
                   1639:   }
                   1640: }
                   1641: 
1.132     brouard  1642: char *trimbb(char *out, char *in)
1.137     brouard  1643: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1644:   char *s;
                   1645:   s=out;
                   1646:   while (*in != '\0'){
1.137     brouard  1647:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1648:       in++;
                   1649:     }
                   1650:     *out++ = *in++;
                   1651:   }
                   1652:   *out='\0';
                   1653:   return s;
                   1654: }
                   1655: 
1.187     brouard  1656: /* char *substrchaine(char *out, char *in, char *chain) */
                   1657: /* { */
                   1658: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1659: /*   char *s, *t; */
                   1660: /*   t=in;s=out; */
                   1661: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1662: /*     *out++ = *in++; */
                   1663: /*   } */
                   1664: 
                   1665: /*   /\* *in matches *chain *\/ */
                   1666: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1667: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1668: /*   } */
                   1669: /*   in--; chain--; */
                   1670: /*   while ( (*in != '\0')){ */
                   1671: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1672: /*     *out++ = *in++; */
                   1673: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1674: /*   } */
                   1675: /*   *out='\0'; */
                   1676: /*   out=s; */
                   1677: /*   return out; */
                   1678: /* } */
                   1679: char *substrchaine(char *out, char *in, char *chain)
                   1680: {
                   1681:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1682:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1683: 
                   1684:   char *strloc;
                   1685: 
                   1686:   strcpy (out, in); 
                   1687:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1688:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1689:   if(strloc != NULL){ 
                   1690:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1691:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1692:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1693:   }
                   1694:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1695:   return out;
                   1696: }
                   1697: 
                   1698: 
1.145     brouard  1699: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1700: {
1.187     brouard  1701:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1702:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.310     brouard  1703:      gives alocc="abcdef" and blocc="ghi2j".
1.145     brouard  1704:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1705:   */
1.160     brouard  1706:   char *s, *t;
1.145     brouard  1707:   t=in;s=in;
                   1708:   while ((*in != occ) && (*in != '\0')){
                   1709:     *alocc++ = *in++;
                   1710:   }
                   1711:   if( *in == occ){
                   1712:     *(alocc)='\0';
                   1713:     s=++in;
                   1714:   }
                   1715:  
                   1716:   if (s == t) {/* occ not found */
                   1717:     *(alocc-(in-s))='\0';
                   1718:     in=s;
                   1719:   }
                   1720:   while ( *in != '\0'){
                   1721:     *blocc++ = *in++;
                   1722:   }
                   1723: 
                   1724:   *blocc='\0';
                   1725:   return t;
                   1726: }
1.137     brouard  1727: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1728: {
1.187     brouard  1729:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1730:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1731:      gives blocc="abcdef2ghi" and alocc="j".
                   1732:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1733:   */
                   1734:   char *s, *t;
                   1735:   t=in;s=in;
                   1736:   while (*in != '\0'){
                   1737:     while( *in == occ){
                   1738:       *blocc++ = *in++;
                   1739:       s=in;
                   1740:     }
                   1741:     *blocc++ = *in++;
                   1742:   }
                   1743:   if (s == t) /* occ not found */
                   1744:     *(blocc-(in-s))='\0';
                   1745:   else
                   1746:     *(blocc-(in-s)-1)='\0';
                   1747:   in=s;
                   1748:   while ( *in != '\0'){
                   1749:     *alocc++ = *in++;
                   1750:   }
                   1751: 
                   1752:   *alocc='\0';
                   1753:   return s;
                   1754: }
                   1755: 
1.126     brouard  1756: int nbocc(char *s, char occ)
                   1757: {
                   1758:   int i,j=0;
                   1759:   int lg=20;
                   1760:   i=0;
                   1761:   lg=strlen(s);
                   1762:   for(i=0; i<= lg; i++) {
1.234     brouard  1763:     if  (s[i] == occ ) j++;
1.126     brouard  1764:   }
                   1765:   return j;
                   1766: }
                   1767: 
1.137     brouard  1768: /* void cutv(char *u,char *v, char*t, char occ) */
                   1769: /* { */
                   1770: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1771: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1772: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1773: /*   int i,lg,j,p=0; */
                   1774: /*   i=0; */
                   1775: /*   lg=strlen(t); */
                   1776: /*   for(j=0; j<=lg-1; j++) { */
                   1777: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1778: /*   } */
1.126     brouard  1779: 
1.137     brouard  1780: /*   for(j=0; j<p; j++) { */
                   1781: /*     (u[j] = t[j]); */
                   1782: /*   } */
                   1783: /*      u[p]='\0'; */
1.126     brouard  1784: 
1.137     brouard  1785: /*    for(j=0; j<= lg; j++) { */
                   1786: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1787: /*   } */
                   1788: /* } */
1.126     brouard  1789: 
1.160     brouard  1790: #ifdef _WIN32
                   1791: char * strsep(char **pp, const char *delim)
                   1792: {
                   1793:   char *p, *q;
                   1794:          
                   1795:   if ((p = *pp) == NULL)
                   1796:     return 0;
                   1797:   if ((q = strpbrk (p, delim)) != NULL)
                   1798:   {
                   1799:     *pp = q + 1;
                   1800:     *q = '\0';
                   1801:   }
                   1802:   else
                   1803:     *pp = 0;
                   1804:   return p;
                   1805: }
                   1806: #endif
                   1807: 
1.126     brouard  1808: /********************** nrerror ********************/
                   1809: 
                   1810: void nrerror(char error_text[])
                   1811: {
                   1812:   fprintf(stderr,"ERREUR ...\n");
                   1813:   fprintf(stderr,"%s\n",error_text);
                   1814:   exit(EXIT_FAILURE);
                   1815: }
                   1816: /*********************** vector *******************/
                   1817: double *vector(int nl, int nh)
                   1818: {
                   1819:   double *v;
                   1820:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1821:   if (!v) nrerror("allocation failure in vector");
                   1822:   return v-nl+NR_END;
                   1823: }
                   1824: 
                   1825: /************************ free vector ******************/
                   1826: void free_vector(double*v, int nl, int nh)
                   1827: {
                   1828:   free((FREE_ARG)(v+nl-NR_END));
                   1829: }
                   1830: 
                   1831: /************************ivector *******************************/
                   1832: int *ivector(long nl,long nh)
                   1833: {
                   1834:   int *v;
                   1835:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1836:   if (!v) nrerror("allocation failure in ivector");
                   1837:   return v-nl+NR_END;
                   1838: }
                   1839: 
                   1840: /******************free ivector **************************/
                   1841: void free_ivector(int *v, long nl, long nh)
                   1842: {
                   1843:   free((FREE_ARG)(v+nl-NR_END));
                   1844: }
                   1845: 
                   1846: /************************lvector *******************************/
                   1847: long *lvector(long nl,long nh)
                   1848: {
                   1849:   long *v;
                   1850:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1851:   if (!v) nrerror("allocation failure in ivector");
                   1852:   return v-nl+NR_END;
                   1853: }
                   1854: 
                   1855: /******************free lvector **************************/
                   1856: void free_lvector(long *v, long nl, long nh)
                   1857: {
                   1858:   free((FREE_ARG)(v+nl-NR_END));
                   1859: }
                   1860: 
                   1861: /******************* imatrix *******************************/
                   1862: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1863:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1864: { 
                   1865:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1866:   int **m; 
                   1867:   
                   1868:   /* allocate pointers to rows */ 
                   1869:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1870:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1871:   m += NR_END; 
                   1872:   m -= nrl; 
                   1873:   
                   1874:   
                   1875:   /* allocate rows and set pointers to them */ 
                   1876:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1877:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1878:   m[nrl] += NR_END; 
                   1879:   m[nrl] -= ncl; 
                   1880:   
                   1881:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1882:   
                   1883:   /* return pointer to array of pointers to rows */ 
                   1884:   return m; 
                   1885: } 
                   1886: 
                   1887: /****************** free_imatrix *************************/
                   1888: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1889:       int **m;
                   1890:       long nch,ncl,nrh,nrl; 
                   1891:      /* free an int matrix allocated by imatrix() */ 
                   1892: { 
                   1893:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1894:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1895: } 
                   1896: 
                   1897: /******************* matrix *******************************/
                   1898: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1899: {
                   1900:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1901:   double **m;
                   1902: 
                   1903:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1904:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1905:   m += NR_END;
                   1906:   m -= nrl;
                   1907: 
                   1908:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1909:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1910:   m[nrl] += NR_END;
                   1911:   m[nrl] -= ncl;
                   1912: 
                   1913:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1914:   return m;
1.145     brouard  1915:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1916: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1917: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1918:    */
                   1919: }
                   1920: 
                   1921: /*************************free matrix ************************/
                   1922: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1923: {
                   1924:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1925:   free((FREE_ARG)(m+nrl-NR_END));
                   1926: }
                   1927: 
                   1928: /******************* ma3x *******************************/
                   1929: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1930: {
                   1931:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1932:   double ***m;
                   1933: 
                   1934:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1935:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1936:   m += NR_END;
                   1937:   m -= nrl;
                   1938: 
                   1939:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1940:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1941:   m[nrl] += NR_END;
                   1942:   m[nrl] -= ncl;
                   1943: 
                   1944:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1945: 
                   1946:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1947:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1948:   m[nrl][ncl] += NR_END;
                   1949:   m[nrl][ncl] -= nll;
                   1950:   for (j=ncl+1; j<=nch; j++) 
                   1951:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1952:   
                   1953:   for (i=nrl+1; i<=nrh; i++) {
                   1954:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1955:     for (j=ncl+1; j<=nch; j++) 
                   1956:       m[i][j]=m[i][j-1]+nlay;
                   1957:   }
                   1958:   return m; 
                   1959:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1960:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1961:   */
                   1962: }
                   1963: 
                   1964: /*************************free ma3x ************************/
                   1965: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1966: {
                   1967:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1968:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1969:   free((FREE_ARG)(m+nrl-NR_END));
                   1970: }
                   1971: 
                   1972: /*************** function subdirf ***********/
                   1973: char *subdirf(char fileres[])
                   1974: {
                   1975:   /* Caution optionfilefiname is hidden */
                   1976:   strcpy(tmpout,optionfilefiname);
                   1977:   strcat(tmpout,"/"); /* Add to the right */
                   1978:   strcat(tmpout,fileres);
                   1979:   return tmpout;
                   1980: }
                   1981: 
                   1982: /*************** function subdirf2 ***********/
                   1983: char *subdirf2(char fileres[], char *preop)
                   1984: {
1.314     brouard  1985:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
                   1986:  Errors in subdirf, 2, 3 while printing tmpout is
1.315     brouard  1987:  rewritten within the same printf. Workaround: many printfs */
1.126     brouard  1988:   /* Caution optionfilefiname is hidden */
                   1989:   strcpy(tmpout,optionfilefiname);
                   1990:   strcat(tmpout,"/");
                   1991:   strcat(tmpout,preop);
                   1992:   strcat(tmpout,fileres);
                   1993:   return tmpout;
                   1994: }
                   1995: 
                   1996: /*************** function subdirf3 ***********/
                   1997: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1998: {
                   1999:   
                   2000:   /* Caution optionfilefiname is hidden */
                   2001:   strcpy(tmpout,optionfilefiname);
                   2002:   strcat(tmpout,"/");
                   2003:   strcat(tmpout,preop);
                   2004:   strcat(tmpout,preop2);
                   2005:   strcat(tmpout,fileres);
                   2006:   return tmpout;
                   2007: }
1.213     brouard  2008:  
                   2009: /*************** function subdirfext ***********/
                   2010: char *subdirfext(char fileres[], char *preop, char *postop)
                   2011: {
                   2012:   
                   2013:   strcpy(tmpout,preop);
                   2014:   strcat(tmpout,fileres);
                   2015:   strcat(tmpout,postop);
                   2016:   return tmpout;
                   2017: }
1.126     brouard  2018: 
1.213     brouard  2019: /*************** function subdirfext3 ***********/
                   2020: char *subdirfext3(char fileres[], char *preop, char *postop)
                   2021: {
                   2022:   
                   2023:   /* Caution optionfilefiname is hidden */
                   2024:   strcpy(tmpout,optionfilefiname);
                   2025:   strcat(tmpout,"/");
                   2026:   strcat(tmpout,preop);
                   2027:   strcat(tmpout,fileres);
                   2028:   strcat(tmpout,postop);
                   2029:   return tmpout;
                   2030: }
                   2031:  
1.162     brouard  2032: char *asc_diff_time(long time_sec, char ascdiff[])
                   2033: {
                   2034:   long sec_left, days, hours, minutes;
                   2035:   days = (time_sec) / (60*60*24);
                   2036:   sec_left = (time_sec) % (60*60*24);
                   2037:   hours = (sec_left) / (60*60) ;
                   2038:   sec_left = (sec_left) %(60*60);
                   2039:   minutes = (sec_left) /60;
                   2040:   sec_left = (sec_left) % (60);
                   2041:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   2042:   return ascdiff;
                   2043: }
                   2044: 
1.126     brouard  2045: /***************** f1dim *************************/
                   2046: extern int ncom; 
                   2047: extern double *pcom,*xicom;
                   2048: extern double (*nrfunc)(double []); 
                   2049:  
                   2050: double f1dim(double x) 
                   2051: { 
                   2052:   int j; 
                   2053:   double f;
                   2054:   double *xt; 
                   2055:  
                   2056:   xt=vector(1,ncom); 
                   2057:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   2058:   f=(*nrfunc)(xt); 
                   2059:   free_vector(xt,1,ncom); 
                   2060:   return f; 
                   2061: } 
                   2062: 
                   2063: /*****************brent *************************/
                   2064: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  2065: {
                   2066:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   2067:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   2068:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   2069:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   2070:    * returned function value. 
                   2071:   */
1.126     brouard  2072:   int iter; 
                   2073:   double a,b,d,etemp;
1.159     brouard  2074:   double fu=0,fv,fw,fx;
1.164     brouard  2075:   double ftemp=0.;
1.126     brouard  2076:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   2077:   double e=0.0; 
                   2078:  
                   2079:   a=(ax < cx ? ax : cx); 
                   2080:   b=(ax > cx ? ax : cx); 
                   2081:   x=w=v=bx; 
                   2082:   fw=fv=fx=(*f)(x); 
                   2083:   for (iter=1;iter<=ITMAX;iter++) { 
                   2084:     xm=0.5*(a+b); 
                   2085:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   2086:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   2087:     printf(".");fflush(stdout);
                   2088:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  2089: #ifdef DEBUGBRENT
1.126     brouard  2090:     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);
                   2091:     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);
                   2092:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   2093: #endif
                   2094:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   2095:       *xmin=x; 
                   2096:       return fx; 
                   2097:     } 
                   2098:     ftemp=fu;
                   2099:     if (fabs(e) > tol1) { 
                   2100:       r=(x-w)*(fx-fv); 
                   2101:       q=(x-v)*(fx-fw); 
                   2102:       p=(x-v)*q-(x-w)*r; 
                   2103:       q=2.0*(q-r); 
                   2104:       if (q > 0.0) p = -p; 
                   2105:       q=fabs(q); 
                   2106:       etemp=e; 
                   2107:       e=d; 
                   2108:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  2109:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  2110:       else { 
1.224     brouard  2111:                                d=p/q; 
                   2112:                                u=x+d; 
                   2113:                                if (u-a < tol2 || b-u < tol2) 
                   2114:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  2115:       } 
                   2116:     } else { 
                   2117:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2118:     } 
                   2119:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   2120:     fu=(*f)(u); 
                   2121:     if (fu <= fx) { 
                   2122:       if (u >= x) a=x; else b=x; 
                   2123:       SHFT(v,w,x,u) 
1.183     brouard  2124:       SHFT(fv,fw,fx,fu) 
                   2125:     } else { 
                   2126:       if (u < x) a=u; else b=u; 
                   2127:       if (fu <= fw || w == x) { 
1.224     brouard  2128:                                v=w; 
                   2129:                                w=u; 
                   2130:                                fv=fw; 
                   2131:                                fw=fu; 
1.183     brouard  2132:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  2133:                                v=u; 
                   2134:                                fv=fu; 
1.183     brouard  2135:       } 
                   2136:     } 
1.126     brouard  2137:   } 
                   2138:   nrerror("Too many iterations in brent"); 
                   2139:   *xmin=x; 
                   2140:   return fx; 
                   2141: } 
                   2142: 
                   2143: /****************** mnbrak ***********************/
                   2144: 
                   2145: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2146:            double (*func)(double)) 
1.183     brouard  2147: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2148: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2149: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2150: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2151:    */
1.126     brouard  2152:   double ulim,u,r,q, dum;
                   2153:   double fu; 
1.187     brouard  2154: 
                   2155:   double scale=10.;
                   2156:   int iterscale=0;
                   2157: 
                   2158:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2159:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2160: 
                   2161: 
                   2162:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2163:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2164:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2165:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2166:   /* } */
                   2167: 
1.126     brouard  2168:   if (*fb > *fa) { 
                   2169:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2170:     SHFT(dum,*fb,*fa,dum) 
                   2171:   } 
1.126     brouard  2172:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2173:   *fc=(*func)(*cx); 
1.183     brouard  2174: #ifdef DEBUG
1.224     brouard  2175:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2176:   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  2177: #endif
1.224     brouard  2178:   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  2179:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2180:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2181:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2182:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2183:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2184:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2185:       fu=(*func)(u); 
1.163     brouard  2186: #ifdef DEBUG
                   2187:       /* f(x)=A(x-u)**2+f(u) */
                   2188:       double A, fparabu; 
                   2189:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2190:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2191:       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);
                   2192:       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  2193:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2194:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2195:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2196:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2197: #endif 
1.184     brouard  2198: #ifdef MNBRAKORIGINAL
1.183     brouard  2199: #else
1.191     brouard  2200: /*       if (fu > *fc) { */
                   2201: /* #ifdef DEBUG */
                   2202: /*       printf("mnbrak4  fu > fc \n"); */
                   2203: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2204: /* #endif */
                   2205: /*     /\* 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 *\\/  *\/ */
                   2206: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2207: /*     dum=u; /\* Shifting c and u *\/ */
                   2208: /*     u = *cx; */
                   2209: /*     *cx = dum; */
                   2210: /*     dum = fu; */
                   2211: /*     fu = *fc; */
                   2212: /*     *fc =dum; */
                   2213: /*       } else { /\* end *\/ */
                   2214: /* #ifdef DEBUG */
                   2215: /*       printf("mnbrak3  fu < fc \n"); */
                   2216: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2217: /* #endif */
                   2218: /*     dum=u; /\* Shifting c and u *\/ */
                   2219: /*     u = *cx; */
                   2220: /*     *cx = dum; */
                   2221: /*     dum = fu; */
                   2222: /*     fu = *fc; */
                   2223: /*     *fc =dum; */
                   2224: /*       } */
1.224     brouard  2225: #ifdef DEBUGMNBRAK
                   2226:                 double A, fparabu; 
                   2227:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2228:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2229:      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);
                   2230:      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  2231: #endif
1.191     brouard  2232:       dum=u; /* Shifting c and u */
                   2233:       u = *cx;
                   2234:       *cx = dum;
                   2235:       dum = fu;
                   2236:       fu = *fc;
                   2237:       *fc =dum;
1.183     brouard  2238: #endif
1.162     brouard  2239:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2240: #ifdef DEBUG
1.224     brouard  2241:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2242:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2243: #endif
1.126     brouard  2244:       fu=(*func)(u); 
                   2245:       if (fu < *fc) { 
1.183     brouard  2246: #ifdef DEBUG
1.224     brouard  2247:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2248:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2249: #endif
                   2250:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2251:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2252: #ifdef DEBUG
                   2253:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2254: #endif
                   2255:       } 
1.162     brouard  2256:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2257: #ifdef DEBUG
1.224     brouard  2258:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2259:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2260: #endif
1.126     brouard  2261:       u=ulim; 
                   2262:       fu=(*func)(u); 
1.183     brouard  2263:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2264: #ifdef DEBUG
1.224     brouard  2265:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2266:       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  2267: #endif
1.126     brouard  2268:       u=(*cx)+GOLD*(*cx-*bx); 
                   2269:       fu=(*func)(u); 
1.224     brouard  2270: #ifdef DEBUG
                   2271:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2272:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2273: #endif
1.183     brouard  2274:     } /* end tests */
1.126     brouard  2275:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2276:     SHFT(*fa,*fb,*fc,fu) 
                   2277: #ifdef DEBUG
1.224     brouard  2278:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2279:       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  2280: #endif
                   2281:   } /* 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  2282: } 
                   2283: 
                   2284: /*************** linmin ************************/
1.162     brouard  2285: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2286: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2287: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2288: the value of func at the returned location p . This is actually all accomplished by calling the
                   2289: routines mnbrak and brent .*/
1.126     brouard  2290: int ncom; 
                   2291: double *pcom,*xicom;
                   2292: double (*nrfunc)(double []); 
                   2293:  
1.224     brouard  2294: #ifdef LINMINORIGINAL
1.126     brouard  2295: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2296: #else
                   2297: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2298: #endif
1.126     brouard  2299: { 
                   2300:   double brent(double ax, double bx, double cx, 
                   2301:               double (*f)(double), double tol, double *xmin); 
                   2302:   double f1dim(double x); 
                   2303:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2304:              double *fc, double (*func)(double)); 
                   2305:   int j; 
                   2306:   double xx,xmin,bx,ax; 
                   2307:   double fx,fb,fa;
1.187     brouard  2308: 
1.203     brouard  2309: #ifdef LINMINORIGINAL
                   2310: #else
                   2311:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2312: #endif
                   2313:   
1.126     brouard  2314:   ncom=n; 
                   2315:   pcom=vector(1,n); 
                   2316:   xicom=vector(1,n); 
                   2317:   nrfunc=func; 
                   2318:   for (j=1;j<=n;j++) { 
                   2319:     pcom[j]=p[j]; 
1.202     brouard  2320:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2321:   } 
1.187     brouard  2322: 
1.203     brouard  2323: #ifdef LINMINORIGINAL
                   2324:   xx=1.;
                   2325: #else
                   2326:   axs=0.0;
                   2327:   xxs=1.;
                   2328:   do{
                   2329:     xx= xxs;
                   2330: #endif
1.187     brouard  2331:     ax=0.;
                   2332:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2333:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2334:     /* 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))   */
                   2335:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2336:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2337:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2338:     /* 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  2339: #ifdef LINMINORIGINAL
                   2340: #else
                   2341:     if (fx != fx){
1.224     brouard  2342:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2343:                        printf("|");
                   2344:                        fprintf(ficlog,"|");
1.203     brouard  2345: #ifdef DEBUGLINMIN
1.224     brouard  2346:                        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  2347: #endif
                   2348:     }
1.224     brouard  2349:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2350: #endif
                   2351:   
1.191     brouard  2352: #ifdef DEBUGLINMIN
                   2353:   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  2354:   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  2355: #endif
1.224     brouard  2356: #ifdef LINMINORIGINAL
                   2357: #else
1.317     brouard  2358:   if(fb == fx){ /* Flat function in the direction */
                   2359:     xmin=xx;
1.224     brouard  2360:     *flat=1;
1.317     brouard  2361:   }else{
1.224     brouard  2362:     *flat=0;
                   2363: #endif
                   2364:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2365:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2366:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2367:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2368:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2369:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2370: #ifdef DEBUG
1.224     brouard  2371:   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);
                   2372:   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);
                   2373: #endif
                   2374: #ifdef LINMINORIGINAL
                   2375: #else
                   2376:                        }
1.126     brouard  2377: #endif
1.191     brouard  2378: #ifdef DEBUGLINMIN
                   2379:   printf("linmin end ");
1.202     brouard  2380:   fprintf(ficlog,"linmin end ");
1.191     brouard  2381: #endif
1.126     brouard  2382:   for (j=1;j<=n;j++) { 
1.203     brouard  2383: #ifdef LINMINORIGINAL
                   2384:     xi[j] *= xmin; 
                   2385: #else
                   2386: #ifdef DEBUGLINMIN
                   2387:     if(xxs <1.0)
                   2388:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2389: #endif
                   2390:     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) */
                   2391: #ifdef DEBUGLINMIN
                   2392:     if(xxs <1.0)
                   2393:       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 );
                   2394: #endif
                   2395: #endif
1.187     brouard  2396:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2397:   } 
1.191     brouard  2398: #ifdef DEBUGLINMIN
1.203     brouard  2399:   printf("\n");
1.191     brouard  2400:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2401:   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  2402:   for (j=1;j<=n;j++) { 
1.202     brouard  2403:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2404:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2405:     if(j % ncovmodel == 0){
1.191     brouard  2406:       printf("\n");
1.202     brouard  2407:       fprintf(ficlog,"\n");
                   2408:     }
1.191     brouard  2409:   }
1.203     brouard  2410: #else
1.191     brouard  2411: #endif
1.126     brouard  2412:   free_vector(xicom,1,n); 
                   2413:   free_vector(pcom,1,n); 
                   2414: } 
                   2415: 
                   2416: 
                   2417: /*************** powell ************************/
1.162     brouard  2418: /*
1.317     brouard  2419: Minimization of a function func of n variables. Input consists in an initial starting point
                   2420: p[1..n] ; an initial matrix xi[1..n][1..n]  whose columns contain the initial set of di-
                   2421: rections (usually the n unit vectors); and ftol, the fractional tolerance in the function value
                   2422: such that failure to decrease by more than this amount in one iteration signals doneness. On
1.162     brouard  2423: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2424: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2425:  */
1.224     brouard  2426: #ifdef LINMINORIGINAL
                   2427: #else
                   2428:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2429:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2430: #endif
1.126     brouard  2431: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2432:            double (*func)(double [])) 
                   2433: { 
1.224     brouard  2434: #ifdef LINMINORIGINAL
                   2435:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2436:              double (*func)(double [])); 
1.224     brouard  2437: #else 
1.241     brouard  2438:  void linmin(double p[], double xi[], int n, double *fret,
                   2439:             double (*func)(double []),int *flat); 
1.224     brouard  2440: #endif
1.239     brouard  2441:  int i,ibig,j,jk,k; 
1.126     brouard  2442:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2443:   double directest;
1.126     brouard  2444:   double fp,fptt;
                   2445:   double *xits;
                   2446:   int niterf, itmp;
                   2447: 
                   2448:   pt=vector(1,n); 
                   2449:   ptt=vector(1,n); 
                   2450:   xit=vector(1,n); 
                   2451:   xits=vector(1,n); 
                   2452:   *fret=(*func)(p); 
                   2453:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  2454:   rcurr_time = time(NULL);  
1.126     brouard  2455:   for (*iter=1;;++(*iter)) { 
                   2456:     ibig=0; 
                   2457:     del=0.0; 
1.157     brouard  2458:     rlast_time=rcurr_time;
                   2459:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2460:     rcurr_time = time(NULL);  
                   2461:     curr_time = *localtime(&rcurr_time);
1.324     brouard  2462:     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);
                   2463:     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  2464: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.324     brouard  2465:     fp=(*fret); /* From former iteration or initial value */
1.192     brouard  2466:     for (i=1;i<=n;i++) {
1.126     brouard  2467:       fprintf(ficrespow," %.12lf", p[i]);
                   2468:     }
1.239     brouard  2469:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2470:     printf("\n#model=  1      +     age ");
                   2471:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2472:     if(nagesqr==1){
1.241     brouard  2473:        printf("  + age*age  ");
                   2474:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2475:     }
                   2476:     for(j=1;j <=ncovmodel-2;j++){
                   2477:       if(Typevar[j]==0) {
                   2478:        printf("  +      V%d  ",Tvar[j]);
                   2479:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2480:       }else if(Typevar[j]==1) {
                   2481:        printf("  +    V%d*age ",Tvar[j]);
                   2482:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2483:       }else if(Typevar[j]==2) {
                   2484:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2485:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2486:       }
                   2487:     }
1.126     brouard  2488:     printf("\n");
1.239     brouard  2489: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2490: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2491:     fprintf(ficlog,"\n");
1.239     brouard  2492:     for(i=1,jk=1; i <=nlstate; i++){
                   2493:       for(k=1; k <=(nlstate+ndeath); k++){
                   2494:        if (k != i) {
                   2495:          printf("%d%d ",i,k);
                   2496:          fprintf(ficlog,"%d%d ",i,k);
                   2497:          for(j=1; j <=ncovmodel; j++){
                   2498:            printf("%12.7f ",p[jk]);
                   2499:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2500:            jk++; 
                   2501:          }
                   2502:          printf("\n");
                   2503:          fprintf(ficlog,"\n");
                   2504:        }
                   2505:       }
                   2506:     }
1.241     brouard  2507:     if(*iter <=3 && *iter >1){
1.157     brouard  2508:       tml = *localtime(&rcurr_time);
                   2509:       strcpy(strcurr,asctime(&tml));
                   2510:       rforecast_time=rcurr_time; 
1.126     brouard  2511:       itmp = strlen(strcurr);
                   2512:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2513:        strcurr[itmp-1]='\0';
1.162     brouard  2514:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2515:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  2516:       for(niterf=10;niterf<=30;niterf+=10){
1.241     brouard  2517:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2518:        forecast_time = *localtime(&rforecast_time);
                   2519:        strcpy(strfor,asctime(&forecast_time));
                   2520:        itmp = strlen(strfor);
                   2521:        if(strfor[itmp-1]=='\n')
                   2522:          strfor[itmp-1]='\0';
                   2523:        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);
                   2524:        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  2525:       }
                   2526:     }
1.187     brouard  2527:     for (i=1;i<=n;i++) { /* For each direction i */
                   2528:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2529:       fptt=(*fret); 
                   2530: #ifdef DEBUG
1.203     brouard  2531:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2532:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2533: #endif
1.203     brouard  2534:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2535:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2536: #ifdef LINMINORIGINAL
1.188     brouard  2537:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2538: #else
                   2539:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2540:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2541: #endif
                   2542:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2543:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2544:                                /* because that direction will be replaced unless the gain del is small */
                   2545:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2546:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2547:                                /* with the new direction. */
                   2548:                                del=fabs(fptt-(*fret)); 
                   2549:                                ibig=i; 
1.126     brouard  2550:       } 
                   2551: #ifdef DEBUG
                   2552:       printf("%d %.12e",i,(*fret));
                   2553:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2554:       for (j=1;j<=n;j++) {
1.224     brouard  2555:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2556:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2557:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2558:       }
                   2559:       for(j=1;j<=n;j++) {
1.225     brouard  2560:                                printf(" p(%d)=%.12e",j,p[j]);
                   2561:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2562:       }
                   2563:       printf("\n");
                   2564:       fprintf(ficlog,"\n");
                   2565: #endif
1.187     brouard  2566:     } /* end loop on each direction i */
                   2567:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2568:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2569:     /* New value of last point Pn is not computed, P(n-1) */
1.319     brouard  2570:     for(j=1;j<=n;j++) {
                   2571:       if(flatdir[j] >0){
                   2572:         printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2573:         fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
1.302     brouard  2574:       }
1.319     brouard  2575:       /* printf("\n"); */
                   2576:       /* fprintf(ficlog,"\n"); */
                   2577:     }
1.243     brouard  2578:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2579:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2580:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2581:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2582:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2583:       /* decreased of more than 3.84  */
                   2584:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2585:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2586:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2587:                        
1.188     brouard  2588:       /* Starting the program with initial values given by a former maximization will simply change */
                   2589:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2590:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2591:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2592: #ifdef DEBUG
                   2593:       int k[2],l;
                   2594:       k[0]=1;
                   2595:       k[1]=-1;
                   2596:       printf("Max: %.12e",(*func)(p));
                   2597:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2598:       for (j=1;j<=n;j++) {
                   2599:        printf(" %.12e",p[j]);
                   2600:        fprintf(ficlog," %.12e",p[j]);
                   2601:       }
                   2602:       printf("\n");
                   2603:       fprintf(ficlog,"\n");
                   2604:       for(l=0;l<=1;l++) {
                   2605:        for (j=1;j<=n;j++) {
                   2606:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2607:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2608:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2609:        }
                   2610:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2611:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2612:       }
                   2613: #endif
                   2614: 
                   2615:       free_vector(xit,1,n); 
                   2616:       free_vector(xits,1,n); 
                   2617:       free_vector(ptt,1,n); 
                   2618:       free_vector(pt,1,n); 
                   2619:       return; 
1.192     brouard  2620:     } /* enough precision */ 
1.240     brouard  2621:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2622:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2623:       ptt[j]=2.0*p[j]-pt[j]; 
                   2624:       xit[j]=p[j]-pt[j]; 
                   2625:       pt[j]=p[j]; 
                   2626:     } 
1.181     brouard  2627:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2628: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2629:                if (*iter <=4) {
1.225     brouard  2630: #else
                   2631: #endif
1.224     brouard  2632: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2633: #else
1.161     brouard  2634:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2635: #endif
1.162     brouard  2636:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2637:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2638:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2639:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2640:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2641:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2642:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2643:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2644:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2645:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2646:       /* mu² and del² are equal when f3=f1 */
                   2647:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2648:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2649:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2650:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2651: #ifdef NRCORIGINAL
                   2652:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2653: #else
                   2654:       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  2655:       t= t- del*SQR(fp-fptt);
1.183     brouard  2656: #endif
1.202     brouard  2657:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2658: #ifdef DEBUG
1.181     brouard  2659:       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);
                   2660:       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  2661:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2662:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2663:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2664:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2665:       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);
                   2666:       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);
                   2667: #endif
1.183     brouard  2668: #ifdef POWELLORIGINAL
                   2669:       if (t < 0.0) { /* Then we use it for new direction */
                   2670: #else
1.182     brouard  2671:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2672:                                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  2673:         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  2674:         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  2675:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2676:       } 
1.181     brouard  2677:       if (directest < 0.0) { /* Then we use it for new direction */
                   2678: #endif
1.191     brouard  2679: #ifdef DEBUGLINMIN
1.234     brouard  2680:        printf("Before linmin in direction P%d-P0\n",n);
                   2681:        for (j=1;j<=n;j++) {
                   2682:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2683:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2684:          if(j % ncovmodel == 0){
                   2685:            printf("\n");
                   2686:            fprintf(ficlog,"\n");
                   2687:          }
                   2688:        }
1.224     brouard  2689: #endif
                   2690: #ifdef LINMINORIGINAL
1.234     brouard  2691:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2692: #else
1.234     brouard  2693:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2694:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2695: #endif
1.234     brouard  2696:        
1.191     brouard  2697: #ifdef DEBUGLINMIN
1.234     brouard  2698:        for (j=1;j<=n;j++) { 
                   2699:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2700:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2701:          if(j % ncovmodel == 0){
                   2702:            printf("\n");
                   2703:            fprintf(ficlog,"\n");
                   2704:          }
                   2705:        }
1.224     brouard  2706: #endif
1.234     brouard  2707:        for (j=1;j<=n;j++) { 
                   2708:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2709:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2710:        }
1.224     brouard  2711: #ifdef LINMINORIGINAL
                   2712: #else
1.234     brouard  2713:        for (j=1, flatd=0;j<=n;j++) {
                   2714:          if(flatdir[j]>0)
                   2715:            flatd++;
                   2716:        }
                   2717:        if(flatd >0){
1.255     brouard  2718:          printf("%d flat directions: ",flatd);
                   2719:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  2720:          for (j=1;j<=n;j++) { 
                   2721:            if(flatdir[j]>0){
                   2722:              printf("%d ",j);
                   2723:              fprintf(ficlog,"%d ",j);
                   2724:            }
                   2725:          }
                   2726:          printf("\n");
                   2727:          fprintf(ficlog,"\n");
1.319     brouard  2728: #ifdef FLATSUP
                   2729:           free_vector(xit,1,n); 
                   2730:           free_vector(xits,1,n); 
                   2731:           free_vector(ptt,1,n); 
                   2732:           free_vector(pt,1,n); 
                   2733:           return;
                   2734: #endif
1.234     brouard  2735:        }
1.191     brouard  2736: #endif
1.234     brouard  2737:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2738:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2739:        
1.126     brouard  2740: #ifdef DEBUG
1.234     brouard  2741:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2742:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2743:        for(j=1;j<=n;j++){
                   2744:          printf(" %lf",xit[j]);
                   2745:          fprintf(ficlog," %lf",xit[j]);
                   2746:        }
                   2747:        printf("\n");
                   2748:        fprintf(ficlog,"\n");
1.126     brouard  2749: #endif
1.192     brouard  2750:       } /* end of t or directest negative */
1.224     brouard  2751: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2752: #else
1.234     brouard  2753:       } /* end if (fptt < fp)  */
1.192     brouard  2754: #endif
1.225     brouard  2755: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2756:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2757: #else
1.224     brouard  2758: #endif
1.234     brouard  2759:                } /* loop iteration */ 
1.126     brouard  2760: } 
1.234     brouard  2761:   
1.126     brouard  2762: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2763:   
1.235     brouard  2764:   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  2765:   {
1.279     brouard  2766:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij 
                   2767:      *   (and selected quantitative values in nres)
                   2768:      *  by left multiplying the unit
                   2769:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   2770:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   2771:      * Wx is row vector: population in state 1, population in state 2, population dead
                   2772:      * or prevalence in state 1, prevalence in state 2, 0
                   2773:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   2774:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   2775:      * Output is prlim.
                   2776:      * Initial matrix pimij 
                   2777:      */
1.206     brouard  2778:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2779:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2780:   /*  0,                   0                  , 1} */
                   2781:   /*
                   2782:    * and after some iteration: */
                   2783:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2784:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2785:   /*  0,                   0                  , 1} */
                   2786:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2787:   /* {0.51571254859325999, 0.4842874514067399, */
                   2788:   /*  0.51326036147820708, 0.48673963852179264} */
                   2789:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2790:     
1.332   ! brouard  2791:     int i, ii,j,k, k1;
1.209     brouard  2792:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2793:   /* double **matprod2(); */ /* test */
1.218     brouard  2794:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2795:   double **newm;
1.209     brouard  2796:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2797:   int ncvloop=0;
1.288     brouard  2798:   int first=0;
1.169     brouard  2799:   
1.209     brouard  2800:   min=vector(1,nlstate);
                   2801:   max=vector(1,nlstate);
                   2802:   meandiff=vector(1,nlstate);
                   2803: 
1.218     brouard  2804:        /* Starting with matrix unity */
1.126     brouard  2805:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2806:     for (j=1;j<=nlstate+ndeath;j++){
                   2807:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2808:     }
1.169     brouard  2809:   
                   2810:   cov[1]=1.;
                   2811:   
                   2812:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2813:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2814:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2815:     ncvloop++;
1.126     brouard  2816:     newm=savm;
                   2817:     /* Covariates have to be included here again */
1.138     brouard  2818:     cov[2]=agefin;
1.319     brouard  2819:      if(nagesqr==1){
                   2820:       cov[3]= agefin*agefin;
                   2821:      }
1.332   ! brouard  2822:      /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
        !          2823:      /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
        !          2824:      for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
        !          2825:        if(Typevar[k1]==1){ /* A product with age */
        !          2826:         cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
        !          2827:        }else{
        !          2828:         cov[2+nagesqr+k1]=precov[nres][k1];
        !          2829:        }
        !          2830:      }/* End of loop on model equation */
        !          2831:      
        !          2832: /* Start of old code (replaced by a loop on position in the model equation */
        !          2833:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only of the model *\/ */
        !          2834:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
        !          2835:     /*   /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; *\/ */
        !          2836:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TnsdVar[TvarsD[k]])]; */
        !          2837:     /*   /\* model = 1 +age + V1*V3 + age*V1 + V2 + V1 + age*V2 + V3 + V3*age + V1*V2  */
        !          2838:     /*    * k                  1        2      3    4      5      6     7        8 */
        !          2839:     /*    *cov[]   1    2      3        4      5    6      7      8     9       10 */
        !          2840:     /*    *TypeVar[k]          2        1      0    0      1      0     1        2 */
        !          2841:     /*    *Dummy[k]            0        2      0    0      2      0     2        0 */
        !          2842:     /*    *Tvar[k]             4        1      2    1      2      3     3        5 */
        !          2843:     /*    *nsd=3                              (1)  (2)           (3) */
        !          2844:     /*    *TvarsD[nsd]                      [1]=2    1             3 */
        !          2845:     /*    *TnsdVar                          [2]=2 [1]=1         [3]=3 */
        !          2846:     /*    *TvarsDind[nsd](=k)               [1]=3 [2]=4         [3]=6 */
        !          2847:     /*    *Tage[]                  [1]=1                  [2]=2      [3]=3 */
        !          2848:     /*    *Tvard[]       [1][1]=1                                           [2][1]=1 */
        !          2849:     /*    *                   [1][2]=3                                           [2][2]=2 */
        !          2850:     /*    *Tprod[](=k)     [1]=1                                              [2]=8 */
        !          2851:     /*    *TvarsDp(=Tvar)   [1]=1            [2]=2             [3]=3          [4]=5 */
        !          2852:     /*    *TvarD (=k)       [1]=1            [2]=3 [3]=4       [3]=6          [4]=6 */
        !          2853:     /*    *TvarsDpType */
        !          2854:     /*    *si model= 1 + age + V3 + V2*age + V2 + V3*age */
        !          2855:     /*    * nsd=1              (1)           (2) */
        !          2856:     /*    *TvarsD[nsd]          3             2 */
        !          2857:     /*    *TnsdVar           (3)=1          (2)=2 */
        !          2858:     /*    *TvarsDind[nsd](=k)  [1]=1        [2]=3 */
        !          2859:     /*    *Tage[]                  [1]=2           [2]= 3    */
        !          2860:     /*    *\/ */
        !          2861:     /*   /\* cov[++k1]=nbcode[TvarsD[k]][codtabm(ij,k)]; *\/ */
        !          2862:     /*   /\* 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)); *\/ */
        !          2863:     /* } */
        !          2864:     /* for (k=1; k<=nsq;k++) { /\* For single quantitative varying covariates only of the model *\/ */
        !          2865:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
        !          2866:     /*   /\* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 *\/ */
        !          2867:     /*   /\* cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
        !          2868:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][resultmodel[nres][k1]] */
        !          2869:     /*   /\* cov[++k1]=Tqresult[nres][k];  *\/ */
        !          2870:     /*   /\* 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]); *\/ */
        !          2871:     /* } */
        !          2872:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
        !          2873:     /*   if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
        !          2874:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
        !          2875:     /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
        !          2876:     /*   } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
        !          2877:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
        !          2878:     /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
        !          2879:     /*   } */
        !          2880:     /*   /\* 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]); *\/ */
        !          2881:     /* } */
        !          2882:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
        !          2883:     /*   /\* 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]); *\/ */
        !          2884:     /*   if(Dummy[Tvard[k][1]]==0){ */
        !          2885:     /*         if(Dummy[Tvard[k][2]]==0){ */
        !          2886:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
        !          2887:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
        !          2888:     /*         }else{ */
        !          2889:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
        !          2890:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
        !          2891:     /*         } */
        !          2892:     /*   }else{ */
        !          2893:     /*         if(Dummy[Tvard[k][2]]==0){ */
        !          2894:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
        !          2895:     /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
        !          2896:     /*         }else{ */
        !          2897:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
        !          2898:     /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
        !          2899:     /*         } */
        !          2900:     /*   } */
        !          2901:     /* } /\* End product without age *\/ */
        !          2902: /* ENd of old code */
1.138     brouard  2903:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2904:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2905:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2906:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2907:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.319     brouard  2908:     /* age and covariate values of ij are in 'cov' */
1.142     brouard  2909:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2910:     
1.126     brouard  2911:     savm=oldm;
                   2912:     oldm=newm;
1.209     brouard  2913: 
                   2914:     for(j=1; j<=nlstate; j++){
                   2915:       max[j]=0.;
                   2916:       min[j]=1.;
                   2917:     }
                   2918:     for(i=1;i<=nlstate;i++){
                   2919:       sumnew=0;
                   2920:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2921:       for(j=1; j<=nlstate; j++){ 
                   2922:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2923:        max[j]=FMAX(max[j],prlim[i][j]);
                   2924:        min[j]=FMIN(min[j],prlim[i][j]);
                   2925:       }
                   2926:     }
                   2927: 
1.126     brouard  2928:     maxmax=0.;
1.209     brouard  2929:     for(j=1; j<=nlstate; j++){
                   2930:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2931:       maxmax=FMAX(maxmax,meandiff[j]);
                   2932:       /* 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  2933:     } /* j loop */
1.203     brouard  2934:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2935:     /* 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  2936:     if(maxmax < ftolpl){
1.209     brouard  2937:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2938:       free_vector(min,1,nlstate);
                   2939:       free_vector(max,1,nlstate);
                   2940:       free_vector(meandiff,1,nlstate);
1.126     brouard  2941:       return prlim;
                   2942:     }
1.288     brouard  2943:   } /* agefin loop */
1.208     brouard  2944:     /* After some age loop it doesn't converge */
1.288     brouard  2945:   if(!first){
                   2946:     first=1;
                   2947:     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  2948:     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);
                   2949:   }else if (first >=1 && first <10){
                   2950:     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);
                   2951:     first++;
                   2952:   }else if (first ==10){
                   2953:     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);
                   2954:     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");
                   2955:     fprintf(ficlog,"Warning: the stable prevalence no convergence; too many cases, giving up noticing, even in log file\n");
                   2956:     first++;
1.288     brouard  2957:   }
                   2958: 
1.209     brouard  2959:   /* 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); */
                   2960:   free_vector(min,1,nlstate);
                   2961:   free_vector(max,1,nlstate);
                   2962:   free_vector(meandiff,1,nlstate);
1.208     brouard  2963:   
1.169     brouard  2964:   return prlim; /* should not reach here */
1.126     brouard  2965: }
                   2966: 
1.217     brouard  2967: 
                   2968:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   2969: 
1.218     brouard  2970:  /* 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) */
                   2971:  /* 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  2972:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  2973: {
1.264     brouard  2974:   /* 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  2975:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   2976:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2977:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2978:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2979:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2980:   /* Initial matrix pimij */
                   2981:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2982:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2983:   /*  0,                   0                  , 1} */
                   2984:   /*
                   2985:    * and after some iteration: */
                   2986:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2987:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2988:   /*  0,                   0                  , 1} */
                   2989:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2990:   /* {0.51571254859325999, 0.4842874514067399, */
                   2991:   /*  0.51326036147820708, 0.48673963852179264} */
                   2992:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2993: 
1.332   ! brouard  2994:   int i, ii,j,k, k1;
1.247     brouard  2995:   int first=0;
1.217     brouard  2996:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   2997:   /* double **matprod2(); */ /* test */
                   2998:   double **out, cov[NCOVMAX+1], **bmij();
                   2999:   double **newm;
1.218     brouard  3000:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   3001:   double        **oldm, **savm;  /* for use */
                   3002: 
1.217     brouard  3003:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   3004:   int ncvloop=0;
                   3005:   
                   3006:   min=vector(1,nlstate);
                   3007:   max=vector(1,nlstate);
                   3008:   meandiff=vector(1,nlstate);
                   3009: 
1.266     brouard  3010:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   3011:   oldm=oldms; savm=savms;
                   3012:   
                   3013:   /* Starting with matrix unity */
                   3014:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   3015:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  3016:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3017:     }
                   3018:   
                   3019:   cov[1]=1.;
                   3020:   
                   3021:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3022:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  3023:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  3024:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   3025:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  3026:     ncvloop++;
1.218     brouard  3027:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   3028:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  3029:     /* Covariates have to be included here again */
                   3030:     cov[2]=agefin;
1.319     brouard  3031:     if(nagesqr==1){
1.217     brouard  3032:       cov[3]= agefin*agefin;;
1.319     brouard  3033:     }
1.332   ! brouard  3034:     for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
        !          3035:       if(Typevar[k1]==1){ /* A product with age */
        !          3036:        cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.242     brouard  3037:       }else{
1.332   ! brouard  3038:        cov[2+nagesqr+k1]=precov[nres][k1];
1.242     brouard  3039:       }
1.332   ! brouard  3040:     }/* End of loop on model equation */
        !          3041: 
        !          3042: /* Old code */ 
        !          3043: 
        !          3044:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
        !          3045:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
        !          3046:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; */
        !          3047:     /*   /\* 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)); *\/ */
        !          3048:     /* } */
        !          3049:     /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
        !          3050:     /* /\*   /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
        !          3051:     /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
        !          3052:     /* /\*   /\\* 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])]); *\\/ *\/ */
        !          3053:     /* /\* } *\/ */
        !          3054:     /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
        !          3055:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
        !          3056:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
        !          3057:     /*   /\* 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]); *\/ */
        !          3058:     /* } */
        !          3059:     /* /\* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; *\/ */
        !          3060:     /* /\* for (k=1; k<=cptcovprod;k++) /\\* Useless *\\/ *\/ */
        !          3061:     /* /\*   /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\\/ *\/ */
        !          3062:     /* /\*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
        !          3063:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
        !          3064:     /*   /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age *\\/ ERROR ???*\/ */
        !          3065:     /*   if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
        !          3066:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
        !          3067:     /*   } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
        !          3068:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
        !          3069:     /*   } */
        !          3070:     /*   /\* 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]); *\/ */
        !          3071:     /* } */
        !          3072:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
        !          3073:     /*   /\* 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]); *\/ */
        !          3074:     /*   if(Dummy[Tvard[k][1]]==0){ */
        !          3075:     /*         if(Dummy[Tvard[k][2]]==0){ */
        !          3076:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
        !          3077:     /*         }else{ */
        !          3078:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
        !          3079:     /*         } */
        !          3080:     /*   }else{ */
        !          3081:     /*         if(Dummy[Tvard[k][2]]==0){ */
        !          3082:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
        !          3083:     /*         }else{ */
        !          3084:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
        !          3085:     /*         } */
        !          3086:     /*   } */
        !          3087:     /* } */
1.217     brouard  3088:     
                   3089:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3090:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3091:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   3092:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3093:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  3094:                /* ij should be linked to the correct index of cov */
                   3095:                /* age and covariate values ij are in 'cov', but we need to pass
                   3096:                 * ij for the observed prevalence at age and status and covariate
                   3097:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   3098:                 */
                   3099:     /* 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 *\/ */
                   3100:     /* 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 *\/ */
                   3101:     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  3102:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  3103:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   3104:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   3105:     /*         printf("%d newm= ",i); */
                   3106:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3107:     /*           printf("%f ",newm[i][j]); */
                   3108:     /*         } */
                   3109:     /*         printf("oldm * "); */
                   3110:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3111:     /*           printf("%f ",oldm[i][j]); */
                   3112:     /*         } */
1.268     brouard  3113:     /*         printf(" bmmij "); */
1.266     brouard  3114:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3115:     /*           printf("%f ",pmmij[i][j]); */
                   3116:     /*         } */
                   3117:     /*         printf("\n"); */
                   3118:     /*   } */
                   3119:     /* } */
1.217     brouard  3120:     savm=oldm;
                   3121:     oldm=newm;
1.266     brouard  3122: 
1.217     brouard  3123:     for(j=1; j<=nlstate; j++){
                   3124:       max[j]=0.;
                   3125:       min[j]=1.;
                   3126:     }
                   3127:     for(j=1; j<=nlstate; j++){ 
                   3128:       for(i=1;i<=nlstate;i++){
1.234     brouard  3129:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   3130:        bprlim[i][j]= newm[i][j];
                   3131:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   3132:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  3133:       }
                   3134:     }
1.218     brouard  3135:                
1.217     brouard  3136:     maxmax=0.;
                   3137:     for(i=1; i<=nlstate; i++){
1.318     brouard  3138:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column, could be nan! */
1.217     brouard  3139:       maxmax=FMAX(maxmax,meandiff[i]);
                   3140:       /* 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  3141:     } /* i loop */
1.217     brouard  3142:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  3143:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3144:     if(maxmax < ftolpl){
1.220     brouard  3145:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3146:       free_vector(min,1,nlstate);
                   3147:       free_vector(max,1,nlstate);
                   3148:       free_vector(meandiff,1,nlstate);
                   3149:       return bprlim;
                   3150:     }
1.288     brouard  3151:   } /* agefin loop */
1.217     brouard  3152:     /* After some age loop it doesn't converge */
1.288     brouard  3153:   if(!first){
1.247     brouard  3154:     first=1;
                   3155:     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\
                   3156: 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);
                   3157:   }
                   3158:   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  3159: 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);
                   3160:   /* 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); */
                   3161:   free_vector(min,1,nlstate);
                   3162:   free_vector(max,1,nlstate);
                   3163:   free_vector(meandiff,1,nlstate);
                   3164:   
                   3165:   return bprlim; /* should not reach here */
                   3166: }
                   3167: 
1.126     brouard  3168: /*************** transition probabilities ***************/ 
                   3169: 
                   3170: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   3171: {
1.138     brouard  3172:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  3173:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  3174:      model to the ncovmodel covariates (including constant and age).
                   3175:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3176:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3177:      ncth covariate in the global vector x is given by the formula:
                   3178:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3179:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3180:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3181:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  3182:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  3183:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  3184:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  3185:   */
                   3186:   double s1, lnpijopii;
1.126     brouard  3187:   /*double t34;*/
1.164     brouard  3188:   int i,j, nc, ii, jj;
1.126     brouard  3189: 
1.223     brouard  3190:   for(i=1; i<= nlstate; i++){
                   3191:     for(j=1; j<i;j++){
                   3192:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3193:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3194:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3195:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3196:       }
                   3197:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3198:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3199:     }
                   3200:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3201:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3202:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3203:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3204:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3205:       }
                   3206:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3207:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3208:     }
                   3209:   }
1.218     brouard  3210:   
1.223     brouard  3211:   for(i=1; i<= nlstate; i++){
                   3212:     s1=0;
                   3213:     for(j=1; j<i; j++){
                   3214:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.330     brouard  3215:       /* 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  3216:     }
                   3217:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3218:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.330     brouard  3219:       /* 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  3220:     }
                   3221:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3222:     ps[i][i]=1./(s1+1.);
                   3223:     /* Computing other pijs */
                   3224:     for(j=1; j<i; j++)
1.325     brouard  3225:       ps[i][j]= exp(ps[i][j])*ps[i][i];/* Bug valgrind */
1.223     brouard  3226:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3227:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3228:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3229:   } /* end i */
1.218     brouard  3230:   
1.223     brouard  3231:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3232:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3233:       ps[ii][jj]=0;
                   3234:       ps[ii][ii]=1;
                   3235:     }
                   3236:   }
1.294     brouard  3237: 
                   3238: 
1.223     brouard  3239:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3240:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3241:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3242:   /*   } */
                   3243:   /*   printf("\n "); */
                   3244:   /* } */
                   3245:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3246:   /*
                   3247:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  3248:                goto end;*/
1.266     brouard  3249:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  3250: }
                   3251: 
1.218     brouard  3252: /*************** backward transition probabilities ***************/ 
                   3253: 
                   3254:  /* 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 ) */
                   3255: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   3256:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   3257: {
1.302     brouard  3258:   /* 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  3259:    * 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  3260:    */
1.218     brouard  3261:   int i, ii, j,k;
1.222     brouard  3262:   
                   3263:   double **out, **pmij();
                   3264:   double sumnew=0.;
1.218     brouard  3265:   double agefin;
1.292     brouard  3266:   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  3267:   double **dnewm, **dsavm, **doldm;
                   3268:   double **bbmij;
                   3269:   
1.218     brouard  3270:   doldm=ddoldms; /* global pointers */
1.222     brouard  3271:   dnewm=ddnewms;
                   3272:   dsavm=ddsavms;
1.318     brouard  3273: 
                   3274:   /* Debug */
                   3275:   /* printf("Bmij ij=%d, cov[2}=%f\n", ij, cov[2]); */
1.222     brouard  3276:   agefin=cov[2];
1.268     brouard  3277:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  3278:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  3279:      the observed prevalence (with this covariate ij) at beginning of transition */
                   3280:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  3281: 
                   3282:   /* P_x */
1.325     brouard  3283:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm *//* Bug valgrind */
1.268     brouard  3284:   /* outputs pmmij which is a stochastic matrix in row */
                   3285: 
                   3286:   /* Diag(w_x) */
1.292     brouard  3287:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  3288:   sumnew=0.;
1.269     brouard  3289:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  3290:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  3291:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  3292:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   3293:   }
                   3294:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   3295:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3296:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  3297:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  3298:     }
                   3299:   }else{
                   3300:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3301:       for (j=1;j<=nlstate+ndeath;j++)
                   3302:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   3303:     }
                   3304:     /* if(sumnew <0.9){ */
                   3305:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   3306:     /* } */
                   3307:   }
                   3308:   k3=0.0;  /* We put the last diagonal to 0 */
                   3309:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   3310:       doldm[ii][ii]= k3;
                   3311:   }
                   3312:   /* End doldm, At the end doldm is diag[(w_i)] */
                   3313:   
1.292     brouard  3314:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   3315:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  3316: 
1.292     brouard  3317:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  3318:   /* 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  3319:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  3320:     sumnew=0.;
1.222     brouard  3321:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  3322:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  3323:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  3324:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  3325:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  3326:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  3327:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3328:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  3329:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3330:        /* }else */
1.268     brouard  3331:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   3332:     } /*End ii */
                   3333:   } /* 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 */
                   3334: 
1.292     brouard  3335:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  3336:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  3337:   /* end bmij */
1.266     brouard  3338:   return ps; /*pointer is unchanged */
1.218     brouard  3339: }
1.217     brouard  3340: /*************** transition probabilities ***************/ 
                   3341: 
1.218     brouard  3342: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  3343: {
                   3344:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3345:      computes the probability to be observed in state j being in state i by appying the
                   3346:      model to the ncovmodel covariates (including constant and age).
                   3347:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3348:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3349:      ncth covariate in the global vector x is given by the formula:
                   3350:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3351:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3352:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3353:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3354:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   3355:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3356:   */
                   3357:   double s1, lnpijopii;
                   3358:   /*double t34;*/
                   3359:   int i,j, nc, ii, jj;
                   3360: 
1.234     brouard  3361:   for(i=1; i<= nlstate; i++){
                   3362:     for(j=1; j<i;j++){
                   3363:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3364:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3365:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3366:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3367:       }
                   3368:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3369:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3370:     }
                   3371:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3372:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3373:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3374:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3375:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3376:       }
                   3377:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3378:     }
                   3379:   }
                   3380:   
                   3381:   for(i=1; i<= nlstate; i++){
                   3382:     s1=0;
                   3383:     for(j=1; j<i; j++){
                   3384:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3385:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3386:     }
                   3387:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3388:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3389:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3390:     }
                   3391:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3392:     ps[i][i]=1./(s1+1.);
                   3393:     /* Computing other pijs */
                   3394:     for(j=1; j<i; j++)
                   3395:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3396:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3397:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3398:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3399:   } /* end i */
                   3400:   
                   3401:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3402:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3403:       ps[ii][jj]=0;
                   3404:       ps[ii][ii]=1;
                   3405:     }
                   3406:   }
1.296     brouard  3407:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  3408:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3409:     s1=0.;
                   3410:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   3411:       s1+=ps[ii][jj];
                   3412:     }
                   3413:     for(ii=1; ii<= nlstate; ii++){
                   3414:       ps[ii][jj]=ps[ii][jj]/s1;
                   3415:     }
                   3416:   }
                   3417:   /* Transposition */
                   3418:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3419:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   3420:       s1=ps[ii][jj];
                   3421:       ps[ii][jj]=ps[jj][ii];
                   3422:       ps[jj][ii]=s1;
                   3423:     }
                   3424:   }
                   3425:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3426:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3427:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3428:   /*   } */
                   3429:   /*   printf("\n "); */
                   3430:   /* } */
                   3431:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3432:   /*
                   3433:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3434:     goto end;*/
                   3435:   return ps;
1.217     brouard  3436: }
                   3437: 
                   3438: 
1.126     brouard  3439: /**************** Product of 2 matrices ******************/
                   3440: 
1.145     brouard  3441: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  3442: {
                   3443:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3444:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3445:   /* in, b, out are matrice of pointers which should have been initialized 
                   3446:      before: only the contents of out is modified. The function returns
                   3447:      a pointer to pointers identical to out */
1.145     brouard  3448:   int i, j, k;
1.126     brouard  3449:   for(i=nrl; i<= nrh; i++)
1.145     brouard  3450:     for(k=ncolol; k<=ncoloh; k++){
                   3451:       out[i][k]=0.;
                   3452:       for(j=ncl; j<=nch; j++)
                   3453:        out[i][k] +=in[i][j]*b[j][k];
                   3454:     }
1.126     brouard  3455:   return out;
                   3456: }
                   3457: 
                   3458: 
                   3459: /************* Higher Matrix Product ***************/
                   3460: 
1.235     brouard  3461: 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  3462: {
1.332   ! brouard  3463:   /* Computes the transition matrix starting at age 'age' and dummies values in each resultline (loop on ij to find the corresponding combination) to over 
1.126     brouard  3464:      'nhstepm*hstepm*stepm' months (i.e. until
                   3465:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3466:      nhstepm*hstepm matrices. 
                   3467:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3468:      (typically every 2 years instead of every month which is too big 
                   3469:      for the memory).
                   3470:      Model is determined by parameters x and covariates have to be 
                   3471:      included manually here. 
                   3472: 
                   3473:      */
                   3474: 
1.330     brouard  3475:   int i, j, d, h, k, k1;
1.131     brouard  3476:   double **out, cov[NCOVMAX+1];
1.126     brouard  3477:   double **newm;
1.187     brouard  3478:   double agexact;
1.214     brouard  3479:   double agebegin, ageend;
1.126     brouard  3480: 
                   3481:   /* Hstepm could be zero and should return the unit matrix */
                   3482:   for (i=1;i<=nlstate+ndeath;i++)
                   3483:     for (j=1;j<=nlstate+ndeath;j++){
                   3484:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3485:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3486:     }
                   3487:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3488:   for(h=1; h <=nhstepm; h++){
                   3489:     for(d=1; d <=hstepm; d++){
                   3490:       newm=savm;
                   3491:       /* Covariates have to be included here again */
                   3492:       cov[1]=1.;
1.214     brouard  3493:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3494:       cov[2]=agexact;
1.319     brouard  3495:       if(nagesqr==1){
1.227     brouard  3496:        cov[3]= agexact*agexact;
1.319     brouard  3497:       }
1.330     brouard  3498:       /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   3499:       /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   3500:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.332   ! brouard  3501:        if(Typevar[k1]==1){ /* A product with age */
        !          3502:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
        !          3503:        }else{
        !          3504:          cov[2+nagesqr+k1]=precov[nres][k1];
        !          3505:        }
        !          3506:       }/* End of loop on model equation */
        !          3507:        /* Old code */ 
        !          3508: /*     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /\* Single dummy  *\/ */
        !          3509: /* /\*    V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) *\/ */
        !          3510: /* /\*       for (k=1; k<=nsd;k++) { /\\* For single dummy covariates only *\\/ *\/ */
        !          3511: /* /\* /\\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\\/ *\/ */
        !          3512: /*     /\* codtabm(ij,k)  (1 & (ij-1) >> (k-1))+1 *\/ */
        !          3513: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
        !          3514: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
        !          3515: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
        !          3516: /* /\*    nsd         1   2                              3 *\/ /\* Counting single dummies covar fixed or tv *\/ */
        !          3517: /* /\*TvarsD[nsd]     4   3                              1 *\/ /\* ID of single dummy cova fixed or timevary*\/ */
        !          3518: /* /\*TvarsDind[k]    2   3                              9 *\/ /\* position K of single dummy cova *\/ */
        !          3519: /*       /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];or [codtabm(ij,TnsdVar[TvarsD[k]] *\/ */
        !          3520: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]]; */
        !          3521: /*       /\* 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]])); *\/ */
        !          3522: /*       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); */
        !          3523: /*       printf("hpxij new Dummy precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
        !          3524: /*     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /\* Single quantitative variables  *\/ */
        !          3525: /*       /\* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline *\/ */
        !          3526: /*       cov[2+nagesqr+k1]=Tqresult[nres][resultmodel[nres][k1]];  */
        !          3527: /*       /\* for (k=1; k<=nsq;k++) { /\\* For single varying covariates only *\\/ *\/ */
        !          3528: /*       /\*   /\\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\\/ *\/ */
        !          3529: /*       /\*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
        !          3530: /*       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]]); */
        !          3531: /*       printf("hpxij new Quanti precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
        !          3532: /*     }else if( Dummy[k1]==2 ){ /\* For dummy with age product *\/ */
        !          3533: /*       /\* Tvar[k1] Variable in the age product age*V1 is 1 *\/ */
        !          3534: /*       /\* [Tinvresult[nres][V1] is its value in the resultline nres *\/ */
        !          3535: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvar[k1]]*cov[2]; */
        !          3536: /*       printf("DhPxij Dummy with age k1=%d Tvar[%d]=%d TinvDoQresult[nres=%d][%d]=%.f age=%.2f,cov[2+%d+%d]=%.3f\n",k1,k1,Tvar[k1],nres,TinvDoQresult[nres][Tvar[k1]],cov[2],nagesqr,k1,cov[2+nagesqr+k1]); */
        !          3537: /*       printf("hpxij new Dummy with age product precov[nres=%d][k1=%d]=%.4f * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
        !          3538: 
        !          3539: /*       /\* cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];    *\/ */
        !          3540: /*       /\* for (k=1; k<=cptcovage;k++){ /\\* For product with age V1+V1*age +V4 +age*V3 *\\/ *\/ */
        !          3541: /*       /\* 1+2 Tage[1]=2 TVar[2]=1 Dummy[2]=2, Tage[2]=4 TVar[4]=3 Dummy[4]=3 quant*\/ */
        !          3542: /*       /\* *\/ */
1.330     brouard  3543: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3544: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3545: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
1.332   ! brouard  3546: /* /\*cptcovage=2                   1               2      *\/ */
        !          3547: /* /\*Tage[k]=                      5               8      *\/  */
        !          3548: /*     }else if( Dummy[k1]==3 ){ /\* For quant with age product *\/ */
        !          3549: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];        */
        !          3550: /*       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]]); */
        !          3551: /*       printf("hpxij new Quanti with age product precov[nres=%d][k1=%d] * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
        !          3552: /*       /\* if(Dummy[Tage[k]]== 2){ /\\* dummy with age *\\/ *\/ */
        !          3553: /*       /\* /\\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\\* dummy with age *\\\/ *\\/ *\/ */
        !          3554: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\\/ *\/ */
        !          3555: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\\/ *\/ */
        !          3556: /*       /\*   cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\/ */
        !          3557: /*       /\*   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); *\/ */
        !          3558: /*       /\* } else if(Dummy[Tage[k]]== 3){ /\\* quantitative with age *\\/ *\/ */
        !          3559: /*       /\*   cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; *\/ */
        !          3560: /*       /\* } *\/ */
        !          3561: /*       /\* 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]); *\/ */
        !          3562: /*     }else if(Typevar[k1]==2 ){ /\* For product (not with age) *\/ */
        !          3563: /* /\*       for (k=1; k<=cptcovprod;k++){ /\\*  For product without age *\\/ *\/ */
        !          3564: /* /\* /\\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\\/ *\/ */
        !          3565: /* /\* /\\*    k        1  2   3   4     5    6    7     8    9 *\\/ *\/ */
        !          3566: /* /\* /\\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\\/ *\/ */
        !          3567: /* /\* /\\*cptcovprod=1            1               2            *\\/ *\/ */
        !          3568: /* /\* /\\*Tprod[]=                4               7            *\\/ *\/ */
        !          3569: /* /\* /\\*Tvard[][1]             4               1             *\\/ *\/ */
        !          3570: /* /\* /\\*Tvard[][2]               3               2           *\\/ *\/ */
1.330     brouard  3571:          
1.332   ! brouard  3572: /*       /\* 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])]); *\/ */
        !          3573: /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
        !          3574: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];     */
        !          3575: /*       printf("hPxij Prod ij=%d k1=%d  cov[2+%d+%d]=%.5f Tvard[%d][1]=V%d * Tvard[%d][2]=V%d ; TinvDoQresult[nres][Tvardk[k1][1]]=%.4f * TinvDoQresult[nres][Tvardk[k1][1]]=%.4f\n",ij,k1,nagesqr,k1,cov[2+nagesqr+k1],k1,Tvardk[k1][1], k1,Tvardk[k1][2], TinvDoQresult[nres][Tvardk[k1][1]], TinvDoQresult[nres][Tvardk[k1][2]]); */
        !          3576: /*       printf("hpxij new Product no age product precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
        !          3577: 
        !          3578: /*       /\* if(Dummy[Tvardk[k1][1]]==0){ *\/ */
        !          3579: /*       /\*   if(Dummy[Tvardk[k1][2]]==0){ /\\* Product of dummies *\\/ *\/ */
        !          3580: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
        !          3581: /*           /\* cov[2+nagesqr+k1]=Tinvresult[nres][Tvardk[k1][1]] * Tinvresult[nres][Tvardk[k1][2]];   *\/ */
        !          3582: /*           /\* 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]])]; *\/ */
        !          3583: /*         /\* }else{ /\\* Product of dummy by quantitative *\\/ *\/ */
        !          3584: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,TnsdVar[Tvard[k][1]])] * Tqresult[nres][k]; *\/ */
        !          3585: /*           /\* cov[2+nagesqr+k1]=Tresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]; *\/ */
        !          3586: /*       /\*   } *\/ */
        !          3587: /*       /\* }else{ /\\* Product of quantitative by...*\\/ *\/ */
        !          3588: /*       /\*   if(Dummy[Tvard[k][2]]==0){  /\\* quant by dummy *\\/ *\/ */
        !          3589: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][Tvard[k][1]]; *\\/ *\/ */
        !          3590: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
        !          3591: /*       /\*   }else{ /\\* Product of two quant *\\/ *\/ */
        !          3592: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\\/ *\/ */
        !          3593: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
        !          3594: /*       /\*   } *\/ */
        !          3595: /*       /\* }/\\*end of products quantitative *\\/ *\/ */
        !          3596: /*     }/\*end of products *\/ */
        !          3597:       /* } /\* End of loop on model equation *\/ */
1.235     brouard  3598:       /* for (k=1; k<=cptcovn;k++)  */
                   3599:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3600:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3601:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3602:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3603:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3604:       
                   3605:       
1.126     brouard  3606:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3607:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.319     brouard  3608:       /* right multiplication of oldm by the current matrix */
1.126     brouard  3609:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3610:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3611:       /* if((int)age == 70){ */
                   3612:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3613:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3614:       /*         printf("%d pmmij ",i); */
                   3615:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3616:       /*           printf("%f ",pmmij[i][j]); */
                   3617:       /*         } */
                   3618:       /*         printf(" oldm "); */
                   3619:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3620:       /*           printf("%f ",oldm[i][j]); */
                   3621:       /*         } */
                   3622:       /*         printf("\n"); */
                   3623:       /*       } */
                   3624:       /* } */
1.126     brouard  3625:       savm=oldm;
                   3626:       oldm=newm;
                   3627:     }
                   3628:     for(i=1; i<=nlstate+ndeath; i++)
                   3629:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  3630:        po[i][j][h]=newm[i][j];
                   3631:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3632:       }
1.128     brouard  3633:     /*printf("h=%d ",h);*/
1.126     brouard  3634:   } /* end h */
1.267     brouard  3635:   /*     printf("\n H=%d \n",h); */
1.126     brouard  3636:   return po;
                   3637: }
                   3638: 
1.217     brouard  3639: /************* Higher Back Matrix Product ***************/
1.218     brouard  3640: /* 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  3641: 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  3642: {
1.332   ! brouard  3643:   /* For dummy covariates given in each resultline (for historical, computes the corresponding combination ij),
        !          3644:      computes the transition matrix starting at age 'age' over
1.217     brouard  3645:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3646:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3647:      nhstepm*hstepm matrices.
                   3648:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3649:      (typically every 2 years instead of every month which is too big
1.217     brouard  3650:      for the memory).
1.218     brouard  3651:      Model is determined by parameters x and covariates have to be
1.266     brouard  3652:      included manually here. Then we use a call to bmij(x and cov)
                   3653:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  3654:   */
1.217     brouard  3655: 
1.332   ! brouard  3656:   int i, j, d, h, k, k1;
1.266     brouard  3657:   double **out, cov[NCOVMAX+1], **bmij();
                   3658:   double **newm, ***newmm;
1.217     brouard  3659:   double agexact;
                   3660:   double agebegin, ageend;
1.222     brouard  3661:   double **oldm, **savm;
1.217     brouard  3662: 
1.266     brouard  3663:   newmm=po; /* To be saved */
                   3664:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  3665:   /* Hstepm could be zero and should return the unit matrix */
                   3666:   for (i=1;i<=nlstate+ndeath;i++)
                   3667:     for (j=1;j<=nlstate+ndeath;j++){
                   3668:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3669:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3670:     }
                   3671:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3672:   for(h=1; h <=nhstepm; h++){
                   3673:     for(d=1; d <=hstepm; d++){
                   3674:       newm=savm;
                   3675:       /* Covariates have to be included here again */
                   3676:       cov[1]=1.;
1.271     brouard  3677:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  3678:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
1.318     brouard  3679:         /* Debug */
                   3680:       /* printf("hBxij age=%lf, agexact=%lf\n", age, agexact); */
1.217     brouard  3681:       cov[2]=agexact;
1.332   ! brouard  3682:       if(nagesqr==1){
1.222     brouard  3683:        cov[3]= agexact*agexact;
1.332   ! brouard  3684:       }
        !          3685:       /** New code */
        !          3686:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
        !          3687:        if(Typevar[k1]==1){ /* A product with age */
        !          3688:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.325     brouard  3689:        }else{
1.332   ! brouard  3690:          cov[2+nagesqr+k1]=precov[nres][k1];
1.325     brouard  3691:        }
1.332   ! brouard  3692:       }/* End of loop on model equation */
        !          3693:       /** End of new code */
        !          3694:   /** This was old code */
        !          3695:       /* for (k=1; k<=nsd;k++){ /\* For single dummy covariates only *\//\* cptcovn error *\/ */
        !          3696:       /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
        !          3697:       /* /\* /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
        !          3698:       /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])];/\* Bug valgrind *\/ */
        !          3699:       /*   /\* 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)); *\/ */
        !          3700:       /* } */
        !          3701:       /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
        !          3702:       /*       /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
        !          3703:       /*       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
        !          3704:       /*       /\* 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]); *\/ */
        !          3705:       /* } */
        !          3706:       /* for (k=1; k<=cptcovage;k++){ /\* Should start at cptcovn+1 *\//\* For product with age *\/ */
        !          3707:       /*       /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age error!!!*\\/ *\/ */
        !          3708:       /*       if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
        !          3709:       /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
        !          3710:       /*       } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
        !          3711:       /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];  */
        !          3712:       /*       } */
        !          3713:       /*       /\* 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]); *\/ */
        !          3714:       /* } */
        !          3715:       /* for (k=1; k<=cptcovprod;k++){ /\* Useless because included in cptcovn *\/ */
        !          3716:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
        !          3717:       /*       if(Dummy[Tvard[k][1]]==0){ */
        !          3718:       /*         if(Dummy[Tvard[k][2]]==0){ */
        !          3719:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][1])]; */
        !          3720:       /*         }else{ */
        !          3721:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
        !          3722:       /*         } */
        !          3723:       /*       }else{ */
        !          3724:       /*         if(Dummy[Tvard[k][2]]==0){ */
        !          3725:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
        !          3726:       /*         }else{ */
        !          3727:       /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
        !          3728:       /*         } */
        !          3729:       /*       } */
        !          3730:       /* }                      */
        !          3731:       /* /\*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*\/ */
        !          3732:       /* /\*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*\/ */
        !          3733: /** End of old code */
        !          3734:       
1.218     brouard  3735:       /* Careful transposed matrix */
1.266     brouard  3736:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  3737:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3738:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3739:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.325     brouard  3740:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);/* Bug valgrind */
1.217     brouard  3741:       /* if((int)age == 70){ */
                   3742:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3743:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3744:       /*         printf("%d pmmij ",i); */
                   3745:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3746:       /*           printf("%f ",pmmij[i][j]); */
                   3747:       /*         } */
                   3748:       /*         printf(" oldm "); */
                   3749:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3750:       /*           printf("%f ",oldm[i][j]); */
                   3751:       /*         } */
                   3752:       /*         printf("\n"); */
                   3753:       /*       } */
                   3754:       /* } */
                   3755:       savm=oldm;
                   3756:       oldm=newm;
                   3757:     }
                   3758:     for(i=1; i<=nlstate+ndeath; i++)
                   3759:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3760:        po[i][j][h]=newm[i][j];
1.268     brouard  3761:        /* if(h==nhstepm) */
                   3762:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  3763:       }
1.268     brouard  3764:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  3765:   } /* end h */
1.268     brouard  3766:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  3767:   return po;
                   3768: }
                   3769: 
                   3770: 
1.162     brouard  3771: #ifdef NLOPT
                   3772:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3773:   double fret;
                   3774:   double *xt;
                   3775:   int j;
                   3776:   myfunc_data *d2 = (myfunc_data *) pd;
                   3777: /* xt = (p1-1); */
                   3778:   xt=vector(1,n); 
                   3779:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3780: 
                   3781:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3782:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3783:   printf("Function = %.12lf ",fret);
                   3784:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3785:   printf("\n");
                   3786:  free_vector(xt,1,n);
                   3787:   return fret;
                   3788: }
                   3789: #endif
1.126     brouard  3790: 
                   3791: /*************** log-likelihood *************/
                   3792: double func( double *x)
                   3793: {
1.226     brouard  3794:   int i, ii, j, k, mi, d, kk;
                   3795:   int ioffset=0;
                   3796:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3797:   double **out;
                   3798:   double lli; /* Individual log likelihood */
                   3799:   int s1, s2;
1.228     brouard  3800:   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  3801:   double bbh, survp;
                   3802:   long ipmx;
                   3803:   double agexact;
                   3804:   /*extern weight */
                   3805:   /* We are differentiating ll according to initial status */
                   3806:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3807:   /*for(i=1;i<imx;i++) 
                   3808:     printf(" %d\n",s[4][i]);
                   3809:   */
1.162     brouard  3810: 
1.226     brouard  3811:   ++countcallfunc;
1.162     brouard  3812: 
1.226     brouard  3813:   cov[1]=1.;
1.126     brouard  3814: 
1.226     brouard  3815:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3816:   ioffset=0;
1.226     brouard  3817:   if(mle==1){
                   3818:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3819:       /* Computes the values of the ncovmodel covariates of the model
                   3820:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3821:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   3822:         to be observed in j being in i according to the model.
                   3823:       */
1.243     brouard  3824:       ioffset=2+nagesqr ;
1.233     brouard  3825:    /* Fixed */
1.319     brouard  3826:       for (k=1; k<=ncovf;k++){ /* For each fixed covariate dummu or quant or prod */
                   3827:        /* # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi */
                   3828:         /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   3829:        /*  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  3830:         /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.319     brouard  3831:        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)*/
                   3832:        /* V1*V2 (7)  TvarFind[2]=7, TvarFind[3]=9 */
1.234     brouard  3833:       }
1.226     brouard  3834:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.319     brouard  3835:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
1.226     brouard  3836:         has been calculated etc */
                   3837:       /* For an individual i, wav[i] gives the number of effective waves */
                   3838:       /* We compute the contribution to Likelihood of each effective transition
                   3839:         mw[mi][i] is real wave of the mi th effectve wave */
                   3840:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   3841:         s2=s[mw[mi+1][i]][i];
                   3842:         And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
                   3843:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   3844:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   3845:       */
                   3846:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  3847:        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*/
                   3848:          /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; but where is the crossproduct? */
1.242     brouard  3849:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
1.234     brouard  3850:        }
                   3851:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3852:          for (j=1;j<=nlstate+ndeath;j++){
                   3853:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3854:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3855:          }
                   3856:        for(d=0; d<dh[mi][i]; d++){
                   3857:          newm=savm;
                   3858:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3859:          cov[2]=agexact;
                   3860:          if(nagesqr==1)
                   3861:            cov[3]= agexact*agexact;  /* Should be changed here */
                   3862:          for (kk=1; kk<=cptcovage;kk++) {
1.318     brouard  3863:            if(!FixedV[Tvar[Tage[kk]]])
                   3864:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   3865:            else
                   3866:              cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
1.234     brouard  3867:          }
                   3868:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3869:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3870:          savm=oldm;
                   3871:          oldm=newm;
                   3872:        } /* end mult */
                   3873:        
                   3874:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   3875:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   3876:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   3877:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   3878:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   3879:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   3880:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   3881:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  3882:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   3883:                                 * -stepm/2 to stepm/2 .
                   3884:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   3885:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   3886:                                 */
1.234     brouard  3887:        s1=s[mw[mi][i]][i];
                   3888:        s2=s[mw[mi+1][i]][i];
                   3889:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3890:        /* bias bh is positive if real duration
                   3891:         * is higher than the multiple of stepm and negative otherwise.
                   3892:         */
                   3893:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   3894:        if( s2 > nlstate){ 
                   3895:          /* i.e. if s2 is a death state and if the date of death is known 
                   3896:             then the contribution to the likelihood is the probability to 
                   3897:             die between last step unit time and current  step unit time, 
                   3898:             which is also equal to probability to die before dh 
                   3899:             minus probability to die before dh-stepm . 
                   3900:             In version up to 0.92 likelihood was computed
                   3901:             as if date of death was unknown. Death was treated as any other
                   3902:             health state: the date of the interview describes the actual state
                   3903:             and not the date of a change in health state. The former idea was
                   3904:             to consider that at each interview the state was recorded
                   3905:             (healthy, disable or death) and IMaCh was corrected; but when we
                   3906:             introduced the exact date of death then we should have modified
                   3907:             the contribution of an exact death to the likelihood. This new
                   3908:             contribution is smaller and very dependent of the step unit
                   3909:             stepm. It is no more the probability to die between last interview
                   3910:             and month of death but the probability to survive from last
                   3911:             interview up to one month before death multiplied by the
                   3912:             probability to die within a month. Thanks to Chris
                   3913:             Jackson for correcting this bug.  Former versions increased
                   3914:             mortality artificially. The bad side is that we add another loop
                   3915:             which slows down the processing. The difference can be up to 10%
                   3916:             lower mortality.
                   3917:          */
                   3918:          /* If, at the beginning of the maximization mostly, the
                   3919:             cumulative probability or probability to be dead is
                   3920:             constant (ie = 1) over time d, the difference is equal to
                   3921:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   3922:             s1 at precedent wave, to be dead a month before current
                   3923:             wave is equal to probability, being at state s1 at
                   3924:             precedent wave, to be dead at mont of the current
                   3925:             wave. Then the observed probability (that this person died)
                   3926:             is null according to current estimated parameter. In fact,
                   3927:             it should be very low but not zero otherwise the log go to
                   3928:             infinity.
                   3929:          */
1.183     brouard  3930: /* #ifdef INFINITYORIGINAL */
                   3931: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3932: /* #else */
                   3933: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   3934: /*         lli=log(mytinydouble); */
                   3935: /*       else */
                   3936: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3937: /* #endif */
1.226     brouard  3938:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3939:          
1.226     brouard  3940:        } else if  ( s2==-1 ) { /* alive */
                   3941:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3942:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3943:          /*survp += out[s1][j]; */
                   3944:          lli= log(survp);
                   3945:        }
                   3946:        else if  (s2==-4) { 
                   3947:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   3948:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3949:          lli= log(survp); 
                   3950:        } 
                   3951:        else if  (s2==-5) { 
                   3952:          for (j=1,survp=0. ; j<=2; j++)  
                   3953:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3954:          lli= log(survp); 
                   3955:        } 
                   3956:        else{
                   3957:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3958:          /*  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 */
                   3959:        } 
                   3960:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   3961:        /*if(lli ==000.0)*/
                   3962:        /*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); */
                   3963:        ipmx +=1;
                   3964:        sw += weight[i];
                   3965:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3966:        /* if (lli < log(mytinydouble)){ */
                   3967:        /*   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); */
                   3968:        /*   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]); */
                   3969:        /* } */
                   3970:       } /* end of wave */
                   3971:     } /* end of individual */
                   3972:   }  else if(mle==2){
                   3973:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.319     brouard  3974:       ioffset=2+nagesqr ;
                   3975:       for (k=1; k<=ncovf;k++)
                   3976:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];
1.226     brouard  3977:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  3978:        for(k=1; k <= ncovv ; k++){
                   3979:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
                   3980:        }
1.226     brouard  3981:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3982:          for (j=1;j<=nlstate+ndeath;j++){
                   3983:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3984:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3985:          }
                   3986:        for(d=0; d<=dh[mi][i]; d++){
                   3987:          newm=savm;
                   3988:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3989:          cov[2]=agexact;
                   3990:          if(nagesqr==1)
                   3991:            cov[3]= agexact*agexact;
                   3992:          for (kk=1; kk<=cptcovage;kk++) {
                   3993:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3994:          }
                   3995:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3996:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3997:          savm=oldm;
                   3998:          oldm=newm;
                   3999:        } /* end mult */
                   4000:       
                   4001:        s1=s[mw[mi][i]][i];
                   4002:        s2=s[mw[mi+1][i]][i];
                   4003:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4004:        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 */
                   4005:        ipmx +=1;
                   4006:        sw += weight[i];
                   4007:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4008:       } /* end of wave */
                   4009:     } /* end of individual */
                   4010:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   4011:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4012:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4013:       for(mi=1; mi<= wav[i]-1; mi++){
                   4014:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4015:          for (j=1;j<=nlstate+ndeath;j++){
                   4016:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4017:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4018:          }
                   4019:        for(d=0; d<dh[mi][i]; d++){
                   4020:          newm=savm;
                   4021:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4022:          cov[2]=agexact;
                   4023:          if(nagesqr==1)
                   4024:            cov[3]= agexact*agexact;
                   4025:          for (kk=1; kk<=cptcovage;kk++) {
                   4026:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4027:          }
                   4028:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4029:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4030:          savm=oldm;
                   4031:          oldm=newm;
                   4032:        } /* end mult */
                   4033:       
                   4034:        s1=s[mw[mi][i]][i];
                   4035:        s2=s[mw[mi+1][i]][i];
                   4036:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4037:        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 */
                   4038:        ipmx +=1;
                   4039:        sw += weight[i];
                   4040:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4041:       } /* end of wave */
                   4042:     } /* end of individual */
                   4043:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   4044:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4045:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4046:       for(mi=1; mi<= wav[i]-1; mi++){
                   4047:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4048:          for (j=1;j<=nlstate+ndeath;j++){
                   4049:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4050:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4051:          }
                   4052:        for(d=0; d<dh[mi][i]; d++){
                   4053:          newm=savm;
                   4054:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4055:          cov[2]=agexact;
                   4056:          if(nagesqr==1)
                   4057:            cov[3]= agexact*agexact;
                   4058:          for (kk=1; kk<=cptcovage;kk++) {
                   4059:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4060:          }
1.126     brouard  4061:        
1.226     brouard  4062:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4063:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4064:          savm=oldm;
                   4065:          oldm=newm;
                   4066:        } /* end mult */
                   4067:       
                   4068:        s1=s[mw[mi][i]][i];
                   4069:        s2=s[mw[mi+1][i]][i];
                   4070:        if( s2 > nlstate){ 
                   4071:          lli=log(out[s1][s2] - savm[s1][s2]);
                   4072:        } else if  ( s2==-1 ) { /* alive */
                   4073:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4074:            survp += out[s1][j];
                   4075:          lli= log(survp);
                   4076:        }else{
                   4077:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4078:        }
                   4079:        ipmx +=1;
                   4080:        sw += weight[i];
                   4081:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.126     brouard  4082: /*     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  4083:       } /* end of wave */
                   4084:     } /* end of individual */
                   4085:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   4086:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4087:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4088:       for(mi=1; mi<= wav[i]-1; mi++){
                   4089:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4090:          for (j=1;j<=nlstate+ndeath;j++){
                   4091:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4092:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4093:          }
                   4094:        for(d=0; d<dh[mi][i]; d++){
                   4095:          newm=savm;
                   4096:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4097:          cov[2]=agexact;
                   4098:          if(nagesqr==1)
                   4099:            cov[3]= agexact*agexact;
                   4100:          for (kk=1; kk<=cptcovage;kk++) {
                   4101:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4102:          }
1.126     brouard  4103:        
1.226     brouard  4104:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4105:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4106:          savm=oldm;
                   4107:          oldm=newm;
                   4108:        } /* end mult */
                   4109:       
                   4110:        s1=s[mw[mi][i]][i];
                   4111:        s2=s[mw[mi+1][i]][i];
                   4112:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4113:        ipmx +=1;
                   4114:        sw += weight[i];
                   4115:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4116:        /*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]);*/
                   4117:       } /* end of wave */
                   4118:     } /* end of individual */
                   4119:   } /* End of if */
                   4120:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   4121:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   4122:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4123:   return -l;
1.126     brouard  4124: }
                   4125: 
                   4126: /*************** log-likelihood *************/
                   4127: double funcone( double *x)
                   4128: {
1.228     brouard  4129:   /* Same as func but slower because of a lot of printf and if */
1.126     brouard  4130:   int i, ii, j, k, mi, d, kk;
1.228     brouard  4131:   int ioffset=0;
1.131     brouard  4132:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  4133:   double **out;
                   4134:   double lli; /* Individual log likelihood */
                   4135:   double llt;
                   4136:   int s1, s2;
1.228     brouard  4137:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   4138: 
1.126     brouard  4139:   double bbh, survp;
1.187     brouard  4140:   double agexact;
1.214     brouard  4141:   double agebegin, ageend;
1.126     brouard  4142:   /*extern weight */
                   4143:   /* We are differentiating ll according to initial status */
                   4144:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   4145:   /*for(i=1;i<imx;i++) 
                   4146:     printf(" %d\n",s[4][i]);
                   4147:   */
                   4148:   cov[1]=1.;
                   4149: 
                   4150:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  4151:   ioffset=0;
                   4152:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.243     brouard  4153:     /* ioffset=2+nagesqr+cptcovage; */
                   4154:     ioffset=2+nagesqr;
1.232     brouard  4155:     /* Fixed */
1.224     brouard  4156:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  4157:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
1.311     brouard  4158:     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  4159:       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)*/
                   4160: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   4161: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   4162: /*    cov[2+6]=covar[2][i]; V2  */
                   4163: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   4164: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   4165: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   4166: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   4167: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   4168: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  4169:     }
1.232     brouard  4170:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   4171:     /*   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?)*\/ */
                   4172:     /* } */
1.231     brouard  4173:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   4174:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   4175:     /* } */
1.225     brouard  4176:     
1.233     brouard  4177: 
                   4178:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.232     brouard  4179:     /* Wave varying (but not age varying) */
                   4180:       for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242     brouard  4181:        /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
                   4182:        cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
                   4183:       }
1.232     brouard  4184:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
1.242     brouard  4185:       /* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4186:       /* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
                   4187:       /* k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
                   4188:       /* cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
                   4189:       /* 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  4190:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  4191:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4192:       /*       /\* 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]); *\/ */
                   4193:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  4194:       /* } */
1.126     brouard  4195:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  4196:        for (j=1;j<=nlstate+ndeath;j++){
                   4197:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4198:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4199:        }
1.214     brouard  4200:       
                   4201:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4202:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   4203:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  4204:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  4205:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4206:          and mw[mi+1][i]. dh depends on stepm.*/
                   4207:        newm=savm;
1.247     brouard  4208:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  4209:        cov[2]=agexact;
                   4210:        if(nagesqr==1)
                   4211:          cov[3]= agexact*agexact;
                   4212:        for (kk=1; kk<=cptcovage;kk++) {
                   4213:          if(!FixedV[Tvar[Tage[kk]]])
                   4214:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4215:          else
                   4216:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
                   4217:        }
                   4218:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   4219:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4220:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4221:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4222:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   4223:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   4224:        savm=oldm;
                   4225:        oldm=newm;
1.126     brouard  4226:       } /* end mult */
                   4227:       
                   4228:       s1=s[mw[mi][i]][i];
                   4229:       s2=s[mw[mi+1][i]][i];
1.217     brouard  4230:       /* if(s2==-1){ */
1.268     brouard  4231:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  4232:       /*       /\* exit(1); *\/ */
                   4233:       /* } */
1.126     brouard  4234:       bbh=(double)bh[mi][i]/(double)stepm; 
                   4235:       /* bias is positive if real duration
                   4236:        * is higher than the multiple of stepm and negative otherwise.
                   4237:        */
                   4238:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  4239:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4240:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  4241:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   4242:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4243:        lli= log(survp);
1.126     brouard  4244:       }else if (mle==1){
1.242     brouard  4245:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  4246:       } else if(mle==2){
1.242     brouard  4247:        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  4248:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  4249:        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  4250:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  4251:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  4252:       } else{  /* mle=0 back to 1 */
1.242     brouard  4253:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4254:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  4255:       } /* End of if */
                   4256:       ipmx +=1;
                   4257:       sw += weight[i];
                   4258:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  4259:       /*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  4260:       if(globpr){
1.246     brouard  4261:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  4262:  %11.6f %11.6f %11.6f ", \
1.242     brouard  4263:                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  4264:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.242     brouard  4265:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   4266:          llt +=ll[k]*gipmx/gsw;
                   4267:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   4268:        }
                   4269:        fprintf(ficresilk," %10.6f\n", -llt);
1.126     brouard  4270:       }
1.232     brouard  4271:        } /* end of wave */
                   4272: } /* end of individual */
                   4273: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   4274: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   4275: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4276: if(globpr==0){ /* First time we count the contributions and weights */
                   4277:        gipmx=ipmx;
                   4278:        gsw=sw;
                   4279: }
                   4280: return -l;
1.126     brouard  4281: }
                   4282: 
                   4283: 
                   4284: /*************** function likelione ***********/
1.292     brouard  4285: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  4286: {
                   4287:   /* This routine should help understanding what is done with 
                   4288:      the selection of individuals/waves and
                   4289:      to check the exact contribution to the likelihood.
                   4290:      Plotting could be done.
                   4291:    */
                   4292:   int k;
                   4293: 
                   4294:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  4295:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  4296:     strcat(fileresilk,fileresu);
1.126     brouard  4297:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   4298:       printf("Problem with resultfile: %s\n", fileresilk);
                   4299:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   4300:     }
1.214     brouard  4301:     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");
                   4302:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  4303:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   4304:     for(k=1; k<=nlstate; k++) 
                   4305:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   4306:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   4307:   }
                   4308: 
1.292     brouard  4309:   *fretone=(*func)(p);
1.126     brouard  4310:   if(*globpri !=0){
                   4311:     fclose(ficresilk);
1.205     brouard  4312:     if (mle ==0)
                   4313:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   4314:     else if(mle >=1)
                   4315:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   4316:     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  4317:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  4318:       
                   4319:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  4320:       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  4321: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   4322:     }
1.207     brouard  4323:     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  4324: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4325:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  4326: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4327:     fflush(fichtm);
1.205     brouard  4328:   }
1.126     brouard  4329:   return;
                   4330: }
                   4331: 
                   4332: 
                   4333: /*********** Maximum Likelihood Estimation ***************/
                   4334: 
                   4335: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   4336: {
1.319     brouard  4337:   int i,j,k, jk, jkk=0, iter=0;
1.126     brouard  4338:   double **xi;
                   4339:   double fret;
                   4340:   double fretone; /* Only one call to likelihood */
                   4341:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  4342: 
                   4343: #ifdef NLOPT
                   4344:   int creturn;
                   4345:   nlopt_opt opt;
                   4346:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   4347:   double *lb;
                   4348:   double minf; /* the minimum objective value, upon return */
                   4349:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   4350:   myfunc_data dinst, *d = &dinst;
                   4351: #endif
                   4352: 
                   4353: 
1.126     brouard  4354:   xi=matrix(1,npar,1,npar);
                   4355:   for (i=1;i<=npar;i++)
                   4356:     for (j=1;j<=npar;j++)
                   4357:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   4358:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  4359:   strcpy(filerespow,"POW_"); 
1.126     brouard  4360:   strcat(filerespow,fileres);
                   4361:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   4362:     printf("Problem with resultfile: %s\n", filerespow);
                   4363:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   4364:   }
                   4365:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   4366:   for (i=1;i<=nlstate;i++)
                   4367:     for(j=1;j<=nlstate+ndeath;j++)
                   4368:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   4369:   fprintf(ficrespow,"\n");
1.162     brouard  4370: #ifdef POWELL
1.319     brouard  4371: #ifdef LINMINORIGINAL
                   4372: #else /* LINMINORIGINAL */
                   4373:   
                   4374:   flatdir=ivector(1,npar); 
                   4375:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   4376: #endif /*LINMINORIGINAL */
                   4377: 
                   4378: #ifdef FLATSUP
                   4379:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4380:   /* reorganizing p by suppressing flat directions */
                   4381:   for(i=1, jk=1; i <=nlstate; i++){
                   4382:     for(k=1; k <=(nlstate+ndeath); k++){
                   4383:       if (k != i) {
                   4384:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4385:         if(flatdir[jk]==1){
                   4386:           printf(" To be skipped %d%d flatdir[%d]=%d ",i,k,jk, flatdir[jk]);
                   4387:         }
                   4388:         for(j=1; j <=ncovmodel; j++){
                   4389:           printf("%12.7f ",p[jk]);
                   4390:           jk++; 
                   4391:         }
                   4392:         printf("\n");
                   4393:       }
                   4394:     }
                   4395:   }
                   4396: /* skipping */
                   4397:   /* for(i=1, jk=1, jkk=1;(flatdir[jk]==0)&& (i <=nlstate); i++){ */
                   4398:   for(i=1, jk=1, jkk=1;i <=nlstate; i++){
                   4399:     for(k=1; k <=(nlstate+ndeath); k++){
                   4400:       if (k != i) {
                   4401:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4402:         if(flatdir[jk]==1){
                   4403:           printf(" To be skipped %d%d flatdir[%d]=%d jk=%d p[%d] ",i,k,jk, flatdir[jk],jk, jk);
                   4404:           for(j=1; j <=ncovmodel;  jk++,j++){
                   4405:             printf(" p[%d]=%12.7f",jk, p[jk]);
                   4406:             /*q[jjk]=p[jk];*/
                   4407:           }
                   4408:         }else{
                   4409:           printf(" To be kept %d%d flatdir[%d]=%d jk=%d q[%d]=p[%d] ",i,k,jk, flatdir[jk],jk, jkk, jk);
                   4410:           for(j=1; j <=ncovmodel;  jk++,jkk++,j++){
                   4411:             printf(" p[%d]=%12.7f=q[%d]",jk, p[jk],jkk);
                   4412:             /*q[jjk]=p[jk];*/
                   4413:           }
                   4414:         }
                   4415:         printf("\n");
                   4416:       }
                   4417:       fflush(stdout);
                   4418:     }
                   4419:   }
                   4420:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4421: #else  /* FLATSUP */
1.126     brouard  4422:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.319     brouard  4423: #endif  /* FLATSUP */
                   4424: 
                   4425: #ifdef LINMINORIGINAL
                   4426: #else
                   4427:       free_ivector(flatdir,1,npar); 
                   4428: #endif  /* LINMINORIGINAL*/
                   4429: #endif /* POWELL */
1.126     brouard  4430: 
1.162     brouard  4431: #ifdef NLOPT
                   4432: #ifdef NEWUOA
                   4433:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   4434: #else
                   4435:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   4436: #endif
                   4437:   lb=vector(0,npar-1);
                   4438:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   4439:   nlopt_set_lower_bounds(opt, lb);
                   4440:   nlopt_set_initial_step1(opt, 0.1);
                   4441:   
                   4442:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   4443:   d->function = func;
                   4444:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   4445:   nlopt_set_min_objective(opt, myfunc, d);
                   4446:   nlopt_set_xtol_rel(opt, ftol);
                   4447:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   4448:     printf("nlopt failed! %d\n",creturn); 
                   4449:   }
                   4450:   else {
                   4451:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   4452:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   4453:     iter=1; /* not equal */
                   4454:   }
                   4455:   nlopt_destroy(opt);
                   4456: #endif
1.319     brouard  4457: #ifdef FLATSUP
                   4458:   /* npared = npar -flatd/ncovmodel; */
                   4459:   /* xired= matrix(1,npared,1,npared); */
                   4460:   /* paramred= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */
                   4461:   /* powell(pred,xired,npared,ftol,&iter,&fret,flatdir,func); */
                   4462:   /* free_matrix(xire,1,npared,1,npared); */
                   4463: #else  /* FLATSUP */
                   4464: #endif /* FLATSUP */
1.126     brouard  4465:   free_matrix(xi,1,npar,1,npar);
                   4466:   fclose(ficrespow);
1.203     brouard  4467:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   4468:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  4469:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  4470: 
                   4471: }
                   4472: 
                   4473: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  4474: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  4475: {
                   4476:   double  **a,**y,*x,pd;
1.203     brouard  4477:   /* double **hess; */
1.164     brouard  4478:   int i, j;
1.126     brouard  4479:   int *indx;
                   4480: 
                   4481:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  4482:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  4483:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   4484:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   4485:   double gompertz(double p[]);
1.203     brouard  4486:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  4487: 
                   4488:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   4489:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   4490:   for (i=1;i<=npar;i++){
1.203     brouard  4491:     printf("%d-",i);fflush(stdout);
                   4492:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  4493:    
                   4494:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   4495:     
                   4496:     /*  printf(" %f ",p[i]);
                   4497:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   4498:   }
                   4499:   
                   4500:   for (i=1;i<=npar;i++) {
                   4501:     for (j=1;j<=npar;j++)  {
                   4502:       if (j>i) { 
1.203     brouard  4503:        printf(".%d-%d",i,j);fflush(stdout);
                   4504:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   4505:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  4506:        
                   4507:        hess[j][i]=hess[i][j];    
                   4508:        /*printf(" %lf ",hess[i][j]);*/
                   4509:       }
                   4510:     }
                   4511:   }
                   4512:   printf("\n");
                   4513:   fprintf(ficlog,"\n");
                   4514: 
                   4515:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4516:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4517:   
                   4518:   a=matrix(1,npar,1,npar);
                   4519:   y=matrix(1,npar,1,npar);
                   4520:   x=vector(1,npar);
                   4521:   indx=ivector(1,npar);
                   4522:   for (i=1;i<=npar;i++)
                   4523:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   4524:   ludcmp(a,npar,indx,&pd);
                   4525: 
                   4526:   for (j=1;j<=npar;j++) {
                   4527:     for (i=1;i<=npar;i++) x[i]=0;
                   4528:     x[j]=1;
                   4529:     lubksb(a,npar,indx,x);
                   4530:     for (i=1;i<=npar;i++){ 
                   4531:       matcov[i][j]=x[i];
                   4532:     }
                   4533:   }
                   4534: 
                   4535:   printf("\n#Hessian matrix#\n");
                   4536:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   4537:   for (i=1;i<=npar;i++) { 
                   4538:     for (j=1;j<=npar;j++) { 
1.203     brouard  4539:       printf("%.6e ",hess[i][j]);
                   4540:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  4541:     }
                   4542:     printf("\n");
                   4543:     fprintf(ficlog,"\n");
                   4544:   }
                   4545: 
1.203     brouard  4546:   /* printf("\n#Covariance matrix#\n"); */
                   4547:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   4548:   /* for (i=1;i<=npar;i++) {  */
                   4549:   /*   for (j=1;j<=npar;j++) {  */
                   4550:   /*     printf("%.6e ",matcov[i][j]); */
                   4551:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   4552:   /*   } */
                   4553:   /*   printf("\n"); */
                   4554:   /*   fprintf(ficlog,"\n"); */
                   4555:   /* } */
                   4556: 
1.126     brouard  4557:   /* Recompute Inverse */
1.203     brouard  4558:   /* for (i=1;i<=npar;i++) */
                   4559:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   4560:   /* ludcmp(a,npar,indx,&pd); */
                   4561: 
                   4562:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   4563: 
                   4564:   /* for (j=1;j<=npar;j++) { */
                   4565:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   4566:   /*   x[j]=1; */
                   4567:   /*   lubksb(a,npar,indx,x); */
                   4568:   /*   for (i=1;i<=npar;i++){  */
                   4569:   /*     y[i][j]=x[i]; */
                   4570:   /*     printf("%.3e ",y[i][j]); */
                   4571:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   4572:   /*   } */
                   4573:   /*   printf("\n"); */
                   4574:   /*   fprintf(ficlog,"\n"); */
                   4575:   /* } */
                   4576: 
                   4577:   /* Verifying the inverse matrix */
                   4578: #ifdef DEBUGHESS
                   4579:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  4580: 
1.203     brouard  4581:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   4582:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  4583: 
                   4584:   for (j=1;j<=npar;j++) {
                   4585:     for (i=1;i<=npar;i++){ 
1.203     brouard  4586:       printf("%.2f ",y[i][j]);
                   4587:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  4588:     }
                   4589:     printf("\n");
                   4590:     fprintf(ficlog,"\n");
                   4591:   }
1.203     brouard  4592: #endif
1.126     brouard  4593: 
                   4594:   free_matrix(a,1,npar,1,npar);
                   4595:   free_matrix(y,1,npar,1,npar);
                   4596:   free_vector(x,1,npar);
                   4597:   free_ivector(indx,1,npar);
1.203     brouard  4598:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  4599: 
                   4600: 
                   4601: }
                   4602: 
                   4603: /*************** hessian matrix ****************/
                   4604: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  4605: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  4606:   int i;
                   4607:   int l=1, lmax=20;
1.203     brouard  4608:   double k1,k2, res, fx;
1.132     brouard  4609:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  4610:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   4611:   int k=0,kmax=10;
                   4612:   double l1;
                   4613: 
                   4614:   fx=func(x);
                   4615:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  4616:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  4617:     l1=pow(10,l);
                   4618:     delts=delt;
                   4619:     for(k=1 ; k <kmax; k=k+1){
                   4620:       delt = delta*(l1*k);
                   4621:       p2[theta]=x[theta] +delt;
1.145     brouard  4622:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  4623:       p2[theta]=x[theta]-delt;
                   4624:       k2=func(p2)-fx;
                   4625:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  4626:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  4627:       
1.203     brouard  4628: #ifdef DEBUGHESSII
1.126     brouard  4629:       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);
                   4630:       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);
                   4631: #endif
                   4632:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   4633:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   4634:        k=kmax;
                   4635:       }
                   4636:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  4637:        k=kmax; l=lmax*10;
1.126     brouard  4638:       }
                   4639:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   4640:        delts=delt;
                   4641:       }
1.203     brouard  4642:     } /* End loop k */
1.126     brouard  4643:   }
                   4644:   delti[theta]=delts;
                   4645:   return res; 
                   4646:   
                   4647: }
                   4648: 
1.203     brouard  4649: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  4650: {
                   4651:   int i;
1.164     brouard  4652:   int l=1, lmax=20;
1.126     brouard  4653:   double k1,k2,k3,k4,res,fx;
1.132     brouard  4654:   double p2[MAXPARM+1];
1.203     brouard  4655:   int k, kmax=1;
                   4656:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  4657: 
                   4658:   int firstime=0;
1.203     brouard  4659:   
1.126     brouard  4660:   fx=func(x);
1.203     brouard  4661:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  4662:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  4663:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4664:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4665:     k1=func(p2)-fx;
                   4666:   
1.203     brouard  4667:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4668:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4669:     k2=func(p2)-fx;
                   4670:   
1.203     brouard  4671:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4672:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4673:     k3=func(p2)-fx;
                   4674:   
1.203     brouard  4675:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4676:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4677:     k4=func(p2)-fx;
1.203     brouard  4678:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   4679:     if(k1*k2*k3*k4 <0.){
1.208     brouard  4680:       firstime=1;
1.203     brouard  4681:       kmax=kmax+10;
1.208     brouard  4682:     }
                   4683:     if(kmax >=10 || firstime ==1){
1.246     brouard  4684:       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);
                   4685:       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  4686:       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);
                   4687:       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);
                   4688:     }
                   4689: #ifdef DEBUGHESSIJ
                   4690:     v1=hess[thetai][thetai];
                   4691:     v2=hess[thetaj][thetaj];
                   4692:     cv12=res;
                   4693:     /* Computing eigen value of Hessian matrix */
                   4694:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4695:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4696:     if ((lc2 <0) || (lc1 <0) ){
                   4697:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4698:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4699:       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);
                   4700:       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);
                   4701:     }
1.126     brouard  4702: #endif
                   4703:   }
                   4704:   return res;
                   4705: }
                   4706: 
1.203     brouard  4707:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   4708: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   4709: /* { */
                   4710: /*   int i; */
                   4711: /*   int l=1, lmax=20; */
                   4712: /*   double k1,k2,k3,k4,res,fx; */
                   4713: /*   double p2[MAXPARM+1]; */
                   4714: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   4715: /*   int k=0,kmax=10; */
                   4716: /*   double l1; */
                   4717:   
                   4718: /*   fx=func(x); */
                   4719: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   4720: /*     l1=pow(10,l); */
                   4721: /*     delts=delt; */
                   4722: /*     for(k=1 ; k <kmax; k=k+1){ */
                   4723: /*       delt = delti*(l1*k); */
                   4724: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   4725: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4726: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4727: /*       k1=func(p2)-fx; */
                   4728:       
                   4729: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4730: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4731: /*       k2=func(p2)-fx; */
                   4732:       
                   4733: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4734: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4735: /*       k3=func(p2)-fx; */
                   4736:       
                   4737: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4738: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4739: /*       k4=func(p2)-fx; */
                   4740: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   4741: /* #ifdef DEBUGHESSIJ */
                   4742: /*       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); */
                   4743: /*       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); */
                   4744: /* #endif */
                   4745: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   4746: /*     k=kmax; */
                   4747: /*       } */
                   4748: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   4749: /*     k=kmax; l=lmax*10; */
                   4750: /*       } */
                   4751: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   4752: /*     delts=delt; */
                   4753: /*       } */
                   4754: /*     } /\* End loop k *\/ */
                   4755: /*   } */
                   4756: /*   delti[theta]=delts; */
                   4757: /*   return res;  */
                   4758: /* } */
                   4759: 
                   4760: 
1.126     brouard  4761: /************** Inverse of matrix **************/
                   4762: void ludcmp(double **a, int n, int *indx, double *d) 
                   4763: { 
                   4764:   int i,imax,j,k; 
                   4765:   double big,dum,sum,temp; 
                   4766:   double *vv; 
                   4767:  
                   4768:   vv=vector(1,n); 
                   4769:   *d=1.0; 
                   4770:   for (i=1;i<=n;i++) { 
                   4771:     big=0.0; 
                   4772:     for (j=1;j<=n;j++) 
                   4773:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  4774:     if (big == 0.0){
                   4775:       printf(" Singular Hessian matrix at row %d:\n",i);
                   4776:       for (j=1;j<=n;j++) {
                   4777:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   4778:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   4779:       }
                   4780:       fflush(ficlog);
                   4781:       fclose(ficlog);
                   4782:       nrerror("Singular matrix in routine ludcmp"); 
                   4783:     }
1.126     brouard  4784:     vv[i]=1.0/big; 
                   4785:   } 
                   4786:   for (j=1;j<=n;j++) { 
                   4787:     for (i=1;i<j;i++) { 
                   4788:       sum=a[i][j]; 
                   4789:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   4790:       a[i][j]=sum; 
                   4791:     } 
                   4792:     big=0.0; 
                   4793:     for (i=j;i<=n;i++) { 
                   4794:       sum=a[i][j]; 
                   4795:       for (k=1;k<j;k++) 
                   4796:        sum -= a[i][k]*a[k][j]; 
                   4797:       a[i][j]=sum; 
                   4798:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   4799:        big=dum; 
                   4800:        imax=i; 
                   4801:       } 
                   4802:     } 
                   4803:     if (j != imax) { 
                   4804:       for (k=1;k<=n;k++) { 
                   4805:        dum=a[imax][k]; 
                   4806:        a[imax][k]=a[j][k]; 
                   4807:        a[j][k]=dum; 
                   4808:       } 
                   4809:       *d = -(*d); 
                   4810:       vv[imax]=vv[j]; 
                   4811:     } 
                   4812:     indx[j]=imax; 
                   4813:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   4814:     if (j != n) { 
                   4815:       dum=1.0/(a[j][j]); 
                   4816:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   4817:     } 
                   4818:   } 
                   4819:   free_vector(vv,1,n);  /* Doesn't work */
                   4820: ;
                   4821: } 
                   4822: 
                   4823: void lubksb(double **a, int n, int *indx, double b[]) 
                   4824: { 
                   4825:   int i,ii=0,ip,j; 
                   4826:   double sum; 
                   4827:  
                   4828:   for (i=1;i<=n;i++) { 
                   4829:     ip=indx[i]; 
                   4830:     sum=b[ip]; 
                   4831:     b[ip]=b[i]; 
                   4832:     if (ii) 
                   4833:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   4834:     else if (sum) ii=i; 
                   4835:     b[i]=sum; 
                   4836:   } 
                   4837:   for (i=n;i>=1;i--) { 
                   4838:     sum=b[i]; 
                   4839:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   4840:     b[i]=sum/a[i][i]; 
                   4841:   } 
                   4842: } 
                   4843: 
                   4844: void pstamp(FILE *fichier)
                   4845: {
1.196     brouard  4846:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  4847: }
                   4848: 
1.297     brouard  4849: void date2dmy(double date,double *day, double *month, double *year){
                   4850:   double yp=0., yp1=0., yp2=0.;
                   4851:   
                   4852:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   4853:                        fractional in yp1 */
                   4854:   *year=yp;
                   4855:   yp2=modf((yp1*12),&yp);
                   4856:   *month=yp;
                   4857:   yp1=modf((yp2*30.5),&yp);
                   4858:   *day=yp;
                   4859:   if(*day==0) *day=1;
                   4860:   if(*month==0) *month=1;
                   4861: }
                   4862: 
1.253     brouard  4863: 
                   4864: 
1.126     brouard  4865: /************ Frequencies ********************/
1.251     brouard  4866: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  4867:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   4868:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  4869: {  /* Some frequencies as well as proposing some starting values */
1.332   ! brouard  4870:   /* Frequencies of any combination of dummy covariate used in the model equation */ 
1.265     brouard  4871:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  4872:   int iind=0, iage=0;
                   4873:   int mi; /* Effective wave */
                   4874:   int first;
                   4875:   double ***freq; /* Frequencies */
1.268     brouard  4876:   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 */
                   4877:   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  4878:   double *meanq, *stdq, *idq;
1.226     brouard  4879:   double **meanqt;
                   4880:   double *pp, **prop, *posprop, *pospropt;
                   4881:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   4882:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   4883:   double agebegin, ageend;
                   4884:     
                   4885:   pp=vector(1,nlstate);
1.251     brouard  4886:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  4887:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   4888:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   4889:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   4890:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  4891:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  4892:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  4893:   meanqt=matrix(1,lastpass,1,nqtveff);
                   4894:   strcpy(fileresp,"P_");
                   4895:   strcat(fileresp,fileresu);
                   4896:   /*strcat(fileresphtm,fileresu);*/
                   4897:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   4898:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   4899:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   4900:     exit(0);
                   4901:   }
1.240     brouard  4902:   
1.226     brouard  4903:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   4904:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   4905:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4906:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4907:     fflush(ficlog);
                   4908:     exit(70); 
                   4909:   }
                   4910:   else{
                   4911:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  4912: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4913: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4914:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4915:   }
1.319     brouard  4916:   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  4917:   
1.226     brouard  4918:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   4919:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   4920:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4921:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4922:     fflush(ficlog);
                   4923:     exit(70); 
1.240     brouard  4924:   } else{
1.226     brouard  4925:     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  4926: ,<hr size=\"2\" color=\"#EC5E5E\"> \n                                  \
1.214     brouard  4927: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4928:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4929:   }
1.319     brouard  4930:   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  4931:   
1.253     brouard  4932:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   4933:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  4934:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  4935:   j1=0;
1.126     brouard  4936:   
1.227     brouard  4937:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
                   4938:   j=cptcoveff;  /* Only dummy covariates of the model */
1.330     brouard  4939:   /* j=cptcovn;  /\* Only dummy covariates of the model *\/ */
1.226     brouard  4940:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  4941:   
                   4942:   
1.226     brouard  4943:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   4944:      reference=low_education V1=0,V2=0
                   4945:      med_educ                V1=1 V2=0, 
                   4946:      high_educ               V1=0 V2=1
1.330     brouard  4947:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcovn 
1.226     brouard  4948:   */
1.249     brouard  4949:   dateintsum=0;
                   4950:   k2cpt=0;
                   4951: 
1.253     brouard  4952:   if(cptcoveff == 0 )
1.265     brouard  4953:     nl=1;  /* Constant and age model only */
1.253     brouard  4954:   else
                   4955:     nl=2;
1.265     brouard  4956: 
                   4957:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   4958:   /* Loop on nj=1 or 2 if dummy covariates j!=0
1.330     brouard  4959:    *   Loop on j1(1 to 2**cptcovn) covariate combination
1.265     brouard  4960:    *     freq[s1][s2][iage] =0.
                   4961:    *     Loop on iind
                   4962:    *       ++freq[s1][s2][iage] weighted
                   4963:    *     end iind
                   4964:    *     if covariate and j!0
                   4965:    *       headers Variable on one line
                   4966:    *     endif cov j!=0
                   4967:    *     header of frequency table by age
                   4968:    *     Loop on age
                   4969:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   4970:    *       pos+=freq[s1][s2][iage] weighted
                   4971:    *       Loop on s1 initial state
                   4972:    *         fprintf(ficresp
                   4973:    *       end s1
                   4974:    *     end age
                   4975:    *     if j!=0 computes starting values
                   4976:    *     end compute starting values
                   4977:    *   end j1
                   4978:    * end nl 
                   4979:    */
1.253     brouard  4980:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   4981:     if(nj==1)
                   4982:       j=0;  /* First pass for the constant */
1.265     brouard  4983:     else{
1.330     brouard  4984:       j=cptcovs; /* Other passes for the covariate values */
1.265     brouard  4985:     }
1.251     brouard  4986:     first=1;
1.332   ! brouard  4987:     for (j1 = 1; j1 <= (int) pow(2,j); j1++){ /* Loop on all dummy covariates combination of the model, ie excluding quantitatives, V4=0, V3=0 for example, fixed or varying covariates */
1.251     brouard  4988:       posproptt=0.;
1.330     brouard  4989:       /*printf("cptcovn=%d Tvaraff=%d", cptcovn,Tvaraff[1]);
1.251     brouard  4990:        scanf("%d", i);*/
                   4991:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  4992:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  4993:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  4994:            freq[i][s2][m]=0;
1.251     brouard  4995:       
                   4996:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  4997:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  4998:          prop[i][m]=0;
                   4999:        posprop[i]=0;
                   5000:        pospropt[i]=0;
                   5001:       }
1.283     brouard  5002:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  5003:         idq[z1]=0.;
                   5004:         meanq[z1]=0.;
                   5005:         stdq[z1]=0.;
1.283     brouard  5006:       }
                   5007:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  5008:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  5009:       /*         meanqt[m][z1]=0.; */
                   5010:       /*       } */
                   5011:       /* }       */
1.251     brouard  5012:       /* dateintsum=0; */
                   5013:       /* k2cpt=0; */
                   5014:       
1.265     brouard  5015:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  5016:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   5017:        bool=1;
                   5018:        if(j !=0){
                   5019:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.330     brouard  5020:            if (cptcovn >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   5021:              for (z1=1; z1<=cptcovn; z1++) { /* loops on covariates in the model */
1.251     brouard  5022:                /* if(Tvaraff[z1] ==-20){ */
                   5023:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   5024:                /* }else  if(Tvaraff[z1] ==-10){ */
                   5025:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
1.330     brouard  5026:                /* }else  */ /* TODO TODO codtabm(j1,z1) or codtabm(j1,Tvaraff[z1]]z1)*/
1.332   ! brouard  5027:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]){ /* for combination j1 of covariates */
1.265     brouard  5028:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  5029:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
1.332   ! brouard  5030:                  /* 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", */
        !          5031:                  /*   bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),*/
        !          5032:                   /*   j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
1.251     brouard  5033:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   5034:                } /* Onlyf fixed */
                   5035:              } /* end z1 */
                   5036:            } /* cptcovn > 0 */
                   5037:          } /* end any */
                   5038:        }/* end j==0 */
1.265     brouard  5039:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  5040:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  5041:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  5042:            m=mw[mi][iind];
                   5043:            if(j!=0){
                   5044:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
1.330     brouard  5045:                for (z1=1; z1<=cptcovn; z1++) {
1.251     brouard  5046:                  if( Fixed[Tmodelind[z1]]==1){
                   5047:                    iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
1.332   ! brouard  5048:                    if (cotvar[m][iv][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality. If covariate's 
1.251     brouard  5049:                                                                                      value is -1, we don't select. It differs from the 
                   5050:                                                                                      constant and age model which counts them. */
                   5051:                      bool=0; /* not selected */
                   5052:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
1.332   ! brouard  5053:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) {
1.251     brouard  5054:                      bool=0;
                   5055:                    }
                   5056:                  }
                   5057:                }
                   5058:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   5059:            } /* end j==0 */
                   5060:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  5061:            if(bool==1){ /*Selected */
1.251     brouard  5062:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   5063:                 and mw[mi+1][iind]. dh depends on stepm. */
                   5064:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   5065:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   5066:              if(m >=firstpass && m <=lastpass){
                   5067:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   5068:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   5069:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   5070:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   5071:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   5072:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   5073:                if (m<lastpass) {
                   5074:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   5075:                  /*   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]); */
                   5076:                  if(s[m][iind]==-1)
                   5077:                    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.));
                   5078:                  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  5079:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
                   5080:                    if(!isnan(covar[ncovcol+z1][iind])){
1.332   ! brouard  5081:                      idq[z1]=idq[z1]+weight[iind];
        !          5082:                      meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
        !          5083:                      /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
        !          5084:                      stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
1.311     brouard  5085:                    }
1.284     brouard  5086:                  }
1.251     brouard  5087:                  /* if((int)agev[m][iind] == 55) */
                   5088:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   5089:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   5090:                  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  5091:                }
1.251     brouard  5092:              } /* end if between passes */  
                   5093:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   5094:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   5095:                k2cpt++;
                   5096:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  5097:              }
1.251     brouard  5098:            }else{
                   5099:              bool=1;
                   5100:            }/* end bool 2 */
                   5101:          } /* end m */
1.284     brouard  5102:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   5103:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   5104:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   5105:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   5106:          /* } */
1.251     brouard  5107:        } /* end bool */
                   5108:       } /* end iind = 1 to imx */
1.319     brouard  5109:       /* prop[s][age] is fed for any initial and valid live state as well as
1.251     brouard  5110:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   5111:       
                   5112:       
                   5113:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.330     brouard  5114:       if(cptcovn==0 && nj==1) /* no covariate and first pass */
1.265     brouard  5115:         pstamp(ficresp);
1.330     brouard  5116:       if  (cptcovn>0 && j!=0){
1.265     brouard  5117:         pstamp(ficresp);
1.251     brouard  5118:        printf( "\n#********** Variable "); 
                   5119:        fprintf(ficresp, "\n#********** Variable "); 
                   5120:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   5121:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   5122:        fprintf(ficlog, "\n#********** Variable "); 
1.330     brouard  5123:        for (z1=1; z1<=cptcovs; z1++){
1.251     brouard  5124:          if(!FixedV[Tvaraff[z1]]){
1.330     brouard  5125:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5126:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5127:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5128:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5129:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.250     brouard  5130:          }else{
1.330     brouard  5131:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5132:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5133:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5134:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5135:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.251     brouard  5136:          }
                   5137:        }
                   5138:        printf( "**********\n#");
                   5139:        fprintf(ficresp, "**********\n#");
                   5140:        fprintf(ficresphtm, "**********</h3>\n");
                   5141:        fprintf(ficresphtmfr, "**********</h3>\n");
                   5142:        fprintf(ficlog, "**********\n");
                   5143:       }
1.284     brouard  5144:       /*
                   5145:        Printing means of quantitative variables if any
                   5146:       */
                   5147:       for (z1=1; z1<= nqfveff; z1++) {
1.311     brouard  5148:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.312     brouard  5149:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
1.284     brouard  5150:        if(weightopt==1){
                   5151:          printf(" Weighted mean and standard deviation of");
                   5152:          fprintf(ficlog," Weighted mean and standard deviation of");
                   5153:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   5154:        }
1.311     brouard  5155:        /* mu = \frac{w x}{\sum w}
                   5156:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
                   5157:        */
                   5158:        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]));
                   5159:        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]));
                   5160:        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  5161:       }
                   5162:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   5163:       /*       for(m=1;m<=lastpass;m++){ */
                   5164:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   5165:       /*   } */
                   5166:       /* } */
1.283     brouard  5167: 
1.251     brouard  5168:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.330     brouard  5169:       if((cptcovn==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
1.265     brouard  5170:         fprintf(ficresp, " Age");
1.332   ! brouard  5171:       if(nj==2) for (z1=1; z1<=cptcovn; z1++) fprintf(ficresp, " V%d=%d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.251     brouard  5172:       for(i=1; i<=nlstate;i++) {
1.330     brouard  5173:        if((cptcovn==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  5174:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   5175:       }
1.330     brouard  5176:       if((cptcovn==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  5177:       fprintf(ficresphtm, "\n");
                   5178:       
                   5179:       /* Header of frequency table by age */
                   5180:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   5181:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  5182:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  5183:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5184:          if(s2!=0 && m!=0)
                   5185:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  5186:        }
1.226     brouard  5187:       }
1.251     brouard  5188:       fprintf(ficresphtmfr, "\n");
                   5189:     
                   5190:       /* For each age */
                   5191:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   5192:        fprintf(ficresphtm,"<tr>");
                   5193:        if(iage==iagemax+1){
                   5194:          fprintf(ficlog,"1");
                   5195:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   5196:        }else if(iage==iagemax+2){
                   5197:          fprintf(ficlog,"0");
                   5198:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   5199:        }else if(iage==iagemax+3){
                   5200:          fprintf(ficlog,"Total");
                   5201:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   5202:        }else{
1.240     brouard  5203:          if(first==1){
1.251     brouard  5204:            first=0;
                   5205:            printf("See log file for details...\n");
                   5206:          }
                   5207:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   5208:          fprintf(ficlog,"Age %d", iage);
                   5209:        }
1.265     brouard  5210:        for(s1=1; s1 <=nlstate ; s1++){
                   5211:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   5212:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  5213:        }
1.265     brouard  5214:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5215:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  5216:            pos += freq[s1][m][iage];
                   5217:          if(pp[s1]>=1.e-10){
1.251     brouard  5218:            if(first==1){
1.265     brouard  5219:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5220:            }
1.265     brouard  5221:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5222:          }else{
                   5223:            if(first==1)
1.265     brouard  5224:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   5225:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  5226:          }
                   5227:        }
                   5228:       
1.265     brouard  5229:        for(s1=1; s1 <=nlstate ; s1++){ 
                   5230:          /* posprop[s1]=0; */
                   5231:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   5232:            pp[s1] += freq[s1][m][iage];
                   5233:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   5234:       
                   5235:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   5236:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   5237:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5238:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5239:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5240:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5241:        }
                   5242:        
                   5243:        /* Writing ficresp */
1.330     brouard  5244:        if(cptcovn==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5245:           if( iage <= iagemax){
                   5246:            fprintf(ficresp," %d",iage);
                   5247:           }
                   5248:         }else if( nj==2){
                   5249:           if( iage <= iagemax){
                   5250:            fprintf(ficresp," %d",iage);
1.332   ! brouard  5251:             for (z1=1; z1<=cptcovn; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.265     brouard  5252:           }
1.240     brouard  5253:        }
1.265     brouard  5254:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  5255:          if(pos>=1.e-5){
1.251     brouard  5256:            if(first==1)
1.265     brouard  5257:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   5258:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  5259:          }else{
                   5260:            if(first==1)
1.265     brouard  5261:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   5262:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  5263:          }
                   5264:          if( iage <= iagemax){
                   5265:            if(pos>=1.e-5){
1.330     brouard  5266:              if(cptcovn==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5267:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5268:               }else if( nj==2){
                   5269:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5270:               }
                   5271:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5272:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   5273:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   5274:            } else{
1.330     brouard  5275:              if((cptcovn==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
1.265     brouard  5276:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  5277:            }
1.240     brouard  5278:          }
1.265     brouard  5279:          pospropt[s1] +=posprop[s1];
                   5280:        } /* end loop s1 */
1.251     brouard  5281:        /* pospropt=0.; */
1.265     brouard  5282:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  5283:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5284:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  5285:              if(first==1){
1.265     brouard  5286:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5287:              }
1.265     brouard  5288:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   5289:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5290:            }
1.265     brouard  5291:            if(s1!=0 && m!=0)
                   5292:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  5293:          }
1.265     brouard  5294:        } /* end loop s1 */
1.251     brouard  5295:        posproptt=0.; 
1.265     brouard  5296:        for(s1=1; s1 <=nlstate; s1++){
                   5297:          posproptt += pospropt[s1];
1.251     brouard  5298:        }
                   5299:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  5300:        fprintf(ficresphtm,"</tr>\n");
1.330     brouard  5301:        if((cptcovn==0 && nj==1)|| nj==2 ) {
1.265     brouard  5302:          if(iage <= iagemax)
                   5303:            fprintf(ficresp,"\n");
1.240     brouard  5304:        }
1.251     brouard  5305:        if(first==1)
                   5306:          printf("Others in log...\n");
                   5307:        fprintf(ficlog,"\n");
                   5308:       } /* end loop age iage */
1.265     brouard  5309:       
1.251     brouard  5310:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  5311:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5312:        if(posproptt < 1.e-5){
1.265     brouard  5313:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  5314:        }else{
1.265     brouard  5315:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  5316:        }
1.226     brouard  5317:       }
1.251     brouard  5318:       fprintf(ficresphtm,"</tr>\n");
                   5319:       fprintf(ficresphtm,"</table>\n");
                   5320:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  5321:       if(posproptt < 1.e-5){
1.251     brouard  5322:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   5323:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  5324:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   5325:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  5326:        invalidvarcomb[j1]=1;
1.226     brouard  5327:       }else{
1.251     brouard  5328:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
                   5329:        invalidvarcomb[j1]=0;
1.226     brouard  5330:       }
1.251     brouard  5331:       fprintf(ficresphtmfr,"</table>\n");
                   5332:       fprintf(ficlog,"\n");
                   5333:       if(j!=0){
                   5334:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  5335:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5336:          for(k=1; k <=(nlstate+ndeath); k++){
                   5337:            if (k != i) {
1.265     brouard  5338:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  5339:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  5340:                  if(j1==1){ /* All dummy covariates to zero */
                   5341:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   5342:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  5343:                    printf("%d%d ",i,k);
                   5344:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5345:                    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]));
                   5346:                    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]));
                   5347:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  5348:                  }
1.253     brouard  5349:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   5350:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   5351:                    x[iage]= (double)iage;
                   5352:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  5353:                    /* 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  5354:                  }
1.268     brouard  5355:                  /* Some are not finite, but linreg will ignore these ages */
                   5356:                  no=0;
1.253     brouard  5357:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  5358:                  pstart[s1]=b;
                   5359:                  pstart[s1-1]=a;
1.252     brouard  5360:                }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 */ 
                   5361:                  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]);
                   5362:                  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  5363:                  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  5364:                  printf("%d%d ",i,k);
                   5365:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5366:                  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  5367:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   5368:                  ;
                   5369:                }
                   5370:                /* printf("%12.7f )", param[i][jj][k]); */
                   5371:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5372:                s1++; 
1.251     brouard  5373:              } /* end jj */
                   5374:            } /* end k!= i */
                   5375:          } /* end k */
1.265     brouard  5376:        } /* end i, s1 */
1.251     brouard  5377:       } /* end j !=0 */
                   5378:     } /* end selected combination of covariate j1 */
                   5379:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   5380:       printf("#Freqsummary: Starting values for the constants:\n");
                   5381:       fprintf(ficlog,"\n");
1.265     brouard  5382:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5383:        for(k=1; k <=(nlstate+ndeath); k++){
                   5384:          if (k != i) {
                   5385:            printf("%d%d ",i,k);
                   5386:            fprintf(ficlog,"%d%d ",i,k);
                   5387:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  5388:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  5389:              if(jj==1){ /* Age has to be done */
1.265     brouard  5390:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   5391:                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]));
                   5392:                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  5393:              }
                   5394:              /* printf("%12.7f )", param[i][jj][k]); */
                   5395:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5396:              s1++; 
1.250     brouard  5397:            }
1.251     brouard  5398:            printf("\n");
                   5399:            fprintf(ficlog,"\n");
1.250     brouard  5400:          }
                   5401:        }
1.284     brouard  5402:       } /* end of state i */
1.251     brouard  5403:       printf("#Freqsummary\n");
                   5404:       fprintf(ficlog,"\n");
1.265     brouard  5405:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   5406:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   5407:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   5408:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5409:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5410:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   5411:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   5412:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  5413:          /* } */
                   5414:        }
1.265     brouard  5415:       } /* end loop s1 */
1.251     brouard  5416:       
                   5417:       printf("\n");
                   5418:       fprintf(ficlog,"\n");
                   5419:     } /* end j=0 */
1.249     brouard  5420:   } /* end j */
1.252     brouard  5421: 
1.253     brouard  5422:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  5423:     for(i=1, jk=1; i <=nlstate; i++){
                   5424:       for(j=1; j <=nlstate+ndeath; j++){
                   5425:        if(j!=i){
                   5426:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5427:          printf("%1d%1d",i,j);
                   5428:          fprintf(ficparo,"%1d%1d",i,j);
                   5429:          for(k=1; k<=ncovmodel;k++){
                   5430:            /*    printf(" %lf",param[i][j][k]); */
                   5431:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   5432:            p[jk]=pstart[jk];
                   5433:            printf(" %f ",pstart[jk]);
                   5434:            fprintf(ficparo," %f ",pstart[jk]);
                   5435:            jk++;
                   5436:          }
                   5437:          printf("\n");
                   5438:          fprintf(ficparo,"\n");
                   5439:        }
                   5440:       }
                   5441:     }
                   5442:   } /* end mle=-2 */
1.226     brouard  5443:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  5444:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  5445:   
1.226     brouard  5446:   fclose(ficresp);
                   5447:   fclose(ficresphtm);
                   5448:   fclose(ficresphtmfr);
1.283     brouard  5449:   free_vector(idq,1,nqfveff);
1.226     brouard  5450:   free_vector(meanq,1,nqfveff);
1.284     brouard  5451:   free_vector(stdq,1,nqfveff);
1.226     brouard  5452:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  5453:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   5454:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  5455:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5456:   free_vector(pospropt,1,nlstate);
                   5457:   free_vector(posprop,1,nlstate);
1.251     brouard  5458:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5459:   free_vector(pp,1,nlstate);
                   5460:   /* End of freqsummary */
                   5461: }
1.126     brouard  5462: 
1.268     brouard  5463: /* Simple linear regression */
                   5464: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   5465: 
                   5466:   /* y=a+bx regression */
                   5467:   double   sumx = 0.0;                        /* sum of x                      */
                   5468:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   5469:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   5470:   double   sumy = 0.0;                        /* sum of y                      */
                   5471:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   5472:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   5473:   double yhat;
                   5474:   
                   5475:   double denom=0;
                   5476:   int i;
                   5477:   int ne=*no;
                   5478:   
                   5479:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5480:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5481:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5482:       continue;
                   5483:     }
                   5484:     ne=ne+1;
                   5485:     sumx  += x[i];       
                   5486:     sumx2 += x[i]*x[i];  
                   5487:     sumxy += x[i] * y[i];
                   5488:     sumy  += y[i];      
                   5489:     sumy2 += y[i]*y[i]; 
                   5490:     denom = (ne * sumx2 - sumx*sumx);
                   5491:     /* 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); */
                   5492:   } 
                   5493:   
                   5494:   denom = (ne * sumx2 - sumx*sumx);
                   5495:   if (denom == 0) {
                   5496:     // vertical, slope m is infinity
                   5497:     *b = INFINITY;
                   5498:     *a = 0;
                   5499:     if (r) *r = 0;
                   5500:     return 1;
                   5501:   }
                   5502:   
                   5503:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   5504:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   5505:   if (r!=NULL) {
                   5506:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   5507:       sqrt((sumx2 - sumx*sumx/ne) *
                   5508:           (sumy2 - sumy*sumy/ne));
                   5509:   }
                   5510:   *no=ne;
                   5511:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5512:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5513:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5514:       continue;
                   5515:     }
                   5516:     ne=ne+1;
                   5517:     yhat = y[i] - *a -*b* x[i];
                   5518:     sume2  += yhat * yhat ;       
                   5519:     
                   5520:     denom = (ne * sumx2 - sumx*sumx);
                   5521:     /* 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); */
                   5522:   } 
                   5523:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   5524:   *sa= *sb * sqrt(sumx2/ne);
                   5525:   
                   5526:   return 0; 
                   5527: }
                   5528: 
1.126     brouard  5529: /************ Prevalence ********************/
1.227     brouard  5530: 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)
                   5531: {  
                   5532:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   5533:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   5534:      We still use firstpass and lastpass as another selection.
                   5535:   */
1.126     brouard  5536:  
1.227     brouard  5537:   int i, m, jk, j1, bool, z1,j, iv;
                   5538:   int mi; /* Effective wave */
                   5539:   int iage;
                   5540:   double agebegin, ageend;
                   5541: 
                   5542:   double **prop;
                   5543:   double posprop; 
                   5544:   double  y2; /* in fractional years */
                   5545:   int iagemin, iagemax;
                   5546:   int first; /** to stop verbosity which is redirected to log file */
                   5547: 
                   5548:   iagemin= (int) agemin;
                   5549:   iagemax= (int) agemax;
                   5550:   /*pp=vector(1,nlstate);*/
1.251     brouard  5551:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  5552:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   5553:   j1=0;
1.222     brouard  5554:   
1.227     brouard  5555:   /*j=cptcoveff;*/
                   5556:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  5557:   
1.288     brouard  5558:   first=0;
1.227     brouard  5559:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of covariate */
                   5560:     for (i=1; i<=nlstate; i++)  
1.251     brouard  5561:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  5562:        prop[i][iage]=0.0;
                   5563:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   5564:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   5565:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   5566:     
                   5567:     for (i=1; i<=imx; i++) { /* Each individual */
                   5568:       bool=1;
                   5569:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   5570:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   5571:        m=mw[mi][i];
                   5572:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   5573:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   5574:        for (z1=1; z1<=cptcoveff; z1++){
                   5575:          if( Fixed[Tmodelind[z1]]==1){
                   5576:            iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
1.332   ! brouard  5577:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality */
1.227     brouard  5578:              bool=0;
                   5579:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
1.332   ! brouard  5580:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) {
1.227     brouard  5581:              bool=0;
                   5582:            }
                   5583:        }
                   5584:        if(bool==1){ /* Otherwise we skip that wave/person */
                   5585:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   5586:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   5587:          if(m >=firstpass && m <=lastpass){
                   5588:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   5589:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   5590:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   5591:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  5592:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  5593:                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); 
                   5594:                exit(1);
                   5595:              }
                   5596:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   5597:                /*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]]);*/
                   5598:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   5599:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   5600:              } /* end valid statuses */ 
                   5601:            } /* end selection of dates */
                   5602:          } /* end selection of waves */
                   5603:        } /* end bool */
                   5604:       } /* end wave */
                   5605:     } /* end individual */
                   5606:     for(i=iagemin; i <= iagemax+3; i++){  
                   5607:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   5608:        posprop += prop[jk][i]; 
                   5609:       } 
                   5610:       
                   5611:       for(jk=1; jk <=nlstate ; jk++){      
                   5612:        if( i <=  iagemax){ 
                   5613:          if(posprop>=1.e-5){ 
                   5614:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   5615:          } else{
1.288     brouard  5616:            if(!first){
                   5617:              first=1;
1.266     brouard  5618:              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]);
                   5619:            }else{
1.288     brouard  5620:              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  5621:            }
                   5622:          }
                   5623:        } 
                   5624:       }/* end jk */ 
                   5625:     }/* end i */ 
1.222     brouard  5626:      /*} *//* end i1 */
1.227     brouard  5627:   } /* end j1 */
1.222     brouard  5628:   
1.227     brouard  5629:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   5630:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  5631:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  5632: }  /* End of prevalence */
1.126     brouard  5633: 
                   5634: /************* Waves Concatenation ***************/
                   5635: 
                   5636: 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)
                   5637: {
1.298     brouard  5638:   /* 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  5639:      Death is a valid wave (if date is known).
                   5640:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   5641:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  5642:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  5643:   */
1.126     brouard  5644: 
1.224     brouard  5645:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  5646:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   5647:      double sum=0., jmean=0.;*/
1.224     brouard  5648:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  5649:   int j, k=0,jk, ju, jl;
                   5650:   double sum=0.;
                   5651:   first=0;
1.214     brouard  5652:   firstwo=0;
1.217     brouard  5653:   firsthree=0;
1.218     brouard  5654:   firstfour=0;
1.164     brouard  5655:   jmin=100000;
1.126     brouard  5656:   jmax=-1;
                   5657:   jmean=0.;
1.224     brouard  5658: 
                   5659: /* Treating live states */
1.214     brouard  5660:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  5661:     mi=0;  /* First valid wave */
1.227     brouard  5662:     mli=0; /* Last valid wave */
1.309     brouard  5663:     m=firstpass;  /* Loop on waves */
                   5664:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
1.227     brouard  5665:       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 */
                   5666:        mli=m-1;/* mw[++mi][i]=m-1; */
                   5667:       }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  5668:        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  5669:        mli=m;
1.224     brouard  5670:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   5671:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  5672:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  5673:       }
1.309     brouard  5674:       else{ /* m = lastpass, eventual special issue with warning */
1.224     brouard  5675: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  5676:        break;
1.224     brouard  5677: #else
1.317     brouard  5678:        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  5679:          if(firsthree == 0){
1.302     brouard  5680:            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  5681:            firsthree=1;
1.317     brouard  5682:          }else if(firsthree >=1 && firsthree < 10){
                   5683:            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);
                   5684:            firsthree++;
                   5685:          }else if(firsthree == 10){
                   5686:            printf("Information, too many Information flags: no more reported to log either\n");
                   5687:            fprintf(ficlog,"Information, too many Information flags: no more reported to log either\n");
                   5688:            firsthree++;
                   5689:          }else{
                   5690:            firsthree++;
1.227     brouard  5691:          }
1.309     brouard  5692:          mw[++mi][i]=m; /* Valid transition with unknown status */
1.227     brouard  5693:          mli=m;
                   5694:        }
                   5695:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   5696:          nbwarn++;
1.309     brouard  5697:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
1.227     brouard  5698:            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);
                   5699:            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);
                   5700:          }
                   5701:          break;
                   5702:        }
                   5703:        break;
1.224     brouard  5704: #endif
1.227     brouard  5705:       }/* End m >= lastpass */
1.126     brouard  5706:     }/* end while */
1.224     brouard  5707: 
1.227     brouard  5708:     /* 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  5709:     /* After last pass */
1.224     brouard  5710: /* Treating death states */
1.214     brouard  5711:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  5712:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   5713:       /* } */
1.126     brouard  5714:       mi++;    /* Death is another wave */
                   5715:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  5716:       /* Only death is a correct wave */
1.126     brouard  5717:       mw[mi][i]=m;
1.257     brouard  5718:     } /* else not in a death state */
1.224     brouard  5719: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  5720:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  5721:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.309     brouard  5722:        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  5723:          nbwarn++;
                   5724:          if(firstfiv==0){
1.309     brouard  5725:            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  5726:            firstfiv=1;
                   5727:          }else{
1.309     brouard  5728:            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  5729:          }
1.309     brouard  5730:            s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
                   5731:        }else{ /* Month of Death occured afer last wave month, potential bias */
1.227     brouard  5732:          nberr++;
                   5733:          if(firstwo==0){
1.309     brouard  5734:            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  5735:            firstwo=1;
                   5736:          }
1.309     brouard  5737:          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  5738:        }
1.257     brouard  5739:       }else{ /* if date of interview is unknown */
1.227     brouard  5740:        /* death is known but not confirmed by death status at any wave */
                   5741:        if(firstfour==0){
1.309     brouard  5742:          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  5743:          firstfour=1;
                   5744:        }
1.309     brouard  5745:        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  5746:       }
1.224     brouard  5747:     } /* end if date of death is known */
                   5748: #endif
1.309     brouard  5749:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
                   5750:     /* wav[i]=mw[mi][i];   */
1.126     brouard  5751:     if(mi==0){
                   5752:       nbwarn++;
                   5753:       if(first==0){
1.227     brouard  5754:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   5755:        first=1;
1.126     brouard  5756:       }
                   5757:       if(first==1){
1.227     brouard  5758:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  5759:       }
                   5760:     } /* end mi==0 */
                   5761:   } /* End individuals */
1.214     brouard  5762:   /* wav and mw are no more changed */
1.223     brouard  5763:        
1.317     brouard  5764:   printf("Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   5765:   fprintf(ficlog,"Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   5766: 
                   5767: 
1.126     brouard  5768:   for(i=1; i<=imx; i++){
                   5769:     for(mi=1; mi<wav[i];mi++){
                   5770:       if (stepm <=0)
1.227     brouard  5771:        dh[mi][i]=1;
1.126     brouard  5772:       else{
1.260     brouard  5773:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  5774:          if (agedc[i] < 2*AGESUP) {
                   5775:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   5776:            if(j==0) j=1;  /* Survives at least one month after exam */
                   5777:            else if(j<0){
                   5778:              nberr++;
                   5779:              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]);
                   5780:              j=1; /* Temporary Dangerous patch */
                   5781:              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);
                   5782:              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]);
                   5783:              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);
                   5784:            }
                   5785:            k=k+1;
                   5786:            if (j >= jmax){
                   5787:              jmax=j;
                   5788:              ijmax=i;
                   5789:            }
                   5790:            if (j <= jmin){
                   5791:              jmin=j;
                   5792:              ijmin=i;
                   5793:            }
                   5794:            sum=sum+j;
                   5795:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   5796:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   5797:          }
                   5798:        }
                   5799:        else{
                   5800:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  5801: /*       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  5802:                                        
1.227     brouard  5803:          k=k+1;
                   5804:          if (j >= jmax) {
                   5805:            jmax=j;
                   5806:            ijmax=i;
                   5807:          }
                   5808:          else if (j <= jmin){
                   5809:            jmin=j;
                   5810:            ijmin=i;
                   5811:          }
                   5812:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   5813:          /*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]);*/
                   5814:          if(j<0){
                   5815:            nberr++;
                   5816:            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]);
                   5817:            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]);
                   5818:          }
                   5819:          sum=sum+j;
                   5820:        }
                   5821:        jk= j/stepm;
                   5822:        jl= j -jk*stepm;
                   5823:        ju= j -(jk+1)*stepm;
                   5824:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   5825:          if(jl==0){
                   5826:            dh[mi][i]=jk;
                   5827:            bh[mi][i]=0;
                   5828:          }else{ /* We want a negative bias in order to only have interpolation ie
                   5829:                  * to avoid the price of an extra matrix product in likelihood */
                   5830:            dh[mi][i]=jk+1;
                   5831:            bh[mi][i]=ju;
                   5832:          }
                   5833:        }else{
                   5834:          if(jl <= -ju){
                   5835:            dh[mi][i]=jk;
                   5836:            bh[mi][i]=jl;       /* bias is positive if real duration
                   5837:                                 * is higher than the multiple of stepm and negative otherwise.
                   5838:                                 */
                   5839:          }
                   5840:          else{
                   5841:            dh[mi][i]=jk+1;
                   5842:            bh[mi][i]=ju;
                   5843:          }
                   5844:          if(dh[mi][i]==0){
                   5845:            dh[mi][i]=1; /* At least one step */
                   5846:            bh[mi][i]=ju; /* At least one step */
                   5847:            /*  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);*/
                   5848:          }
                   5849:        } /* end if mle */
1.126     brouard  5850:       }
                   5851:     } /* end wave */
                   5852:   }
                   5853:   jmean=sum/k;
                   5854:   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  5855:   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  5856: }
1.126     brouard  5857: 
                   5858: /*********** Tricode ****************************/
1.220     brouard  5859:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  5860:  {
                   5861:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   5862:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   5863:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   5864:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   5865:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   5866:     */
1.130     brouard  5867: 
1.242     brouard  5868:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   5869:    int modmaxcovj=0; /* Modality max of covariates j */
                   5870:    int cptcode=0; /* Modality max of covariates j */
                   5871:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  5872: 
                   5873: 
1.242     brouard  5874:    /* cptcoveff=0;  */
                   5875:    /* *cptcov=0; */
1.126     brouard  5876:  
1.242     brouard  5877:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  5878:    for (k=1; k <= maxncov; k++)
                   5879:      for(j=1; j<=2; j++)
                   5880:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  5881: 
1.242     brouard  5882:    /* Loop on covariates without age and products and no quantitative variable */
                   5883:    for (k=1; k<=cptcovt; k++) { /* From model V1 + V2*age + V3 + V3*V4 keeps V1 + V3 = 2 only */
                   5884:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
                   5885:      if(Dummy[k]==0 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
                   5886:        switch(Fixed[k]) {
                   5887:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.311     brouard  5888:         modmaxcovj=0;
                   5889:         modmincovj=0;
1.242     brouard  5890:         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*/
                   5891:           ij=(int)(covar[Tvar[k]][i]);
                   5892:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   5893:            * If product of Vn*Vm, still boolean *:
                   5894:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   5895:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   5896:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   5897:              modality of the nth covariate of individual i. */
                   5898:           if (ij > modmaxcovj)
                   5899:             modmaxcovj=ij; 
                   5900:           else if (ij < modmincovj) 
                   5901:             modmincovj=ij; 
1.287     brouard  5902:           if (ij <0 || ij >1 ){
1.311     brouard  5903:             printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   5904:             fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   5905:             fflush(ficlog);
                   5906:             exit(1);
1.287     brouard  5907:           }
                   5908:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  5909:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   5910:             exit(1);
                   5911:           }else
                   5912:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   5913:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   5914:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   5915:           /* getting the maximum value of the modality of the covariate
                   5916:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   5917:              female ies 1, then modmaxcovj=1.
                   5918:           */
                   5919:         } /* end for loop on individuals i */
                   5920:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   5921:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   5922:         cptcode=modmaxcovj;
                   5923:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   5924:         /*for (i=0; i<=cptcode; i++) {*/
                   5925:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   5926:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   5927:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   5928:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   5929:             if( j != -1){
                   5930:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   5931:                                  covariate for which somebody answered excluding 
                   5932:                                  undefined. Usually 2: 0 and 1. */
                   5933:             }
                   5934:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   5935:                                     covariate for which somebody answered including 
                   5936:                                     undefined. Usually 3: -1, 0 and 1. */
                   5937:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   5938:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   5939:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  5940:                        
1.242     brouard  5941:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   5942:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   5943:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   5944:         /* modmincovj=3; modmaxcovj = 7; */
                   5945:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   5946:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   5947:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   5948:         /* nbcode[Tvar[j]][ij]=k; */
                   5949:         /* nbcode[Tvar[j]][1]=0; */
                   5950:         /* nbcode[Tvar[j]][2]=1; */
                   5951:         /* nbcode[Tvar[j]][3]=2; */
                   5952:         /* To be continued (not working yet). */
                   5953:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  5954: 
                   5955:         /* 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*/
                   5956:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   5957:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   5958:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   5959:         /*, could be restored in the future */
                   5960:         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  5961:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   5962:             break;
                   5963:           }
                   5964:           ij++;
1.287     brouard  5965:           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  5966:           cptcode = ij; /* New max modality for covar j */
                   5967:         } /* end of loop on modality i=-1 to 1 or more */
                   5968:         break;
                   5969:        case 1: /* Testing on varying covariate, could be simple and
                   5970:                * should look at waves or product of fixed *
                   5971:                * varying. No time to test -1, assuming 0 and 1 only */
                   5972:         ij=0;
                   5973:         for(i=0; i<=1;i++){
                   5974:           nbcode[Tvar[k]][++ij]=i;
                   5975:         }
                   5976:         break;
                   5977:        default:
                   5978:         break;
                   5979:        } /* end switch */
                   5980:      } /* end dummy test */
1.311     brouard  5981:      if(Dummy[k]==1 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
                   5982:        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*/
                   5983:         if(isnan(covar[Tvar[k]][i])){
                   5984:           printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   5985:           fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   5986:           fflush(ficlog);
                   5987:           exit(1);
                   5988:          }
                   5989:        }
                   5990:      }
1.287     brouard  5991:    } /* 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  5992:   
                   5993:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   5994:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   5995:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   5996:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   5997:      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 */ 
                   5998:      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 */
                   5999:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   6000:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   6001:   
                   6002:    ij=0;
                   6003:    /* for (i=0; i<=  maxncov-1; i++) { /\* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) *\/ */
                   6004:    for (k=1; k<=  cptcovt; k++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   6005:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   6006:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
                   6007:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy and non empty in the model */
                   6008:        /* If product not in single variable we don't print results */
                   6009:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   6010:        ++ij;/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, */
                   6011:        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*/
                   6012:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   6013:        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 */
                   6014:        if(Fixed[k]!=0)
                   6015:         anyvaryingduminmodel=1;
                   6016:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   6017:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6018:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   6019:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   6020:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   6021:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6022:      } 
                   6023:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   6024:    /* ij--; */
                   6025:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
1.330     brouard  6026:    *cptcov=ij; /* cptcov= Number of total real effective covariates: effective (used as cptcoveff in other functions)
1.242     brouard  6027:                * because they can be excluded from the model and real
                   6028:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   6029:    for(j=ij+1; j<= cptcovt; j++){
                   6030:      Tvaraff[j]=0;
                   6031:      Tmodelind[j]=0;
                   6032:    }
                   6033:    for(j=ntveff+1; j<= cptcovt; j++){
                   6034:      TmodelInvind[j]=0;
                   6035:    }
                   6036:    /* To be sorted */
                   6037:    ;
                   6038:  }
1.126     brouard  6039: 
1.145     brouard  6040: 
1.126     brouard  6041: /*********** Health Expectancies ****************/
                   6042: 
1.235     brouard  6043:  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  6044: 
                   6045: {
                   6046:   /* Health expectancies, no variances */
1.329     brouard  6047:   /* cij is the combination in the list of combination of dummy covariates */
                   6048:   /* strstart is a string of time at start of computing */
1.164     brouard  6049:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  6050:   int nhstepma, nstepma; /* Decreasing with age */
                   6051:   double age, agelim, hf;
                   6052:   double ***p3mat;
                   6053:   double eip;
                   6054: 
1.238     brouard  6055:   /* pstamp(ficreseij); */
1.126     brouard  6056:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   6057:   fprintf(ficreseij,"# Age");
                   6058:   for(i=1; i<=nlstate;i++){
                   6059:     for(j=1; j<=nlstate;j++){
                   6060:       fprintf(ficreseij," e%1d%1d ",i,j);
                   6061:     }
                   6062:     fprintf(ficreseij," e%1d. ",i);
                   6063:   }
                   6064:   fprintf(ficreseij,"\n");
                   6065: 
                   6066:   
                   6067:   if(estepm < stepm){
                   6068:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6069:   }
                   6070:   else  hstepm=estepm;   
                   6071:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6072:    * This is mainly to measure the difference between two models: for example
                   6073:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6074:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6075:    * progression in between and thus overestimating or underestimating according
                   6076:    * to the curvature of the survival function. If, for the same date, we 
                   6077:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6078:    * to compare the new estimate of Life expectancy with the same linear 
                   6079:    * hypothesis. A more precise result, taking into account a more precise
                   6080:    * curvature will be obtained if estepm is as small as stepm. */
                   6081: 
                   6082:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6083:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6084:      nhstepm is the number of hstepm from age to agelim 
                   6085:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  6086:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  6087:      and note for a fixed period like estepm months */
                   6088:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6089:      survival function given by stepm (the optimization length). Unfortunately it
                   6090:      means that if the survival funtion is printed only each two years of age and if
                   6091:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6092:      results. So we changed our mind and took the option of the best precision.
                   6093:   */
                   6094:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6095: 
                   6096:   agelim=AGESUP;
                   6097:   /* If stepm=6 months */
                   6098:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   6099:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   6100:     
                   6101: /* nhstepm age range expressed in number of stepm */
                   6102:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6103:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6104:   /* if (stepm >= YEARM) hstepm=1;*/
                   6105:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6106:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6107: 
                   6108:   for (age=bage; age<=fage; age ++){ 
                   6109:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6110:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6111:     /* if (stepm >= YEARM) hstepm=1;*/
                   6112:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   6113: 
                   6114:     /* If stepm=6 months */
                   6115:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6116:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
1.330     brouard  6117:     /* 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  6118:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  6119:     
                   6120:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6121:     
                   6122:     printf("%d|",(int)age);fflush(stdout);
                   6123:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6124:     
                   6125:     /* Computing expectancies */
                   6126:     for(i=1; i<=nlstate;i++)
                   6127:       for(j=1; j<=nlstate;j++)
                   6128:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6129:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   6130:          
                   6131:          /* 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]);*/
                   6132: 
                   6133:        }
                   6134: 
                   6135:     fprintf(ficreseij,"%3.0f",age );
                   6136:     for(i=1; i<=nlstate;i++){
                   6137:       eip=0;
                   6138:       for(j=1; j<=nlstate;j++){
                   6139:        eip +=eij[i][j][(int)age];
                   6140:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   6141:       }
                   6142:       fprintf(ficreseij,"%9.4f", eip );
                   6143:     }
                   6144:     fprintf(ficreseij,"\n");
                   6145:     
                   6146:   }
                   6147:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6148:   printf("\n");
                   6149:   fprintf(ficlog,"\n");
                   6150:   
                   6151: }
                   6152: 
1.235     brouard  6153:  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  6154: 
                   6155: {
                   6156:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  6157:      to initial status i, ei. .
1.126     brouard  6158:   */
                   6159:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   6160:   int nhstepma, nstepma; /* Decreasing with age */
                   6161:   double age, agelim, hf;
                   6162:   double ***p3matp, ***p3matm, ***varhe;
                   6163:   double **dnewm,**doldm;
                   6164:   double *xp, *xm;
                   6165:   double **gp, **gm;
                   6166:   double ***gradg, ***trgradg;
                   6167:   int theta;
                   6168: 
                   6169:   double eip, vip;
                   6170: 
                   6171:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   6172:   xp=vector(1,npar);
                   6173:   xm=vector(1,npar);
                   6174:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   6175:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   6176:   
                   6177:   pstamp(ficresstdeij);
                   6178:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   6179:   fprintf(ficresstdeij,"# Age");
                   6180:   for(i=1; i<=nlstate;i++){
                   6181:     for(j=1; j<=nlstate;j++)
                   6182:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   6183:     fprintf(ficresstdeij," e%1d. ",i);
                   6184:   }
                   6185:   fprintf(ficresstdeij,"\n");
                   6186: 
                   6187:   pstamp(ficrescveij);
                   6188:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   6189:   fprintf(ficrescveij,"# Age");
                   6190:   for(i=1; i<=nlstate;i++)
                   6191:     for(j=1; j<=nlstate;j++){
                   6192:       cptj= (j-1)*nlstate+i;
                   6193:       for(i2=1; i2<=nlstate;i2++)
                   6194:        for(j2=1; j2<=nlstate;j2++){
                   6195:          cptj2= (j2-1)*nlstate+i2;
                   6196:          if(cptj2 <= cptj)
                   6197:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   6198:        }
                   6199:     }
                   6200:   fprintf(ficrescveij,"\n");
                   6201:   
                   6202:   if(estepm < stepm){
                   6203:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6204:   }
                   6205:   else  hstepm=estepm;   
                   6206:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6207:    * This is mainly to measure the difference between two models: for example
                   6208:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6209:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6210:    * progression in between and thus overestimating or underestimating according
                   6211:    * to the curvature of the survival function. If, for the same date, we 
                   6212:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6213:    * to compare the new estimate of Life expectancy with the same linear 
                   6214:    * hypothesis. A more precise result, taking into account a more precise
                   6215:    * curvature will be obtained if estepm is as small as stepm. */
                   6216: 
                   6217:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6218:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6219:      nhstepm is the number of hstepm from age to agelim 
                   6220:      nstepm is the number of stepm from age to agelin. 
                   6221:      Look at hpijx to understand the reason of that which relies in memory size
                   6222:      and note for a fixed period like estepm months */
                   6223:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6224:      survival function given by stepm (the optimization length). Unfortunately it
                   6225:      means that if the survival funtion is printed only each two years of age and if
                   6226:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6227:      results. So we changed our mind and took the option of the best precision.
                   6228:   */
                   6229:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6230: 
                   6231:   /* If stepm=6 months */
                   6232:   /* nhstepm age range expressed in number of stepm */
                   6233:   agelim=AGESUP;
                   6234:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   6235:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6236:   /* if (stepm >= YEARM) hstepm=1;*/
                   6237:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6238:   
                   6239:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6240:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6241:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   6242:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   6243:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   6244:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   6245: 
                   6246:   for (age=bage; age<=fage; age ++){ 
                   6247:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6248:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6249:     /* if (stepm >= YEARM) hstepm=1;*/
                   6250:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  6251:                
1.126     brouard  6252:     /* If stepm=6 months */
                   6253:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6254:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   6255:     
                   6256:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  6257:                
1.126     brouard  6258:     /* Computing  Variances of health expectancies */
                   6259:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   6260:        decrease memory allocation */
                   6261:     for(theta=1; theta <=npar; theta++){
                   6262:       for(i=1; i<=npar; i++){ 
1.222     brouard  6263:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6264:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  6265:       }
1.235     brouard  6266:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   6267:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  6268:                        
1.126     brouard  6269:       for(j=1; j<= nlstate; j++){
1.222     brouard  6270:        for(i=1; i<=nlstate; i++){
                   6271:          for(h=0; h<=nhstepm-1; h++){
                   6272:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   6273:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   6274:          }
                   6275:        }
1.126     brouard  6276:       }
1.218     brouard  6277:                        
1.126     brouard  6278:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  6279:        for(h=0; h<=nhstepm-1; h++){
                   6280:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   6281:        }
1.126     brouard  6282:     }/* End theta */
                   6283:     
                   6284:     
                   6285:     for(h=0; h<=nhstepm-1; h++)
                   6286:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  6287:        for(theta=1; theta <=npar; theta++)
                   6288:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  6289:     
1.218     brouard  6290:                
1.222     brouard  6291:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  6292:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  6293:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  6294:                
1.222     brouard  6295:     printf("%d|",(int)age);fflush(stdout);
                   6296:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6297:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  6298:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  6299:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   6300:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   6301:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   6302:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   6303:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  6304:       }
                   6305:     }
1.320     brouard  6306:     /* if((int)age ==50){ */
                   6307:     /*   printf(" age=%d cij=%d nres=%d varhe[%d][%d]=%f ",(int)age, cij, nres, 1,2,varhe[1][2]); */
                   6308:     /* } */
1.126     brouard  6309:     /* Computing expectancies */
1.235     brouard  6310:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  6311:     for(i=1; i<=nlstate;i++)
                   6312:       for(j=1; j<=nlstate;j++)
1.222     brouard  6313:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6314:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  6315:                                        
1.222     brouard  6316:          /* 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  6317:                                        
1.222     brouard  6318:        }
1.269     brouard  6319: 
                   6320:     /* Standard deviation of expectancies ij */                
1.126     brouard  6321:     fprintf(ficresstdeij,"%3.0f",age );
                   6322:     for(i=1; i<=nlstate;i++){
                   6323:       eip=0.;
                   6324:       vip=0.;
                   6325:       for(j=1; j<=nlstate;j++){
1.222     brouard  6326:        eip += eij[i][j][(int)age];
                   6327:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   6328:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   6329:        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  6330:       }
                   6331:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   6332:     }
                   6333:     fprintf(ficresstdeij,"\n");
1.218     brouard  6334:                
1.269     brouard  6335:     /* Variance of expectancies ij */          
1.126     brouard  6336:     fprintf(ficrescveij,"%3.0f",age );
                   6337:     for(i=1; i<=nlstate;i++)
                   6338:       for(j=1; j<=nlstate;j++){
1.222     brouard  6339:        cptj= (j-1)*nlstate+i;
                   6340:        for(i2=1; i2<=nlstate;i2++)
                   6341:          for(j2=1; j2<=nlstate;j2++){
                   6342:            cptj2= (j2-1)*nlstate+i2;
                   6343:            if(cptj2 <= cptj)
                   6344:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   6345:          }
1.126     brouard  6346:       }
                   6347:     fprintf(ficrescveij,"\n");
1.218     brouard  6348:                
1.126     brouard  6349:   }
                   6350:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   6351:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   6352:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   6353:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   6354:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6355:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6356:   printf("\n");
                   6357:   fprintf(ficlog,"\n");
1.218     brouard  6358:        
1.126     brouard  6359:   free_vector(xm,1,npar);
                   6360:   free_vector(xp,1,npar);
                   6361:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   6362:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   6363:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   6364: }
1.218     brouard  6365:  
1.126     brouard  6366: /************ Variance ******************/
1.235     brouard  6367:  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  6368:  {
1.279     brouard  6369:    /** Variance of health expectancies 
                   6370:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   6371:     * double **newm;
                   6372:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   6373:     */
1.218     brouard  6374:   
                   6375:    /* int movingaverage(); */
                   6376:    double **dnewm,**doldm;
                   6377:    double **dnewmp,**doldmp;
                   6378:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  6379:    int first=0;
1.218     brouard  6380:    int k;
                   6381:    double *xp;
1.279     brouard  6382:    double **gp, **gm;  /**< for var eij */
                   6383:    double ***gradg, ***trgradg; /**< for var eij */
                   6384:    double **gradgp, **trgradgp; /**< for var p point j */
                   6385:    double *gpp, *gmp; /**< for var p point j */
                   6386:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
1.218     brouard  6387:    double ***p3mat;
                   6388:    double age,agelim, hf;
                   6389:    /* double ***mobaverage; */
                   6390:    int theta;
                   6391:    char digit[4];
                   6392:    char digitp[25];
                   6393: 
                   6394:    char fileresprobmorprev[FILENAMELENGTH];
                   6395: 
                   6396:    if(popbased==1){
                   6397:      if(mobilav!=0)
                   6398:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   6399:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   6400:    }
                   6401:    else 
                   6402:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  6403: 
1.218     brouard  6404:    /* if (mobilav!=0) { */
                   6405:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6406:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   6407:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   6408:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   6409:    /*   } */
                   6410:    /* } */
                   6411: 
                   6412:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   6413:    sprintf(digit,"%-d",ij);
                   6414:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   6415:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   6416:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   6417:    strcat(fileresprobmorprev,fileresu);
                   6418:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   6419:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   6420:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   6421:    }
                   6422:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6423:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6424:    pstamp(ficresprobmorprev);
                   6425:    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  6426:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
                   6427:    for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332   ! brouard  6428:      fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
1.238     brouard  6429:    }
                   6430:    for(j=1;j<=cptcoveff;j++) 
1.332   ! brouard  6431:      fprintf(ficresprobmorprev,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,TnsdVar[Tvaraff[j]])]);
1.238     brouard  6432:    fprintf(ficresprobmorprev,"\n");
                   6433: 
1.218     brouard  6434:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   6435:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6436:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   6437:      for(i=1; i<=nlstate;i++)
                   6438:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   6439:    }  
                   6440:    fprintf(ficresprobmorprev,"\n");
                   6441:   
                   6442:    fprintf(ficgp,"\n# Routine varevsij");
                   6443:    fprintf(ficgp,"\nunset title \n");
                   6444:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   6445:    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");
                   6446:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  6447: 
1.218     brouard  6448:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6449:    pstamp(ficresvij);
                   6450:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   6451:    if(popbased==1)
                   6452:      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);
                   6453:    else
                   6454:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   6455:    fprintf(ficresvij,"# Age");
                   6456:    for(i=1; i<=nlstate;i++)
                   6457:      for(j=1; j<=nlstate;j++)
                   6458:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   6459:    fprintf(ficresvij,"\n");
                   6460: 
                   6461:    xp=vector(1,npar);
                   6462:    dnewm=matrix(1,nlstate,1,npar);
                   6463:    doldm=matrix(1,nlstate,1,nlstate);
                   6464:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   6465:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6466: 
                   6467:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   6468:    gpp=vector(nlstate+1,nlstate+ndeath);
                   6469:    gmp=vector(nlstate+1,nlstate+ndeath);
                   6470:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  6471:   
1.218     brouard  6472:    if(estepm < stepm){
                   6473:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   6474:    }
                   6475:    else  hstepm=estepm;   
                   6476:    /* For example we decided to compute the life expectancy with the smallest unit */
                   6477:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6478:       nhstepm is the number of hstepm from age to agelim 
                   6479:       nstepm is the number of stepm from age to agelim. 
                   6480:       Look at function hpijx to understand why because of memory size limitations, 
                   6481:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   6482:       survival function given by stepm (the optimization length). Unfortunately it
                   6483:       means that if the survival funtion is printed every two years of age and if
                   6484:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6485:       results. So we changed our mind and took the option of the best precision.
                   6486:    */
                   6487:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6488:    agelim = AGESUP;
                   6489:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6490:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6491:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6492:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6493:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   6494:      gp=matrix(0,nhstepm,1,nlstate);
                   6495:      gm=matrix(0,nhstepm,1,nlstate);
                   6496:                
                   6497:                
                   6498:      for(theta=1; theta <=npar; theta++){
                   6499:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   6500:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6501:        }
1.279     brouard  6502:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   6503:        * returns into prlim .
1.288     brouard  6504:        */
1.242     brouard  6505:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  6506: 
                   6507:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  6508:        if (popbased==1) {
                   6509:         if(mobilav ==0){
                   6510:           for(i=1; i<=nlstate;i++)
                   6511:             prlim[i][i]=probs[(int)age][i][ij];
                   6512:         }else{ /* mobilav */ 
                   6513:           for(i=1; i<=nlstate;i++)
                   6514:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6515:         }
                   6516:        }
1.295     brouard  6517:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  6518:        */                      
                   6519:        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  6520:        /**< 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  6521:        * at horizon h in state j including mortality.
                   6522:        */
1.218     brouard  6523:        for(j=1; j<= nlstate; j++){
                   6524:         for(h=0; h<=nhstepm; h++){
                   6525:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   6526:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6527:         }
                   6528:        }
1.279     brouard  6529:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  6530:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  6531:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  6532:        */
                   6533:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6534:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   6535:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  6536:        }
                   6537:        
                   6538:        /* Again with minus shift */
1.218     brouard  6539:                        
                   6540:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   6541:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6542: 
1.242     brouard  6543:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  6544:                        
                   6545:        if (popbased==1) {
                   6546:         if(mobilav ==0){
                   6547:           for(i=1; i<=nlstate;i++)
                   6548:             prlim[i][i]=probs[(int)age][i][ij];
                   6549:         }else{ /* mobilav */ 
                   6550:           for(i=1; i<=nlstate;i++)
                   6551:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6552:         }
                   6553:        }
                   6554:                        
1.235     brouard  6555:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  6556:                        
                   6557:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   6558:         for(h=0; h<=nhstepm; h++){
                   6559:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   6560:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6561:         }
                   6562:        }
                   6563:        /* This for computing probability of death (h=1 means
                   6564:          computed over hstepm matrices product = hstepm*stepm months) 
                   6565:          as a weighted average of prlim.
                   6566:        */
                   6567:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6568:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   6569:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   6570:        }    
1.279     brouard  6571:        /* end shifting computations */
                   6572: 
                   6573:        /**< Computing gradient matrix at horizon h 
                   6574:        */
1.218     brouard  6575:        for(j=1; j<= nlstate; j++) /* vareij */
                   6576:         for(h=0; h<=nhstepm; h++){
                   6577:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   6578:         }
1.279     brouard  6579:        /**< Gradient of overall mortality p.3 (or p.j) 
                   6580:        */
                   6581:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
1.218     brouard  6582:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   6583:        }
                   6584:                        
                   6585:      } /* End theta */
1.279     brouard  6586:      
                   6587:      /* We got the gradient matrix for each theta and state j */               
1.218     brouard  6588:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   6589:                
                   6590:      for(h=0; h<=nhstepm; h++) /* veij */
                   6591:        for(j=1; j<=nlstate;j++)
                   6592:         for(theta=1; theta <=npar; theta++)
                   6593:           trgradg[h][j][theta]=gradg[h][theta][j];
                   6594:                
                   6595:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   6596:        for(theta=1; theta <=npar; theta++)
                   6597:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  6598:      /**< as well as its transposed matrix 
                   6599:       */               
1.218     brouard  6600:                
                   6601:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6602:      for(i=1;i<=nlstate;i++)
                   6603:        for(j=1;j<=nlstate;j++)
                   6604:         vareij[i][j][(int)age] =0.;
1.279     brouard  6605: 
                   6606:      /* Computing trgradg by matcov by gradg at age and summing over h
                   6607:       * and k (nhstepm) formula 15 of article
                   6608:       * Lievre-Brouard-Heathcote
                   6609:       */
                   6610:      
1.218     brouard  6611:      for(h=0;h<=nhstepm;h++){
                   6612:        for(k=0;k<=nhstepm;k++){
                   6613:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   6614:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   6615:         for(i=1;i<=nlstate;i++)
                   6616:           for(j=1;j<=nlstate;j++)
                   6617:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   6618:        }
                   6619:      }
                   6620:                
1.279     brouard  6621:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
                   6622:       * p.j overall mortality formula 49 but computed directly because
                   6623:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   6624:       * wix is independent of theta.
                   6625:       */
1.218     brouard  6626:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   6627:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   6628:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   6629:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   6630:         varppt[j][i]=doldmp[j][i];
                   6631:      /* end ppptj */
                   6632:      /*  x centered again */
                   6633:                
1.242     brouard  6634:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  6635:                
                   6636:      if (popbased==1) {
                   6637:        if(mobilav ==0){
                   6638:         for(i=1; i<=nlstate;i++)
                   6639:           prlim[i][i]=probs[(int)age][i][ij];
                   6640:        }else{ /* mobilav */ 
                   6641:         for(i=1; i<=nlstate;i++)
                   6642:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   6643:        }
                   6644:      }
                   6645:                
                   6646:      /* This for computing probability of death (h=1 means
                   6647:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   6648:        as a weighted average of prlim.
                   6649:      */
1.235     brouard  6650:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  6651:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6652:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   6653:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   6654:      }    
                   6655:      /* end probability of death */
                   6656:                
                   6657:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   6658:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6659:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   6660:        for(i=1; i<=nlstate;i++){
                   6661:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   6662:        }
                   6663:      } 
                   6664:      fprintf(ficresprobmorprev,"\n");
                   6665:                
                   6666:      fprintf(ficresvij,"%.0f ",age );
                   6667:      for(i=1; i<=nlstate;i++)
                   6668:        for(j=1; j<=nlstate;j++){
                   6669:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   6670:        }
                   6671:      fprintf(ficresvij,"\n");
                   6672:      free_matrix(gp,0,nhstepm,1,nlstate);
                   6673:      free_matrix(gm,0,nhstepm,1,nlstate);
                   6674:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   6675:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   6676:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6677:    } /* End age */
                   6678:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   6679:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   6680:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   6681:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   6682:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   6683:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   6684:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   6685:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   6686:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   6687:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   6688:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6689:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6690:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   6691:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   6692:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   6693:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   6694:    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);
                   6695:    /*  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  6696:     */
1.218     brouard  6697:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   6698:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  6699: 
1.218     brouard  6700:    free_vector(xp,1,npar);
                   6701:    free_matrix(doldm,1,nlstate,1,nlstate);
                   6702:    free_matrix(dnewm,1,nlstate,1,npar);
                   6703:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6704:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   6705:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6706:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6707:    fclose(ficresprobmorprev);
                   6708:    fflush(ficgp);
                   6709:    fflush(fichtm); 
                   6710:  }  /* end varevsij */
1.126     brouard  6711: 
                   6712: /************ Variance of prevlim ******************/
1.269     brouard  6713:  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  6714: {
1.205     brouard  6715:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  6716:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  6717: 
1.268     brouard  6718:   double **dnewmpar,**doldm;
1.126     brouard  6719:   int i, j, nhstepm, hstepm;
                   6720:   double *xp;
                   6721:   double *gp, *gm;
                   6722:   double **gradg, **trgradg;
1.208     brouard  6723:   double **mgm, **mgp;
1.126     brouard  6724:   double age,agelim;
                   6725:   int theta;
                   6726:   
                   6727:   pstamp(ficresvpl);
1.288     brouard  6728:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  6729:   fprintf(ficresvpl,"# Age ");
                   6730:   if(nresult >=1)
                   6731:     fprintf(ficresvpl," Result# ");
1.126     brouard  6732:   for(i=1; i<=nlstate;i++)
                   6733:       fprintf(ficresvpl," %1d-%1d",i,i);
                   6734:   fprintf(ficresvpl,"\n");
                   6735: 
                   6736:   xp=vector(1,npar);
1.268     brouard  6737:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  6738:   doldm=matrix(1,nlstate,1,nlstate);
                   6739:   
                   6740:   hstepm=1*YEARM; /* Every year of age */
                   6741:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   6742:   agelim = AGESUP;
                   6743:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6744:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6745:     if (stepm >= YEARM) hstepm=1;
                   6746:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6747:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  6748:     mgp=matrix(1,npar,1,nlstate);
                   6749:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  6750:     gp=vector(1,nlstate);
                   6751:     gm=vector(1,nlstate);
                   6752: 
                   6753:     for(theta=1; theta <=npar; theta++){
                   6754:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   6755:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6756:       }
1.288     brouard  6757:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6758:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6759:       /* else */
                   6760:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6761:       for(i=1;i<=nlstate;i++){
1.126     brouard  6762:        gp[i] = prlim[i][i];
1.208     brouard  6763:        mgp[theta][i] = prlim[i][i];
                   6764:       }
1.126     brouard  6765:       for(i=1; i<=npar; i++) /* Computes gradient */
                   6766:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6767:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6768:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6769:       /* else */
                   6770:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6771:       for(i=1;i<=nlstate;i++){
1.126     brouard  6772:        gm[i] = prlim[i][i];
1.208     brouard  6773:        mgm[theta][i] = prlim[i][i];
                   6774:       }
1.126     brouard  6775:       for(i=1;i<=nlstate;i++)
                   6776:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  6777:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  6778:     } /* End theta */
                   6779: 
                   6780:     trgradg =matrix(1,nlstate,1,npar);
                   6781: 
                   6782:     for(j=1; j<=nlstate;j++)
                   6783:       for(theta=1; theta <=npar; theta++)
                   6784:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  6785:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6786:     /*   printf("\nmgm mgp %d ",(int)age); */
                   6787:     /*   for(j=1; j<=nlstate;j++){ */
                   6788:     /*         printf(" %d ",j); */
                   6789:     /*         for(theta=1; theta <=npar; theta++) */
                   6790:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   6791:     /*         printf("\n "); */
                   6792:     /*   } */
                   6793:     /* } */
                   6794:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6795:     /*   printf("\n gradg %d ",(int)age); */
                   6796:     /*   for(j=1; j<=nlstate;j++){ */
                   6797:     /*         printf("%d ",j); */
                   6798:     /*         for(theta=1; theta <=npar; theta++) */
                   6799:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   6800:     /*         printf("\n "); */
                   6801:     /*   } */
                   6802:     /* } */
1.126     brouard  6803: 
                   6804:     for(i=1;i<=nlstate;i++)
                   6805:       varpl[i][(int)age] =0.;
1.209     brouard  6806:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  6807:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6808:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6809:     }else{
1.268     brouard  6810:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6811:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6812:     }
1.126     brouard  6813:     for(i=1;i<=nlstate;i++)
                   6814:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   6815: 
                   6816:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  6817:     if(nresult >=1)
                   6818:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  6819:     for(i=1; i<=nlstate;i++){
1.126     brouard  6820:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  6821:       /* for(j=1;j<=nlstate;j++) */
                   6822:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   6823:     }
1.126     brouard  6824:     fprintf(ficresvpl,"\n");
                   6825:     free_vector(gp,1,nlstate);
                   6826:     free_vector(gm,1,nlstate);
1.208     brouard  6827:     free_matrix(mgm,1,npar,1,nlstate);
                   6828:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  6829:     free_matrix(gradg,1,npar,1,nlstate);
                   6830:     free_matrix(trgradg,1,nlstate,1,npar);
                   6831:   } /* End age */
                   6832: 
                   6833:   free_vector(xp,1,npar);
                   6834:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  6835:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   6836: 
                   6837: }
                   6838: 
                   6839: 
                   6840: /************ Variance of backprevalence limit ******************/
1.269     brouard  6841:  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  6842: {
                   6843:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   6844:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   6845: 
                   6846:   double **dnewmpar,**doldm;
                   6847:   int i, j, nhstepm, hstepm;
                   6848:   double *xp;
                   6849:   double *gp, *gm;
                   6850:   double **gradg, **trgradg;
                   6851:   double **mgm, **mgp;
                   6852:   double age,agelim;
                   6853:   int theta;
                   6854:   
                   6855:   pstamp(ficresvbl);
                   6856:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   6857:   fprintf(ficresvbl,"# Age ");
                   6858:   if(nresult >=1)
                   6859:     fprintf(ficresvbl," Result# ");
                   6860:   for(i=1; i<=nlstate;i++)
                   6861:       fprintf(ficresvbl," %1d-%1d",i,i);
                   6862:   fprintf(ficresvbl,"\n");
                   6863: 
                   6864:   xp=vector(1,npar);
                   6865:   dnewmpar=matrix(1,nlstate,1,npar);
                   6866:   doldm=matrix(1,nlstate,1,nlstate);
                   6867:   
                   6868:   hstepm=1*YEARM; /* Every year of age */
                   6869:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   6870:   agelim = AGEINF;
                   6871:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   6872:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6873:     if (stepm >= YEARM) hstepm=1;
                   6874:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6875:     gradg=matrix(1,npar,1,nlstate);
                   6876:     mgp=matrix(1,npar,1,nlstate);
                   6877:     mgm=matrix(1,npar,1,nlstate);
                   6878:     gp=vector(1,nlstate);
                   6879:     gm=vector(1,nlstate);
                   6880: 
                   6881:     for(theta=1; theta <=npar; theta++){
                   6882:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   6883:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6884:       }
                   6885:       if(mobilavproj > 0 )
                   6886:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6887:       else
                   6888:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6889:       for(i=1;i<=nlstate;i++){
                   6890:        gp[i] = bprlim[i][i];
                   6891:        mgp[theta][i] = bprlim[i][i];
                   6892:       }
                   6893:      for(i=1; i<=npar; i++) /* Computes gradient */
                   6894:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   6895:        if(mobilavproj > 0 )
                   6896:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6897:        else
                   6898:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6899:       for(i=1;i<=nlstate;i++){
                   6900:        gm[i] = bprlim[i][i];
                   6901:        mgm[theta][i] = bprlim[i][i];
                   6902:       }
                   6903:       for(i=1;i<=nlstate;i++)
                   6904:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   6905:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   6906:     } /* End theta */
                   6907: 
                   6908:     trgradg =matrix(1,nlstate,1,npar);
                   6909: 
                   6910:     for(j=1; j<=nlstate;j++)
                   6911:       for(theta=1; theta <=npar; theta++)
                   6912:        trgradg[j][theta]=gradg[theta][j];
                   6913:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6914:     /*   printf("\nmgm mgp %d ",(int)age); */
                   6915:     /*   for(j=1; j<=nlstate;j++){ */
                   6916:     /*         printf(" %d ",j); */
                   6917:     /*         for(theta=1; theta <=npar; theta++) */
                   6918:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   6919:     /*         printf("\n "); */
                   6920:     /*   } */
                   6921:     /* } */
                   6922:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6923:     /*   printf("\n gradg %d ",(int)age); */
                   6924:     /*   for(j=1; j<=nlstate;j++){ */
                   6925:     /*         printf("%d ",j); */
                   6926:     /*         for(theta=1; theta <=npar; theta++) */
                   6927:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   6928:     /*         printf("\n "); */
                   6929:     /*   } */
                   6930:     /* } */
                   6931: 
                   6932:     for(i=1;i<=nlstate;i++)
                   6933:       varbpl[i][(int)age] =0.;
                   6934:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   6935:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6936:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   6937:     }else{
                   6938:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6939:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   6940:     }
                   6941:     for(i=1;i<=nlstate;i++)
                   6942:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   6943: 
                   6944:     fprintf(ficresvbl,"%.0f ",age );
                   6945:     if(nresult >=1)
                   6946:       fprintf(ficresvbl,"%d ",nres );
                   6947:     for(i=1; i<=nlstate;i++)
                   6948:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   6949:     fprintf(ficresvbl,"\n");
                   6950:     free_vector(gp,1,nlstate);
                   6951:     free_vector(gm,1,nlstate);
                   6952:     free_matrix(mgm,1,npar,1,nlstate);
                   6953:     free_matrix(mgp,1,npar,1,nlstate);
                   6954:     free_matrix(gradg,1,npar,1,nlstate);
                   6955:     free_matrix(trgradg,1,nlstate,1,npar);
                   6956:   } /* End age */
                   6957: 
                   6958:   free_vector(xp,1,npar);
                   6959:   free_matrix(doldm,1,nlstate,1,npar);
                   6960:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  6961: 
                   6962: }
                   6963: 
                   6964: /************ Variance of one-step probabilities  ******************/
                   6965: 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  6966:  {
                   6967:    int i, j=0,  k1, l1, tj;
                   6968:    int k2, l2, j1,  z1;
                   6969:    int k=0, l;
                   6970:    int first=1, first1, first2;
1.326     brouard  6971:    int nres=0; /* New */
1.222     brouard  6972:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   6973:    double **dnewm,**doldm;
                   6974:    double *xp;
                   6975:    double *gp, *gm;
                   6976:    double **gradg, **trgradg;
                   6977:    double **mu;
                   6978:    double age, cov[NCOVMAX+1];
                   6979:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   6980:    int theta;
                   6981:    char fileresprob[FILENAMELENGTH];
                   6982:    char fileresprobcov[FILENAMELENGTH];
                   6983:    char fileresprobcor[FILENAMELENGTH];
                   6984:    double ***varpij;
                   6985: 
                   6986:    strcpy(fileresprob,"PROB_"); 
                   6987:    strcat(fileresprob,fileres);
                   6988:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   6989:      printf("Problem with resultfile: %s\n", fileresprob);
                   6990:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   6991:    }
                   6992:    strcpy(fileresprobcov,"PROBCOV_"); 
                   6993:    strcat(fileresprobcov,fileresu);
                   6994:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   6995:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   6996:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   6997:    }
                   6998:    strcpy(fileresprobcor,"PROBCOR_"); 
                   6999:    strcat(fileresprobcor,fileresu);
                   7000:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   7001:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   7002:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   7003:    }
                   7004:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7005:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7006:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7007:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7008:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7009:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7010:    pstamp(ficresprob);
                   7011:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   7012:    fprintf(ficresprob,"# Age");
                   7013:    pstamp(ficresprobcov);
                   7014:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   7015:    fprintf(ficresprobcov,"# Age");
                   7016:    pstamp(ficresprobcor);
                   7017:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   7018:    fprintf(ficresprobcor,"# Age");
1.126     brouard  7019: 
                   7020: 
1.222     brouard  7021:    for(i=1; i<=nlstate;i++)
                   7022:      for(j=1; j<=(nlstate+ndeath);j++){
                   7023:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   7024:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   7025:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   7026:      }  
                   7027:    /* fprintf(ficresprob,"\n");
                   7028:       fprintf(ficresprobcov,"\n");
                   7029:       fprintf(ficresprobcor,"\n");
                   7030:    */
                   7031:    xp=vector(1,npar);
                   7032:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7033:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7034:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   7035:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   7036:    first=1;
                   7037:    fprintf(ficgp,"\n# Routine varprob");
                   7038:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   7039:    fprintf(fichtm,"\n");
                   7040: 
1.288     brouard  7041:    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  7042:    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);
                   7043:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  7044: and drawn. It helps understanding how is the covariance between two incidences.\
                   7045:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  7046:    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  7047: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   7048: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   7049: standard deviations wide on each axis. <br>\
                   7050:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   7051:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   7052: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   7053: 
1.222     brouard  7054:    cov[1]=1;
                   7055:    /* tj=cptcoveff; */
1.225     brouard  7056:    tj = (int) pow(2,cptcoveff);
1.222     brouard  7057:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   7058:    j1=0;
1.332   ! brouard  7059: 
        !          7060:    for(nres=1;nres <=nresult; nres++){ /* For each resultline */
        !          7061:    for(j1=1; j1<=tj;j1++){ /* For any combination of dummy covariates, fixed and varying */
        !          7062:      printf("Varprob  TKresult[nres]=%d j1=%d, nres=%d, cptcovn=%d, cptcoveff=%d tj=%d \n",  TKresult[nres], j1, nres, cptcovn, cptcoveff, tj);
        !          7063:      if(tj != 1 && TKresult[nres]!= j1)
        !          7064:        continue;
        !          7065: 
        !          7066:    /* for(j1=1; j1<=tj;j1++){  /\* For each valid combination of covariates or only once*\/ */
        !          7067:      /* for(nres=1;nres <=1; nres++){ /\* For each resultline *\/ */
        !          7068:      /* /\* for(nres=1;nres <=nresult; nres++){ /\\* For each resultline *\\/ *\/ */
1.222     brouard  7069:      if  (cptcovn>0) {
                   7070:        fprintf(ficresprob, "\n#********** Variable "); 
1.332   ! brouard  7071:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.222     brouard  7072:        fprintf(ficresprob, "**********\n#\n");
                   7073:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.332   ! brouard  7074:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.222     brouard  7075:        fprintf(ficresprobcov, "**********\n#\n");
1.220     brouard  7076:                        
1.222     brouard  7077:        fprintf(ficgp, "\n#********** Variable "); 
1.332   ! brouard  7078:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.222     brouard  7079:        fprintf(ficgp, "**********\n#\n");
1.220     brouard  7080:                        
                   7081:                        
1.222     brouard  7082:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.319     brouard  7083:        /* for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]); */
1.332   ! brouard  7084:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtmcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.222     brouard  7085:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  7086:                        
1.222     brouard  7087:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.332   ! brouard  7088:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.222     brouard  7089:        fprintf(ficresprobcor, "**********\n#");    
                   7090:        if(invalidvarcomb[j1]){
                   7091:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   7092:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   7093:         continue;
                   7094:        }
                   7095:      }
                   7096:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   7097:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7098:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   7099:      gm=vector(1,(nlstate)*(nlstate+ndeath));
                   7100:      for (age=bage; age<=fage; age ++){ 
                   7101:        cov[2]=age;
                   7102:        if(nagesqr==1)
                   7103:         cov[3]= age*age;
1.326     brouard  7104:        /* for (k=1; k<=cptcovn;k++) { */
                   7105:        /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)]; */
                   7106:        for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   7107:         /* Here comes the value of the covariate 'j1' after renumbering k with single dummy covariates */
1.332   ! brouard  7108:         cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(j1,TnsdVar[TvarsD[k]])];
1.222     brouard  7109:         /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
                   7110:                                                                    * 1  1 1 1 1
                   7111:                                                                    * 2  2 1 1 1
                   7112:                                                                    * 3  1 2 1 1
                   7113:                                                                    */
                   7114:         /* nbcode[1][1]=0 nbcode[1][2]=1;*/
                   7115:        }
1.319     brouard  7116:        /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   7117:        /* ) p nbcode[Tvar[Tage[k]]][(1 & (ij-1) >> (k-1))+1] */
                   7118:        /*for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.326     brouard  7119:        for (k=1; k<=cptcovage;k++){  /* For product with age */
                   7120:         if(Dummy[Tage[k]]==2){ /* dummy with age */
1.332   ! brouard  7121:           cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(j1,TnsdVar[Tvar[Tage[k]]])]*cov[2];
1.326     brouard  7122:           /* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   7123:         } else if(Dummy[Tage[k]]==3){ /* quantitative with age */
1.327     brouard  7124:           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]);
1.332   ! brouard  7125:           /* cov[2+nagesqr+Tage[k]]=meanq[k]/idq[k]*cov[2];/\* Using the mean of quantitative variable Tvar[Tage[k]] /\* Tqresult[nres][k]; *\/ */
        !          7126:           /* exit(1); */
1.326     brouard  7127:           /* cov[++k1]=Tqresult[nres][k];  */
                   7128:         }
                   7129:         /* cov[2+Tage[k]+nagesqr]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   7130:        }
                   7131:        for (k=1; k<=cptcovprod;k++){/* For product without age */
1.329     brouard  7132:         if(Dummy[Tvard[k][1]]==0){
                   7133:           if(Dummy[Tvard[k][2]]==0){
1.332   ! brouard  7134:             cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,TnsdVar[Tvard[k][1]])] * nbcode[Tvard[k][2]][codtabm(j1,TnsdVar[Tvard[k][2]])];
1.326     brouard  7135:             /* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; */
                   7136:           }else{ /* Should we use the mean of the quantitative variables? */
1.332   ! brouard  7137:             cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,TnsdVar[Tvard[k][1]])] * Tqresult[nres][resultmodel[nres][k]];
1.326     brouard  7138:             /* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; */
                   7139:           }
                   7140:         }else{
1.329     brouard  7141:           if(Dummy[Tvard[k][2]]==0){
1.332   ! brouard  7142:             cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(j1,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][TnsdVar[Tvard[k][1]]];
1.326     brouard  7143:             /* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; */
                   7144:           }else{
1.332   ! brouard  7145:             cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][TnsdVar[Tvard[k][1]]]*  Tqinvresult[nres][TnsdVar[Tvard[k][2]]];
1.326     brouard  7146:             /* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   7147:           }
                   7148:         }
                   7149:         /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
                   7150:        }                       
                   7151: /* For each age and combination of dummy covariates we slightly move the parameters of delti in order to get the gradient*/                    
1.222     brouard  7152:        for(theta=1; theta <=npar; theta++){
                   7153:         for(i=1; i<=npar; i++)
                   7154:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  7155:                                
1.222     brouard  7156:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  7157:                                
1.222     brouard  7158:         k=0;
                   7159:         for(i=1; i<= (nlstate); i++){
                   7160:           for(j=1; j<=(nlstate+ndeath);j++){
                   7161:             k=k+1;
                   7162:             gp[k]=pmmij[i][j];
                   7163:           }
                   7164:         }
1.220     brouard  7165:                                
1.222     brouard  7166:         for(i=1; i<=npar; i++)
                   7167:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  7168:                                
1.222     brouard  7169:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   7170:         k=0;
                   7171:         for(i=1; i<=(nlstate); i++){
                   7172:           for(j=1; j<=(nlstate+ndeath);j++){
                   7173:             k=k+1;
                   7174:             gm[k]=pmmij[i][j];
                   7175:           }
                   7176:         }
1.220     brouard  7177:                                
1.222     brouard  7178:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   7179:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   7180:        }
1.126     brouard  7181: 
1.222     brouard  7182:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   7183:         for(theta=1; theta <=npar; theta++)
                   7184:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  7185:                        
1.222     brouard  7186:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   7187:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  7188:                        
1.222     brouard  7189:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  7190:                        
1.222     brouard  7191:        k=0;
                   7192:        for(i=1; i<=(nlstate); i++){
                   7193:         for(j=1; j<=(nlstate+ndeath);j++){
                   7194:           k=k+1;
                   7195:           mu[k][(int) age]=pmmij[i][j];
                   7196:         }
                   7197:        }
                   7198:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   7199:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   7200:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  7201:                        
1.222     brouard  7202:        /*printf("\n%d ",(int)age);
                   7203:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7204:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7205:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7206:         }*/
1.220     brouard  7207:                        
1.222     brouard  7208:        fprintf(ficresprob,"\n%d ",(int)age);
                   7209:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   7210:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  7211:                        
1.222     brouard  7212:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   7213:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   7214:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7215:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   7216:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   7217:        }
                   7218:        i=0;
                   7219:        for (k=1; k<=(nlstate);k++){
                   7220:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   7221:           i++;
                   7222:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   7223:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   7224:           for (j=1; j<=i;j++){
                   7225:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   7226:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   7227:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   7228:           }
                   7229:         }
                   7230:        }/* end of loop for state */
                   7231:      } /* end of loop for age */
                   7232:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7233:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7234:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7235:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7236:     
                   7237:      /* Confidence intervalle of pij  */
                   7238:      /*
                   7239:        fprintf(ficgp,"\nunset parametric;unset label");
                   7240:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   7241:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   7242:        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);
                   7243:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   7244:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   7245:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   7246:      */
                   7247:                
                   7248:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   7249:      first1=1;first2=2;
                   7250:      for (k2=1; k2<=(nlstate);k2++){
                   7251:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   7252:         if(l2==k2) continue;
                   7253:         j=(k2-1)*(nlstate+ndeath)+l2;
                   7254:         for (k1=1; k1<=(nlstate);k1++){
                   7255:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   7256:             if(l1==k1) continue;
                   7257:             i=(k1-1)*(nlstate+ndeath)+l1;
                   7258:             if(i<=j) continue;
                   7259:             for (age=bage; age<=fage; age ++){ 
                   7260:               if ((int)age %5==0){
                   7261:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   7262:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7263:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7264:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   7265:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   7266:                 c12=cv12/sqrt(v1*v2);
                   7267:                 /* Computing eigen value of matrix of covariance */
                   7268:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7269:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7270:                 if ((lc2 <0) || (lc1 <0) ){
                   7271:                   if(first2==1){
                   7272:                     first1=0;
                   7273:                     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);
                   7274:                   }
                   7275:                   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);
                   7276:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   7277:                   /* lc2=fabs(lc2); */
                   7278:                 }
1.220     brouard  7279:                                                                
1.222     brouard  7280:                 /* Eigen vectors */
1.280     brouard  7281:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   7282:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7283:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7284:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   7285:                 }else
                   7286:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  7287:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   7288:                 v21=(lc1-v1)/cv12*v11;
                   7289:                 v12=-v21;
                   7290:                 v22=v11;
                   7291:                 tnalp=v21/v11;
                   7292:                 if(first1==1){
                   7293:                   first1=0;
                   7294:                   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);
                   7295:                 }
                   7296:                 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);
                   7297:                 /*printf(fignu*/
                   7298:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   7299:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   7300:                 if(first==1){
                   7301:                   first=0;
                   7302:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   7303:                   fprintf(ficgp,"\nset parametric;unset label");
                   7304:                   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);
                   7305:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  7306:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  7307:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  7308: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  7309:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   7310:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7311:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7312:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   7313:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7314:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7315:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7316:                   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  7317:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   7318:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  7319:                 }else{
                   7320:                   first=0;
                   7321:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   7322:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7323:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7324:                   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  7325:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   7326:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  7327:                 }/* if first */
                   7328:               } /* age mod 5 */
                   7329:             } /* end loop age */
                   7330:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7331:             first=1;
                   7332:           } /*l12 */
                   7333:         } /* k12 */
                   7334:        } /*l1 */
                   7335:      }/* k1 */
1.332   ! brouard  7336:    }  /* loop on combination of covariates j1 */
1.326     brouard  7337:    } /* loop on nres */
1.222     brouard  7338:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   7339:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   7340:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7341:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   7342:    free_vector(xp,1,npar);
                   7343:    fclose(ficresprob);
                   7344:    fclose(ficresprobcov);
                   7345:    fclose(ficresprobcor);
                   7346:    fflush(ficgp);
                   7347:    fflush(fichtmcov);
                   7348:  }
1.126     brouard  7349: 
                   7350: 
                   7351: /******************* Printing html file ***********/
1.201     brouard  7352: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  7353:                  int lastpass, int stepm, int weightopt, char model[],\
                   7354:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  7355:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   7356:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   7357:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.237     brouard  7358:   int jj1, k1, i1, cpt, k4, nres;
1.319     brouard  7359:   /* In fact some results are already printed in fichtm which is open */
1.126     brouard  7360:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   7361:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   7362: </ul>");
1.319     brouard  7363: /*    fprintf(fichtm,"<ul><li> model=1+age+%s\n \ */
                   7364: /* </ul>", model); */
1.214     brouard  7365:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   7366:    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",
                   7367:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
1.332   ! brouard  7368:    fprintf(fichtm,"<li> - Observed prevalence (cross-sectional prevalence) in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> (html file) ",
1.213     brouard  7369:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   7370:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  7371:    fprintf(fichtm,"\
                   7372:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  7373:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  7374:    fprintf(fichtm,"\
1.217     brouard  7375:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   7376:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   7377:    fprintf(fichtm,"\
1.288     brouard  7378:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7379:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  7380:    fprintf(fichtm,"\
1.288     brouard  7381:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  7382:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   7383:    fprintf(fichtm,"\
1.211     brouard  7384:  - (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  7385:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7386:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  7387:    if(prevfcast==1){
                   7388:      fprintf(fichtm,"\
                   7389:  - Prevalence projections by age and states:                           \
1.201     brouard  7390:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  7391:    }
1.126     brouard  7392: 
                   7393: 
1.225     brouard  7394:    m=pow(2,cptcoveff);
1.222     brouard  7395:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7396: 
1.317     brouard  7397:    fprintf(fichtm," \n<ul><li><b>Graphs (first order)</b></li><p>");
1.264     brouard  7398: 
                   7399:    jj1=0;
                   7400: 
                   7401:    fprintf(fichtm," \n<ul>");
                   7402:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   7403:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
                   7404:      if(m != 1 && TKresult[nres]!= k1)
                   7405:        continue;
                   7406:      jj1++;
                   7407:      if (cptcovn > 0) {
                   7408:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
                   7409:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7410:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7411:        }
                   7412:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7413:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7414:        }
                   7415:        fprintf(fichtm,"\">");
                   7416:        
                   7417:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   7418:        fprintf(fichtm,"************ Results for covariates");
                   7419:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7420:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7421:        }
                   7422:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7423:         fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7424:        }
                   7425:        if(invalidvarcomb[k1]){
                   7426:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   7427:         continue;
                   7428:        }
                   7429:        fprintf(fichtm,"</a></li>");
                   7430:      } /* cptcovn >0 */
                   7431:    }
1.317     brouard  7432:    fprintf(fichtm," \n</ul>");
1.264     brouard  7433: 
1.222     brouard  7434:    jj1=0;
1.237     brouard  7435: 
                   7436:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.241     brouard  7437:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
1.253     brouard  7438:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7439:        continue;
1.220     brouard  7440: 
1.222     brouard  7441:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7442:      jj1++;
                   7443:      if (cptcovn > 0) {
1.264     brouard  7444:        fprintf(fichtm,"\n<p><a name=\"rescov");
                   7445:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7446:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7447:        }
                   7448:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7449:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7450:        }
                   7451:        fprintf(fichtm,"\"</a>");
                   7452:  
1.222     brouard  7453:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  7454:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.237     brouard  7455:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7456:         printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
                   7457:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   7458:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  7459:        }
1.237     brouard  7460:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7461:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7462:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);fflush(stdout);
                   7463:       }
                   7464:        
1.230     brouard  7465:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.321     brouard  7466:        fprintf(fichtm," (model=%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.222     brouard  7467:        if(invalidvarcomb[k1]){
                   7468:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   7469:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   7470:         continue;
                   7471:        }
                   7472:      }
                   7473:      /* aij, bij */
1.259     brouard  7474:      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  7475: <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  7476:      /* Pij */
1.241     brouard  7477:      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> \
                   7478: <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  7479:      /* Quasi-incidences */
                   7480:      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  7481:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  7482:  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  7483: 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> \
                   7484: <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  7485:      /* Survival functions (period) in state j */
                   7486:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  7487:        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);
                   7488:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   7489:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.222     brouard  7490:      }
                   7491:      /* State specific survival functions (period) */
                   7492:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  7493:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
                   7494:  And probability to be observed in various states (up to %d) being in state %d at different ages.      \
1.329     brouard  7495:  <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);
                   7496:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   7497:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.222     brouard  7498:      }
1.288     brouard  7499:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  7500:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  7501:        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);
                   7502:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"P_"),subdirf2(optionfilefiname,"P_"));
                   7503:       fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.222     brouard  7504:      }
1.296     brouard  7505:      if(prevbcast==1){
1.288     brouard  7506:        /* Backward prevalence in each health state */
1.222     brouard  7507:        for(cpt=1; cpt<=nlstate;cpt++){
1.264     brouard  7508:         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  7509: <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  7510:        }
1.217     brouard  7511:      }
1.222     brouard  7512:      if(prevfcast==1){
1.288     brouard  7513:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  7514:        for(cpt=1; cpt<=nlstate;cpt++){
1.314     brouard  7515:         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);
                   7516:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
                   7517:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
                   7518:                 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  7519:        }
                   7520:      }
1.296     brouard  7521:      if(prevbcast==1){
1.268     brouard  7522:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   7523:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  7524:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
                   7525:  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 \
                   7526:  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  7527: 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);
                   7528:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
                   7529:         fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
1.268     brouard  7530:        }
                   7531:      }
1.220     brouard  7532:         
1.222     brouard  7533:      for(cpt=1; cpt<=nlstate;cpt++) {
1.314     brouard  7534:        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);
                   7535:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
                   7536:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
1.222     brouard  7537:      }
                   7538:      /* } /\* end i1 *\/ */
                   7539:    }/* End k1 */
                   7540:    fprintf(fichtm,"</ul>");
1.126     brouard  7541: 
1.222     brouard  7542:    fprintf(fichtm,"\
1.126     brouard  7543: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  7544:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  7545:  - 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  7546: But because parameters are usually highly correlated (a higher incidence of disability \
                   7547: and a higher incidence of recovery can give very close observed transition) it might \
                   7548: be very useful to look not only at linear confidence intervals estimated from the \
                   7549: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   7550: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   7551: covariance matrix of the one-step probabilities. \
                   7552: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  7553: 
1.222     brouard  7554:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   7555:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   7556:    fprintf(fichtm,"\
1.126     brouard  7557:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7558:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  7559: 
1.222     brouard  7560:    fprintf(fichtm,"\
1.126     brouard  7561:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7562:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   7563:    fprintf(fichtm,"\
1.126     brouard  7564:  - 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): \
                   7565:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7566:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  7567:    fprintf(fichtm,"\
1.126     brouard  7568:  - (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): \
                   7569:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7570:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  7571:    fprintf(fichtm,"\
1.288     brouard  7572:  - 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  7573:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   7574:    fprintf(fichtm,"\
1.128     brouard  7575:  - 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  7576:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   7577:    fprintf(fichtm,"\
1.288     brouard  7578:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  7579:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  7580: 
                   7581: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   7582: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   7583: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   7584: /*     <br>",fileres,fileres,fileres,fileres); */
                   7585: /*  else  */
                   7586: /*    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  7587:    fflush(fichtm);
1.126     brouard  7588: 
1.225     brouard  7589:    m=pow(2,cptcoveff);
1.222     brouard  7590:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7591: 
1.317     brouard  7592:    fprintf(fichtm," <ul><li><b>Graphs (second order)</b></li><p>");
                   7593: 
                   7594:   jj1=0;
                   7595: 
                   7596:    fprintf(fichtm," \n<ul>");
                   7597:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   7598:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
                   7599:      if(m != 1 && TKresult[nres]!= k1)
                   7600:        continue;
                   7601:      jj1++;
                   7602:      if (cptcovn > 0) {
                   7603:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescovsecond");
                   7604:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7605:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7606:        }
                   7607:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7608:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7609:        }
                   7610:        fprintf(fichtm,"\">");
                   7611:        
                   7612:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   7613:        fprintf(fichtm,"************ Results for covariates");
                   7614:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7615:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7616:        }
                   7617:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7618:         fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7619:        }
                   7620:        if(invalidvarcomb[k1]){
                   7621:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   7622:         continue;
                   7623:        }
                   7624:        fprintf(fichtm,"</a></li>");
                   7625:      } /* cptcovn >0 */
                   7626:    }
                   7627:    fprintf(fichtm," \n</ul>");
                   7628: 
1.222     brouard  7629:    jj1=0;
1.237     brouard  7630: 
1.241     brouard  7631:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.222     brouard  7632:    for(k1=1; k1<=m;k1++){
1.253     brouard  7633:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7634:        continue;
1.222     brouard  7635:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7636:      jj1++;
1.126     brouard  7637:      if (cptcovn > 0) {
1.317     brouard  7638:        fprintf(fichtm,"\n<p><a name=\"rescovsecond");
                   7639:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7640:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7641:        }
                   7642:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7643:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7644:        }
                   7645:        fprintf(fichtm,"\"</a>");
                   7646:        
1.126     brouard  7647:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.317     brouard  7648:        for (cpt=1; cpt<=cptcoveff;cpt++){  /**< cptcoveff number of variables */
1.237     brouard  7649:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);
1.317     brouard  7650:         printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
1.237     brouard  7651:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
1.317     brouard  7652:        }
1.237     brouard  7653:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7654:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7655:       }
                   7656: 
1.321     brouard  7657:        fprintf(fichtm," (model=%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.220     brouard  7658: 
1.222     brouard  7659:        if(invalidvarcomb[k1]){
                   7660:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   7661:         continue;
                   7662:        }
1.126     brouard  7663:      }
                   7664:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  7665:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.314     brouard  7666: 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);
                   7667:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   7668:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
1.126     brouard  7669:      }
                   7670:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.314     brouard  7671: health expectancies in each live states (1 to %d). If popbased=1 the smooth (due to the model) \
1.128     brouard  7672: true period expectancies (those weighted with period prevalences are also\
                   7673:  drawn in addition to the population based expectancies computed using\
1.314     brouard  7674:  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);
                   7675:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
                   7676:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  7677:      /* } /\* end i1 *\/ */
                   7678:    }/* End k1 */
1.241     brouard  7679:   }/* End nres */
1.222     brouard  7680:    fprintf(fichtm,"</ul>");
                   7681:    fflush(fichtm);
1.126     brouard  7682: }
                   7683: 
                   7684: /******************* Gnuplot file **************/
1.296     brouard  7685: 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  7686: 
                   7687:   char dirfileres[132],optfileres[132];
1.264     brouard  7688:   char gplotcondition[132], gplotlabel[132];
1.237     brouard  7689:   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  7690:   int lv=0, vlv=0, kl=0;
1.130     brouard  7691:   int ng=0;
1.201     brouard  7692:   int vpopbased;
1.223     brouard  7693:   int ioffset; /* variable offset for columns */
1.270     brouard  7694:   int iyearc=1; /* variable column for year of projection  */
                   7695:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  7696:   int nres=0; /* Index of resultline */
1.266     brouard  7697:   int istart=1; /* For starting graphs in projections */
1.219     brouard  7698: 
1.126     brouard  7699: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   7700: /*     printf("Problem with file %s",optionfilegnuplot); */
                   7701: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   7702: /*   } */
                   7703: 
                   7704:   /*#ifdef windows */
                   7705:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  7706:   /*#endif */
1.225     brouard  7707:   m=pow(2,cptcoveff);
1.126     brouard  7708: 
1.274     brouard  7709:   /* diagram of the model */
                   7710:   fprintf(ficgp,"\n#Diagram of the model \n");
                   7711:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   7712:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   7713:   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);
                   7714: 
                   7715:   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);
                   7716:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   7717:   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);
                   7718:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   7719:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   7720:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   7721:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   7722: 
1.202     brouard  7723:   /* Contribution to likelihood */
                   7724:   /* Plot the probability implied in the likelihood */
1.223     brouard  7725:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   7726:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   7727:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   7728:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  7729: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  7730:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   7731: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  7732:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   7733:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   7734:   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));
                   7735:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   7736:   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));
                   7737:   for (i=1; i<= nlstate ; i ++) {
                   7738:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   7739:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   7740:     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);
                   7741:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   7742:       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);
                   7743:     }
                   7744:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   7745:   }
                   7746:   /* 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 */               
                   7747:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   7748:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   7749:   fprintf(ficgp,"\nset out;unset log\n");
                   7750:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  7751: 
1.126     brouard  7752:   strcpy(dirfileres,optionfilefiname);
                   7753:   strcpy(optfileres,"vpl");
1.223     brouard  7754:   /* 1eme*/
1.238     brouard  7755:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
                   7756:     for (k1=1; k1<= m ; k1 ++){ /* For each valid combination of covariate */
1.236     brouard  7757:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.238     brouard  7758:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.253     brouard  7759:        if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7760:          continue;
                   7761:        /* We are interested in selected combination by the resultline */
1.246     brouard  7762:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  7763:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  7764:        strcpy(gplotlabel,"(");
1.238     brouard  7765:        for (k=1; k<=cptcoveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
1.332   ! brouard  7766:          /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the value of the covariate corresponding to k1 combination *\/ */
        !          7767:          lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.238     brouard  7768:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7769:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7770:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7771:          vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
                   7772:          /* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
1.246     brouard  7773:          /* printf(" V%d=%d ",Tvaraff[k],vlv); */
1.238     brouard  7774:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7775:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7776:        }
                   7777:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.246     brouard  7778:          /* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  7779:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7780:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7781:        }
                   7782:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  7783:        /* printf("\n#\n"); */
1.238     brouard  7784:        fprintf(ficgp,"\n#\n");
                   7785:        if(invalidvarcomb[k1]){
1.260     brouard  7786:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  7787:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7788:          continue;
                   7789:        }
1.235     brouard  7790:       
1.241     brouard  7791:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   7792:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  7793:        /* 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  7794:        fprintf(ficgp,"set title \"Alive state %d %s model=%s\" font \"Helvetica,12\"\n",cpt,gplotlabel,model);
1.260     brouard  7795:        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);
                   7796:        /* 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); */
                   7797:       /* k1-1 error should be nres-1*/
1.238     brouard  7798:        for (i=1; i<= nlstate ; i ++) {
                   7799:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7800:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   7801:        }
1.288     brouard  7802:        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  7803:        for (i=1; i<= nlstate ; i ++) {
                   7804:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7805:          else fprintf(ficgp," %%*lf (%%*lf)");
                   7806:        } 
1.260     brouard  7807:        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  7808:        for (i=1; i<= nlstate ; i ++) {
                   7809:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7810:          else fprintf(ficgp," %%*lf (%%*lf)");
                   7811:        }  
1.265     brouard  7812:        /* 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)); */
                   7813:        
                   7814:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   7815:         if(cptcoveff ==0){
1.271     brouard  7816:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  7817:        }else{
                   7818:          kl=0;
                   7819:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332   ! brouard  7820:            /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
        !          7821:            lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.265     brouard  7822:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7823:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7824:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7825:            vlv= nbcode[Tvaraff[k]][lv];
                   7826:            kl++;
                   7827:            /* 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 *\/ */
                   7828:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7829:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7830:            /* ''  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*/
                   7831:            if(k==cptcoveff){
                   7832:              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], \
                   7833:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   7834:            }else{
                   7835:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   7836:              kl++;
                   7837:            }
                   7838:          } /* end covariate */
                   7839:        } /* end if no covariate */
                   7840: 
1.296     brouard  7841:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  7842:          /* 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  7843:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  7844:          if(cptcoveff ==0){
1.245     brouard  7845:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  7846:          }else{
                   7847:            kl=0;
                   7848:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332   ! brouard  7849:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
        !          7850:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.238     brouard  7851:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7852:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7853:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332   ! brouard  7854:              /* vlv= nbcode[Tvaraff[k]][lv]; */
        !          7855:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.223     brouard  7856:              kl++;
1.238     brouard  7857:              /* 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 *\/ */
                   7858:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7859:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7860:              /* ''  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*/
                   7861:              if(k==cptcoveff){
1.245     brouard  7862:                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  7863:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  7864:              }else{
1.332   ! brouard  7865:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]);
1.238     brouard  7866:                kl++;
                   7867:              }
                   7868:            } /* end covariate */
                   7869:          } /* end if no covariate */
1.296     brouard  7870:          if(prevbcast == 1){
1.268     brouard  7871:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   7872:            /* k1-1 error should be nres-1*/
                   7873:            for (i=1; i<= nlstate ; i ++) {
                   7874:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7875:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   7876:            }
1.271     brouard  7877:            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  7878:            for (i=1; i<= nlstate ; i ++) {
                   7879:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7880:              else fprintf(ficgp," %%*lf (%%*lf)");
                   7881:            } 
1.276     brouard  7882:            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  7883:            for (i=1; i<= nlstate ; i ++) {
                   7884:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7885:              else fprintf(ficgp," %%*lf (%%*lf)");
                   7886:            } 
1.274     brouard  7887:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  7888:          } /* end if backprojcast */
1.296     brouard  7889:        } /* end if prevbcast */
1.276     brouard  7890:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   7891:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  7892:       } /* nres */
1.201     brouard  7893:     } /* k1 */
                   7894:   } /* cpt */
1.235     brouard  7895: 
                   7896:   
1.126     brouard  7897:   /*2 eme*/
1.238     brouard  7898:   for (k1=1; k1<= m ; k1 ++){  
                   7899:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7900:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7901:        continue;
                   7902:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  7903:       strcpy(gplotlabel,"(");
1.238     brouard  7904:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.332   ! brouard  7905:        /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate number corresponding to k1 combination *\/ */
        !          7906:        lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.223     brouard  7907:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7908:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7909:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332   ! brouard  7910:        /* vlv= nbcode[Tvaraff[k]][lv]; */
        !          7911:        vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.223     brouard  7912:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7913:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  7914:       }
1.237     brouard  7915:       /* for(k=1; k <= ncovds; k++){ */
1.236     brouard  7916:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  7917:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.236     brouard  7918:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7919:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7920:       }
1.264     brouard  7921:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  7922:       fprintf(ficgp,"\n#\n");
1.223     brouard  7923:       if(invalidvarcomb[k1]){
                   7924:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7925:        continue;
                   7926:       }
1.219     brouard  7927:                        
1.241     brouard  7928:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  7929:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  7930:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   7931:        if(vpopbased==0){
1.238     brouard  7932:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  7933:        }else
1.238     brouard  7934:          fprintf(ficgp,"\nreplot ");
                   7935:        for (i=1; i<= nlstate+1 ; i ++) {
                   7936:          k=2*i;
1.261     brouard  7937:          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  7938:          for (j=1; j<= nlstate+1 ; j ++) {
                   7939:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7940:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7941:          }   
                   7942:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   7943:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
1.261     brouard  7944:          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  7945:          for (j=1; j<= nlstate+1 ; j ++) {
                   7946:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7947:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7948:          }   
                   7949:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  7950:          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  7951:          for (j=1; j<= nlstate+1 ; j ++) {
                   7952:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7953:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7954:          }   
                   7955:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   7956:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   7957:        } /* state */
                   7958:       } /* vpopbased */
1.264     brouard  7959:       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  7960:     } /* end nres */
                   7961:   } /* k1 end 2 eme*/
                   7962:        
                   7963:        
                   7964:   /*3eme*/
                   7965:   for (k1=1; k1<= m ; k1 ++){
                   7966:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7967:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7968:        continue;
                   7969: 
1.332   ! brouard  7970:       for (cpt=1; cpt<= nlstate ; cpt ++) { /* Fragile no verification of covariate values */
1.261     brouard  7971:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  7972:        strcpy(gplotlabel,"(");
1.238     brouard  7973:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.332   ! brouard  7974:          /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate number corresponding to k1 combination *\/ */
        !          7975:          lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /* Should be the covariate value corresponding to combination k1 and covariate k */
1.238     brouard  7976:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7977:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7978:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332   ! brouard  7979:          /* vlv= nbcode[Tvaraff[k]][lv]; */
        !          7980:          vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.238     brouard  7981:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7982:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7983:        }
                   7984:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.332   ! brouard  7985:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]);
        !          7986:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]);
1.238     brouard  7987:        }       
1.264     brouard  7988:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7989:        fprintf(ficgp,"\n#\n");
                   7990:        if(invalidvarcomb[k1]){
                   7991:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7992:          continue;
                   7993:        }
                   7994:                        
                   7995:        /*       k=2+nlstate*(2*cpt-2); */
                   7996:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  7997:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  7998:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  7999:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  8000: 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  8001:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8002:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8003:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   8004:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8005:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8006:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  8007:                                
1.238     brouard  8008:        */
                   8009:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  8010:          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  8011:          /*    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  8012:                                
1.238     brouard  8013:        } 
1.261     brouard  8014:        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  8015:       }
1.264     brouard  8016:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  8017:     } /* end nres */
                   8018:   } /* end kl 3eme */
1.126     brouard  8019:   
1.223     brouard  8020:   /* 4eme */
1.201     brouard  8021:   /* Survival functions (period) from state i in state j by initial state i */
1.238     brouard  8022:   for (k1=1; k1<=m; k1++){    /* For each covariate and each value */
                   8023:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  8024:       if(m != 1 && TKresult[nres]!= k1)
1.223     brouard  8025:        continue;
1.238     brouard  8026:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  8027:        strcpy(gplotlabel,"(");
1.238     brouard  8028:        fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
                   8029:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.332   ! brouard  8030:          lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
        !          8031:          /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate number corresponding to k1 combination *\/ */
1.238     brouard  8032:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8033:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8034:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332   ! brouard  8035:          /* vlv= nbcode[Tvaraff[k]][lv]; */
        !          8036:          vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.238     brouard  8037:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8038:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  8039:        }
                   8040:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.332   ! brouard  8041:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
        !          8042:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
1.238     brouard  8043:        }       
1.264     brouard  8044:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8045:        fprintf(ficgp,"\n#\n");
                   8046:        if(invalidvarcomb[k1]){
                   8047:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8048:          continue;
1.223     brouard  8049:        }
1.238     brouard  8050:       
1.241     brouard  8051:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  8052:        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  8053:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8054: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8055:        k=3;
                   8056:        for (i=1; i<= nlstate ; i ++){
                   8057:          if(i==1){
                   8058:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8059:          }else{
                   8060:            fprintf(ficgp,", '' ");
                   8061:          }
                   8062:          l=(nlstate+ndeath)*(i-1)+1;
                   8063:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8064:          for (j=2; j<= nlstate+ndeath ; j ++)
                   8065:            fprintf(ficgp,"+$%d",k+l+j-1);
                   8066:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   8067:        } /* nlstate */
1.264     brouard  8068:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8069:       } /* end cpt state*/ 
                   8070:     } /* end nres */
                   8071:   } /* end covariate k1 */  
                   8072: 
1.220     brouard  8073: /* 5eme */
1.201     brouard  8074:   /* Survival functions (period) from state i in state j by final state j */
1.238     brouard  8075:   for (k1=1; k1<= m ; k1++){ /* For each covariate combination if any */
                   8076:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  8077:       if(m != 1 && TKresult[nres]!= k1)
1.227     brouard  8078:        continue;
1.238     brouard  8079:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  8080:        strcpy(gplotlabel,"(");
1.238     brouard  8081:        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);
                   8082:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.332   ! brouard  8083:          lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
        !          8084:          /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate number corresponding to k1 combination *\/ */
1.238     brouard  8085:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8086:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8087:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332   ! brouard  8088:          /* vlv= nbcode[Tvaraff[k]][lv]; */
        !          8089:          vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.238     brouard  8090:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8091:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  8092:        }
                   8093:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.332   ! brouard  8094:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
        !          8095:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
1.238     brouard  8096:        }       
1.264     brouard  8097:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8098:        fprintf(ficgp,"\n#\n");
                   8099:        if(invalidvarcomb[k1]){
                   8100:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8101:          continue;
                   8102:        }
1.227     brouard  8103:       
1.241     brouard  8104:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  8105:        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  8106:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8107: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8108:        k=3;
                   8109:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8110:          if(j==1)
                   8111:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8112:          else
                   8113:            fprintf(ficgp,", '' ");
                   8114:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8115:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   8116:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   8117:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   8118:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   8119:        } /* nlstate */
                   8120:        fprintf(ficgp,", '' ");
                   8121:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   8122:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8123:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8124:          if(j < nlstate)
                   8125:            fprintf(ficgp,"$%d +",k+l);
                   8126:          else
                   8127:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   8128:        }
1.264     brouard  8129:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8130:       } /* end cpt state*/ 
                   8131:     } /* end covariate */  
                   8132:   } /* end nres */
1.227     brouard  8133:   
1.220     brouard  8134: /* 6eme */
1.202     brouard  8135:   /* CV preval stable (period) for each covariate */
1.237     brouard  8136:   for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   8137:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  8138:     if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  8139:       continue;
1.255     brouard  8140:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  8141:       strcpy(gplotlabel,"(");      
1.288     brouard  8142:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.225     brouard  8143:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.332   ! brouard  8144:        /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate number corresponding to k1 combination *\/ */
        !          8145:        lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.227     brouard  8146:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8147:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8148:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332   ! brouard  8149:        /* vlv= nbcode[Tvaraff[k]][lv]; */
        !          8150:        vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.227     brouard  8151:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8152:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  8153:       }
1.237     brouard  8154:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.332   ! brouard  8155:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
        !          8156:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
1.237     brouard  8157:       }        
1.264     brouard  8158:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8159:       fprintf(ficgp,"\n#\n");
1.223     brouard  8160:       if(invalidvarcomb[k1]){
1.227     brouard  8161:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8162:        continue;
1.223     brouard  8163:       }
1.227     brouard  8164:       
1.241     brouard  8165:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  8166:       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  8167:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8168: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  8169:       k=3; /* Offset */
1.255     brouard  8170:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  8171:        if(i==1)
                   8172:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8173:        else
                   8174:          fprintf(ficgp,", '' ");
1.255     brouard  8175:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  8176:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8177:        for (j=2; j<= nlstate ; j ++)
                   8178:          fprintf(ficgp,"+$%d",k+l+j-1);
                   8179:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  8180:       } /* nlstate */
1.264     brouard  8181:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  8182:     } /* end cpt state*/ 
                   8183:   } /* end covariate */  
1.227     brouard  8184:   
                   8185:   
1.220     brouard  8186: /* 7eme */
1.296     brouard  8187:   if(prevbcast == 1){
1.288     brouard  8188:     /* CV backward prevalence  for each covariate */
1.237     brouard  8189:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   8190:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  8191:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  8192:        continue;
1.268     brouard  8193:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  8194:        strcpy(gplotlabel,"(");      
1.288     brouard  8195:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.227     brouard  8196:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.332   ! brouard  8197:          /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate number corresponding to k1 combination *\/ */
        !          8198:          lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.227     brouard  8199:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8200:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
1.223     brouard  8201:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332   ! brouard  8202:          /* vlv= nbcode[Tvaraff[k]][lv]; */
        !          8203:          vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.227     brouard  8204:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8205:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.227     brouard  8206:        }
1.237     brouard  8207:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.332   ! brouard  8208:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
        !          8209:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
1.237     brouard  8210:        }       
1.264     brouard  8211:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8212:        fprintf(ficgp,"\n#\n");
                   8213:        if(invalidvarcomb[k1]){
                   8214:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8215:          continue;
                   8216:        }
                   8217:        
1.241     brouard  8218:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  8219:        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  8220:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8221: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  8222:        k=3; /* Offset */
1.268     brouard  8223:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  8224:          if(i==1)
                   8225:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   8226:          else
                   8227:            fprintf(ficgp,", '' ");
                   8228:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  8229:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.324     brouard  8230:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   8231:          /* 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  8232:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  8233:          /* for (j=2; j<= nlstate ; j ++) */
                   8234:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   8235:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  8236:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  8237:        } /* nlstate */
1.264     brouard  8238:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  8239:       } /* end cpt state*/ 
                   8240:     } /* end covariate */  
1.296     brouard  8241:   } /* End if prevbcast */
1.218     brouard  8242:   
1.223     brouard  8243:   /* 8eme */
1.218     brouard  8244:   if(prevfcast==1){
1.288     brouard  8245:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  8246:     
1.237     brouard  8247:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   8248:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  8249:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  8250:        continue;
1.211     brouard  8251:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  8252:        strcpy(gplotlabel,"(");      
1.288     brouard  8253:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.227     brouard  8254:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
1.332   ! brouard  8255:          /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
        !          8256:          lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.227     brouard  8257:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8258:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8259:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332   ! brouard  8260:          /* vlv= nbcode[Tvaraff[k]][lv]; */
        !          8261:          vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.227     brouard  8262:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8263:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.227     brouard  8264:        }
1.237     brouard  8265:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.332   ! brouard  8266:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
        !          8267:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
1.237     brouard  8268:        }       
1.264     brouard  8269:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8270:        fprintf(ficgp,"\n#\n");
                   8271:        if(invalidvarcomb[k1]){
                   8272:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8273:          continue;
                   8274:        }
                   8275:        
                   8276:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  8277:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  8278:        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  8279:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  8280: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  8281: 
                   8282:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   8283:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8284:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8285:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  8286:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8287:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8288:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8289:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  8290:          if(i==istart){
1.227     brouard  8291:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   8292:          }else{
                   8293:            fprintf(ficgp,",\\\n '' ");
                   8294:          }
                   8295:          if(cptcoveff ==0){ /* No covariate */
                   8296:            ioffset=2; /* Age is in 2 */
                   8297:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8298:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8299:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8300:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8301:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  8302:            if(i==nlstate+1){
1.270     brouard  8303:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  8304:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   8305:              fprintf(ficgp,",\\\n '' ");
                   8306:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  8307:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  8308:                     offyear,                           \
1.268     brouard  8309:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  8310:            }else
1.227     brouard  8311:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   8312:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8313:          }else{ /* more than 2 covariates */
1.270     brouard  8314:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   8315:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8316:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   8317:            iyearc=ioffset-1;
                   8318:            iagec=ioffset;
1.227     brouard  8319:            fprintf(ficgp," u %d:(",ioffset); 
                   8320:            kl=0;
                   8321:            strcpy(gplotcondition,"(");
                   8322:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
1.332   ! brouard  8323:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
        !          8324:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.227     brouard  8325:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8326:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8327:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332   ! brouard  8328:              /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
        !          8329:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.227     brouard  8330:              kl++;
                   8331:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   8332:              kl++;
                   8333:              if(k <cptcoveff && cptcoveff>1)
                   8334:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   8335:            }
                   8336:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   8337:            /* 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 *\/ */
                   8338:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8339:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8340:            /* ''  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*/
                   8341:            if(i==nlstate+1){
1.270     brouard  8342:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   8343:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  8344:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  8345:              fprintf(ficgp," u %d:(",iagec); 
                   8346:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   8347:                      iyearc, iagec, offyear,                           \
                   8348:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  8349: /*  '' 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  8350:            }else{
                   8351:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   8352:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8353:            }
                   8354:          } /* end if covariate */
                   8355:        } /* nlstate */
1.264     brouard  8356:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  8357:       } /* end cpt state*/
                   8358:     } /* end covariate */
                   8359:   } /* End if prevfcast */
1.227     brouard  8360:   
1.296     brouard  8361:   if(prevbcast==1){
1.268     brouard  8362:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   8363:     
                   8364:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   8365:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8366:       if(m != 1 && TKresult[nres]!= k1)
                   8367:        continue;
                   8368:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   8369:        strcpy(gplotlabel,"(");      
                   8370:        fprintf(ficgp,"\n#\n#\n#Back projection of prevalence to stable (mixed) back prevalence: 'BPROJ_' files, covariatecombination#=%d originstate=%d",k1, cpt);
                   8371:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
1.332   ! brouard  8372:          /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
        !          8373:          lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /* Should be the covariate value corresponding to combination k1 and covariate k */
1.268     brouard  8374:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8375:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8376:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332   ! brouard  8377:          /* vlv= nbcode[Tvaraff[k]][lv]; */
        !          8378:          vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.268     brouard  8379:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   8380:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
                   8381:        }
                   8382:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.332   ! brouard  8383:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
        !          8384:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
1.268     brouard  8385:        }       
                   8386:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   8387:        fprintf(ficgp,"\n#\n");
                   8388:        if(invalidvarcomb[k1]){
                   8389:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8390:          continue;
                   8391:        }
                   8392:        
                   8393:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   8394:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   8395:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   8396:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   8397: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8398: 
                   8399:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   8400:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8401:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8402:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   8403:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8404:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8405:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8406:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8407:          if(i==istart){
                   8408:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   8409:          }else{
                   8410:            fprintf(ficgp,",\\\n '' ");
                   8411:          }
                   8412:          if(cptcoveff ==0){ /* No covariate */
                   8413:            ioffset=2; /* Age is in 2 */
                   8414:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8415:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8416:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8417:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8418:            fprintf(ficgp," u %d:(", ioffset); 
                   8419:            if(i==nlstate+1){
1.270     brouard  8420:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  8421:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   8422:              fprintf(ficgp,",\\\n '' ");
                   8423:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  8424:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  8425:                     offbyear,                          \
                   8426:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   8427:            }else
                   8428:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   8429:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   8430:          }else{ /* more than 2 covariates */
1.270     brouard  8431:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   8432:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8433:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   8434:            iyearc=ioffset-1;
                   8435:            iagec=ioffset;
1.268     brouard  8436:            fprintf(ficgp," u %d:(",ioffset); 
                   8437:            kl=0;
                   8438:            strcpy(gplotcondition,"(");
                   8439:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
1.332   ! brouard  8440:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
        !          8441:              lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /* Should be the covariate value corresponding to combination k1 and covariate k */
1.268     brouard  8442:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8443:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8444:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332   ! brouard  8445:              /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
        !          8446:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.268     brouard  8447:              kl++;
                   8448:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   8449:              kl++;
                   8450:              if(k <cptcoveff && cptcoveff>1)
                   8451:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   8452:            }
                   8453:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   8454:            /* 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 *\/ */
                   8455:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8456:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8457:            /* ''  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*/
                   8458:            if(i==nlstate+1){
1.270     brouard  8459:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   8460:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  8461:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  8462:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  8463:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  8464:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   8465:                      iyearc,iagec,offbyear,                            \
                   8466:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  8467: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   8468:            }else{
                   8469:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   8470:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   8471:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   8472:            }
                   8473:          } /* end if covariate */
                   8474:        } /* nlstate */
                   8475:        fprintf(ficgp,"\nset out; unset label;\n");
                   8476:       } /* end cpt state*/
                   8477:     } /* end covariate */
1.296     brouard  8478:   } /* End if prevbcast */
1.268     brouard  8479:   
1.227     brouard  8480:   
1.238     brouard  8481:   /* 9eme writing MLE parameters */
                   8482:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  8483:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  8484:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  8485:     for(k=1; k <=(nlstate+ndeath); k++){
                   8486:       if (k != i) {
1.227     brouard  8487:        fprintf(ficgp,"#   current state %d\n",k);
                   8488:        for(j=1; j <=ncovmodel; j++){
                   8489:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   8490:          jk++; 
                   8491:        }
                   8492:        fprintf(ficgp,"\n");
1.126     brouard  8493:       }
                   8494:     }
1.223     brouard  8495:   }
1.187     brouard  8496:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  8497:   
1.145     brouard  8498:   /*goto avoid;*/
1.238     brouard  8499:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   8500:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  8501:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   8502:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   8503:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   8504:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   8505:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8506:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   8507:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8508:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   8509:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   8510:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8511:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   8512:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   8513:   fprintf(ficgp,"#\n");
1.223     brouard  8514:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  8515:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.237     brouard  8516:     fprintf(ficgp,"#model=%s \n",model);
1.238     brouard  8517:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.264     brouard  8518:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
                   8519:     for(k1=1; k1 <=m; k1++)  /* For each combination of covariate */
1.237     brouard  8520:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.264     brouard  8521:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  8522:        continue;
1.264     brouard  8523:       fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1);
                   8524:       strcpy(gplotlabel,"(");
1.276     brouard  8525:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.264     brouard  8526:       for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
1.332   ! brouard  8527:        /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
        !          8528:        lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /* Should be the covariate value corresponding to combination k1 and covariate k */
1.264     brouard  8529:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8530:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8531:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332   ! brouard  8532:        /* vlv= nbcode[Tvaraff[k]][lv]; */
        !          8533:        vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.264     brouard  8534:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   8535:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
                   8536:       }
1.237     brouard  8537:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.332   ! brouard  8538:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
        !          8539:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
1.237     brouard  8540:       }        
1.264     brouard  8541:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  8542:       fprintf(ficgp,"\n#\n");
1.264     brouard  8543:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  8544:       fprintf(ficgp,"\nset key outside ");
                   8545:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   8546:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  8547:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   8548:       if (ng==1){
                   8549:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   8550:        fprintf(ficgp,"\nunset log y");
                   8551:       }else if (ng==2){
                   8552:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   8553:        fprintf(ficgp,"\nset log y");
                   8554:       }else if (ng==3){
                   8555:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   8556:        fprintf(ficgp,"\nset log y");
                   8557:       }else
                   8558:        fprintf(ficgp,"\nunset title ");
                   8559:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   8560:       i=1;
                   8561:       for(k2=1; k2<=nlstate; k2++) {
                   8562:        k3=i;
                   8563:        for(k=1; k<=(nlstate+ndeath); k++) {
                   8564:          if (k != k2){
                   8565:            switch( ng) {
                   8566:            case 1:
                   8567:              if(nagesqr==0)
                   8568:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   8569:              else /* nagesqr =1 */
                   8570:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   8571:              break;
                   8572:            case 2: /* ng=2 */
                   8573:              if(nagesqr==0)
                   8574:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   8575:              else /* nagesqr =1 */
                   8576:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   8577:              break;
                   8578:            case 3:
                   8579:              if(nagesqr==0)
                   8580:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   8581:              else /* nagesqr =1 */
                   8582:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   8583:              break;
                   8584:            }
                   8585:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  8586:            ijp=1; /* product no age */
                   8587:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   8588:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  8589:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.329     brouard  8590:              switch(Typevar[j]){
                   8591:              case 1:
                   8592:                if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   8593:                  if(j==Tage[ij]) { /* Product by age  To be looked at!!*//* Bug valgrind */
                   8594:                    if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   8595:                      if(DummyV[j]==0){/* Bug valgrind */
                   8596:                        fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   8597:                      }else{ /* quantitative */
                   8598:                        fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   8599:                        /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8600:                      }
                   8601:                      ij++;
1.268     brouard  8602:                    }
1.237     brouard  8603:                  }
1.329     brouard  8604:                }
                   8605:                break;
                   8606:              case 2:
                   8607:                if(cptcovprod >0){
                   8608:                  if(j==Tprod[ijp]) { /* */ 
                   8609:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   8610:                    if(ijp <=cptcovprod) { /* Product */
                   8611:                      if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   8612:                        if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   8613:                          /* 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)]); */
                   8614:                          fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   8615:                        }else{ /* Vn is dummy and Vm is quanti */
                   8616:                          /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8617:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8618:                        }
                   8619:                      }else{ /* Vn*Vm Vn is quanti */
                   8620:                        if(DummyV[Tvard[ijp][2]]==0){
                   8621:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   8622:                        }else{ /* Both quanti */
                   8623:                          fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8624:                        }
1.268     brouard  8625:                      }
1.329     brouard  8626:                      ijp++;
1.237     brouard  8627:                    }
1.329     brouard  8628:                  } /* end Tprod */
                   8629:                }
                   8630:                break;
                   8631:              case 0:
                   8632:                /* simple covariate */
1.264     brouard  8633:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  8634:                if(Dummy[j]==0){
                   8635:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   8636:                }else{ /* quantitative */
                   8637:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  8638:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  8639:                }
1.329     brouard  8640:               /* end simple */
                   8641:                break;
                   8642:              default:
                   8643:                break;
                   8644:              } /* end switch */
1.237     brouard  8645:            } /* end j */
1.329     brouard  8646:          }else{ /* k=k2 */
                   8647:            if(ng !=1 ){ /* For logit formula of log p11 is more difficult to get */
                   8648:              fprintf(ficgp," (1.");i=i-ncovmodel;
                   8649:            }else
                   8650:              i=i-ncovmodel;
1.223     brouard  8651:          }
1.227     brouard  8652:          
1.223     brouard  8653:          if(ng != 1){
                   8654:            fprintf(ficgp,")/(1");
1.227     brouard  8655:            
1.264     brouard  8656:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  8657:              if(nagesqr==0)
1.264     brouard  8658:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  8659:              else /* nagesqr =1 */
1.264     brouard  8660:                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  8661:               
1.223     brouard  8662:              ij=1;
1.329     brouard  8663:              ijp=1;
                   8664:              /* for(j=3; j <=ncovmodel-nagesqr; j++){ */
                   8665:              for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
                   8666:                switch(Typevar[j]){
                   8667:                case 1:
                   8668:                  if(cptcovage >0){ 
                   8669:                    if(j==Tage[ij]) { /* Bug valgrind */
                   8670:                      if(ij <=cptcovage) { /* Bug valgrind */
                   8671:                        if(DummyV[j]==0){/* Bug valgrind */
                   8672:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]); */
                   8673:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,nbcode[Tvar[j]][codtabm(k1,j)]); */
                   8674:                          fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]);
                   8675:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);; */
                   8676:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8677:                        }else{ /* quantitative */
                   8678:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   8679:                          fprintf(ficgp,"+p%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   8680:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   8681:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8682:                        }
                   8683:                        ij++;
                   8684:                      }
                   8685:                    }
                   8686:                  }
                   8687:                  break;
                   8688:                case 2:
                   8689:                  if(cptcovprod >0){
                   8690:                    if(j==Tprod[ijp]) { /* */ 
                   8691:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   8692:                      if(ijp <=cptcovprod) { /* Product */
                   8693:                        if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   8694:                          if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   8695:                            /* 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)]); */
                   8696:                            fprintf(ficgp,"+p%d*%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   8697:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   8698:                          }else{ /* Vn is dummy and Vm is quanti */
                   8699:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8700:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8701:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8702:                          }
                   8703:                        }else{ /* Vn*Vm Vn is quanti */
                   8704:                          if(DummyV[Tvard[ijp][2]]==0){
                   8705:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   8706:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   8707:                          }else{ /* Both quanti */
                   8708:                            fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8709:                            /* fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8710:                          } 
                   8711:                        }
                   8712:                        ijp++;
                   8713:                      }
                   8714:                    } /* end Tprod */
                   8715:                  } /* end if */
                   8716:                  break;
                   8717:                case 0: 
                   8718:                  /* simple covariate */
                   8719:                  /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
                   8720:                  if(Dummy[j]==0){
                   8721:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   8722:                    fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]); /*  */
                   8723:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   8724:                  }else{ /* quantitative */
                   8725:                    fprintf(ficgp,"+p%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* */
                   8726:                    /* fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* *\/ */
                   8727:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8728:                  }
                   8729:                  /* end simple */
                   8730:                  /* fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);/\* Valgrind bug nbcode *\/ */
                   8731:                  break;
                   8732:                default:
                   8733:                  break;
                   8734:                } /* end switch */
1.223     brouard  8735:              }
                   8736:              fprintf(ficgp,")");
                   8737:            }
                   8738:            fprintf(ficgp,")");
                   8739:            if(ng ==2)
1.276     brouard  8740:              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  8741:            else /* ng= 3 */
1.276     brouard  8742:              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  8743:           }else{ /* end ng <> 1 */
1.223     brouard  8744:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  8745:              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  8746:          }
                   8747:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   8748:            fprintf(ficgp,",");
                   8749:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   8750:            fprintf(ficgp,",");
                   8751:          i=i+ncovmodel;
                   8752:        } /* end k */
                   8753:       } /* end k2 */
1.276     brouard  8754:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   8755:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.264     brouard  8756:     } /* end k1 */
1.223     brouard  8757:   } /* end ng */
                   8758:   /* avoid: */
                   8759:   fflush(ficgp); 
1.126     brouard  8760: }  /* end gnuplot */
                   8761: 
                   8762: 
                   8763: /*************** Moving average **************/
1.219     brouard  8764: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  8765:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  8766:    
1.222     brouard  8767:    int i, cpt, cptcod;
                   8768:    int modcovmax =1;
                   8769:    int mobilavrange, mob;
                   8770:    int iage=0;
1.288     brouard  8771:    int firstA1=0, firstA2=0;
1.222     brouard  8772: 
1.266     brouard  8773:    double sum=0., sumr=0.;
1.222     brouard  8774:    double age;
1.266     brouard  8775:    double *sumnewp, *sumnewm, *sumnewmr;
                   8776:    double *agemingood, *agemaxgood; 
                   8777:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  8778:   
                   8779:   
1.278     brouard  8780:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   8781:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  8782: 
                   8783:    sumnewp = vector(1,ncovcombmax);
                   8784:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  8785:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  8786:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  8787:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  8788:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  8789:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  8790: 
                   8791:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  8792:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  8793:      sumnewp[cptcod]=0.;
1.266     brouard  8794:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   8795:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  8796:    }
                   8797:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   8798:   
1.266     brouard  8799:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   8800:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  8801:      else mobilavrange=mobilav;
                   8802:      for (age=bage; age<=fage; age++)
                   8803:        for (i=1; i<=nlstate;i++)
                   8804:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   8805:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8806:      /* We keep the original values on the extreme ages bage, fage and for 
                   8807:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   8808:        we use a 5 terms etc. until the borders are no more concerned. 
                   8809:      */ 
                   8810:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   8811:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  8812:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   8813:           sumnewm[cptcod]=0.;
                   8814:           for (i=1; i<=nlstate;i++){
1.222     brouard  8815:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   8816:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   8817:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   8818:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   8819:             }
                   8820:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  8821:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8822:           } /* end i */
                   8823:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   8824:         } /* end cptcod */
1.222     brouard  8825:        }/* end age */
                   8826:      }/* end mob */
1.266     brouard  8827:    }else{
                   8828:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  8829:      return -1;
1.266     brouard  8830:    }
                   8831: 
                   8832:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  8833:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   8834:      if(invalidvarcomb[cptcod]){
                   8835:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   8836:        continue;
                   8837:      }
1.219     brouard  8838: 
1.266     brouard  8839:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   8840:        sumnewm[cptcod]=0.;
                   8841:        sumnewmr[cptcod]=0.;
                   8842:        for (i=1; i<=nlstate;i++){
                   8843:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8844:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8845:        }
                   8846:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8847:         agemingoodr[cptcod]=age;
                   8848:        }
                   8849:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8850:           agemingood[cptcod]=age;
                   8851:        }
                   8852:      } /* age */
                   8853:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  8854:        sumnewm[cptcod]=0.;
1.266     brouard  8855:        sumnewmr[cptcod]=0.;
1.222     brouard  8856:        for (i=1; i<=nlstate;i++){
                   8857:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  8858:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8859:        }
                   8860:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8861:         agemaxgoodr[cptcod]=age;
1.222     brouard  8862:        }
                   8863:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  8864:         agemaxgood[cptcod]=age;
                   8865:        }
                   8866:      } /* age */
                   8867:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   8868:      /* but they will change */
1.288     brouard  8869:      firstA1=0;firstA2=0;
1.266     brouard  8870:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   8871:        sumnewm[cptcod]=0.;
                   8872:        sumnewmr[cptcod]=0.;
                   8873:        for (i=1; i<=nlstate;i++){
                   8874:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8875:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8876:        }
                   8877:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   8878:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8879:           agemaxgoodr[cptcod]=age;  /* age min */
                   8880:           for (i=1; i<=nlstate;i++)
                   8881:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8882:         }else{ /* bad we change the value with the values of good ages */
                   8883:           for (i=1; i<=nlstate;i++){
                   8884:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   8885:           } /* i */
                   8886:         } /* end bad */
                   8887:        }else{
                   8888:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8889:           agemaxgood[cptcod]=age;
                   8890:         }else{ /* bad we change the value with the values of good ages */
                   8891:           for (i=1; i<=nlstate;i++){
                   8892:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   8893:           } /* i */
                   8894:         } /* end bad */
                   8895:        }/* end else */
                   8896:        sum=0.;sumr=0.;
                   8897:        for (i=1; i<=nlstate;i++){
                   8898:         sum+=mobaverage[(int)age][i][cptcod];
                   8899:         sumr+=probs[(int)age][i][cptcod];
                   8900:        }
                   8901:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  8902:         if(!firstA1){
                   8903:           firstA1=1;
                   8904:           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);
                   8905:         }
                   8906:         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  8907:        } /* end bad */
                   8908:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   8909:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  8910:         if(!firstA2){
                   8911:           firstA2=1;
                   8912:           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);
                   8913:         }
                   8914:         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  8915:        } /* end bad */
                   8916:      }/* age */
1.266     brouard  8917: 
                   8918:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  8919:        sumnewm[cptcod]=0.;
1.266     brouard  8920:        sumnewmr[cptcod]=0.;
1.222     brouard  8921:        for (i=1; i<=nlstate;i++){
                   8922:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  8923:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8924:        } 
                   8925:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   8926:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   8927:           agemingoodr[cptcod]=age;
                   8928:           for (i=1; i<=nlstate;i++)
                   8929:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8930:         }else{ /* bad we change the value with the values of good ages */
                   8931:           for (i=1; i<=nlstate;i++){
                   8932:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   8933:           } /* i */
                   8934:         } /* end bad */
                   8935:        }else{
                   8936:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8937:           agemingood[cptcod]=age;
                   8938:         }else{ /* bad */
                   8939:           for (i=1; i<=nlstate;i++){
                   8940:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   8941:           } /* i */
                   8942:         } /* end bad */
                   8943:        }/* end else */
                   8944:        sum=0.;sumr=0.;
                   8945:        for (i=1; i<=nlstate;i++){
                   8946:         sum+=mobaverage[(int)age][i][cptcod];
                   8947:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  8948:        }
1.266     brouard  8949:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  8950:         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  8951:        } /* end bad */
                   8952:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   8953:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  8954:         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  8955:        } /* end bad */
                   8956:      }/* age */
1.266     brouard  8957: 
1.222     brouard  8958:                
                   8959:      for (age=bage; age<=fage; age++){
1.235     brouard  8960:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  8961:        sumnewp[cptcod]=0.;
                   8962:        sumnewm[cptcod]=0.;
                   8963:        for (i=1; i<=nlstate;i++){
                   8964:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   8965:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8966:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   8967:        }
                   8968:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   8969:      }
                   8970:      /* printf("\n"); */
                   8971:      /* } */
1.266     brouard  8972: 
1.222     brouard  8973:      /* brutal averaging */
1.266     brouard  8974:      /* for (i=1; i<=nlstate;i++){ */
                   8975:      /*   for (age=1; age<=bage; age++){ */
                   8976:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   8977:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   8978:      /*   }     */
                   8979:      /*   for (age=fage; age<=AGESUP; age++){ */
                   8980:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   8981:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   8982:      /*   } */
                   8983:      /* } /\* end i status *\/ */
                   8984:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   8985:      /*   for (age=1; age<=AGESUP; age++){ */
                   8986:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   8987:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   8988:      /*   } */
                   8989:      /* } */
1.222     brouard  8990:    }/* end cptcod */
1.266     brouard  8991:    free_vector(agemaxgoodr,1, ncovcombmax);
                   8992:    free_vector(agemaxgood,1, ncovcombmax);
                   8993:    free_vector(agemingood,1, ncovcombmax);
                   8994:    free_vector(agemingoodr,1, ncovcombmax);
                   8995:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  8996:    free_vector(sumnewm,1, ncovcombmax);
                   8997:    free_vector(sumnewp,1, ncovcombmax);
                   8998:    return 0;
                   8999:  }/* End movingaverage */
1.218     brouard  9000:  
1.126     brouard  9001: 
1.296     brouard  9002:  
1.126     brouard  9003: /************** Forecasting ******************/
1.296     brouard  9004: /* 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)*/
                   9005: 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){
                   9006:   /* dateintemean, mean date of interviews
                   9007:      dateprojd, year, month, day of starting projection 
                   9008:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  9009:      agemin, agemax range of age
                   9010:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   9011:   */
1.296     brouard  9012:   /* double anprojd, mprojd, jprojd; */
                   9013:   /* double anprojf, mprojf, jprojf; */
1.267     brouard  9014:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  9015:   double agec; /* generic age */
1.296     brouard  9016:   double agelim, ppij, yp,yp1,yp2;
1.126     brouard  9017:   double *popeffectif,*popcount;
                   9018:   double ***p3mat;
1.218     brouard  9019:   /* double ***mobaverage; */
1.126     brouard  9020:   char fileresf[FILENAMELENGTH];
                   9021: 
                   9022:   agelim=AGESUP;
1.211     brouard  9023:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9024:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9025:      We still use firstpass and lastpass as another selection.
                   9026:   */
1.214     brouard  9027:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9028:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  9029:  
1.201     brouard  9030:   strcpy(fileresf,"F_"); 
                   9031:   strcat(fileresf,fileresu);
1.126     brouard  9032:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   9033:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   9034:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   9035:   }
1.235     brouard  9036:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   9037:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  9038: 
1.225     brouard  9039:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  9040: 
                   9041: 
                   9042:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9043:   if (stepm<=12) stepsize=1;
                   9044:   if(estepm < stepm){
                   9045:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9046:   }
1.270     brouard  9047:   else{
                   9048:     hstepm=estepm;   
                   9049:   }
                   9050:   if(estepm > stepm){ /* Yes every two year */
                   9051:     stepsize=2;
                   9052:   }
1.296     brouard  9053:   hstepm=hstepm/stepm;
1.126     brouard  9054: 
1.296     brouard  9055:   
                   9056:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9057:   /*                              fractional in yp1 *\/ */
                   9058:   /* aintmean=yp; */
                   9059:   /* yp2=modf((yp1*12),&yp); */
                   9060:   /* mintmean=yp; */
                   9061:   /* yp1=modf((yp2*30.5),&yp); */
                   9062:   /* jintmean=yp; */
                   9063:   /* if(jintmean==0) jintmean=1; */
                   9064:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  9065: 
1.296     brouard  9066: 
                   9067:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   9068:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   9069:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.227     brouard  9070:   i1=pow(2,cptcoveff);
1.126     brouard  9071:   if (cptcovn < 1){i1=1;}
                   9072:   
1.296     brouard  9073:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  9074:   
                   9075:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  9076:   
1.126     brouard  9077: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  9078:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.332   ! brouard  9079:     for(k=1; k<=i1;k++){ /* We want to find the combination k corresponding to the values of the dummies given in this resut line (to be cleaned one day) */
1.253     brouard  9080:     if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  9081:       continue;
1.227     brouard  9082:     if(invalidvarcomb[k]){
                   9083:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   9084:       continue;
                   9085:     }
                   9086:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   9087:     for(j=1;j<=cptcoveff;j++) {
1.332   ! brouard  9088:       /* fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); */
        !          9089:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.227     brouard  9090:     }
1.235     brouard  9091:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  9092:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.235     brouard  9093:     }
1.227     brouard  9094:     fprintf(ficresf," yearproj age");
                   9095:     for(j=1; j<=nlstate+ndeath;j++){ 
                   9096:       for(i=1; i<=nlstate;i++)               
                   9097:        fprintf(ficresf," p%d%d",i,j);
                   9098:       fprintf(ficresf," wp.%d",j);
                   9099:     }
1.296     brouard  9100:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  9101:       fprintf(ficresf,"\n");
1.296     brouard  9102:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  9103:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   9104:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  9105:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   9106:        nhstepm = nhstepm/hstepm; 
                   9107:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9108:        oldm=oldms;savm=savms;
1.268     brouard  9109:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  9110:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  9111:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  9112:        for (h=0; h<=nhstepm; h++){
                   9113:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  9114:            break;
                   9115:          }
                   9116:        }
                   9117:        fprintf(ficresf,"\n");
                   9118:        for(j=1;j<=cptcoveff;j++) 
1.332   ! brouard  9119:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Tvaraff not correct *\/ */
        !          9120:          fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /* TnsdVar[Tvaraff]  correct */
1.296     brouard  9121:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  9122:        
                   9123:        for(j=1; j<=nlstate+ndeath;j++) {
                   9124:          ppij=0.;
                   9125:          for(i=1; i<=nlstate;i++) {
1.278     brouard  9126:            if (mobilav>=1)
                   9127:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   9128:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   9129:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   9130:            }
1.268     brouard  9131:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   9132:          } /* end i */
                   9133:          fprintf(ficresf," %.3f", ppij);
                   9134:        }/* end j */
1.227     brouard  9135:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9136:       } /* end agec */
1.266     brouard  9137:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   9138:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  9139:     } /* end yearp */
                   9140:   } /* end  k */
1.219     brouard  9141:        
1.126     brouard  9142:   fclose(ficresf);
1.215     brouard  9143:   printf("End of Computing forecasting \n");
                   9144:   fprintf(ficlog,"End of Computing forecasting\n");
                   9145: 
1.126     brouard  9146: }
                   9147: 
1.269     brouard  9148: /************** Back Forecasting ******************/
1.296     brouard  9149:  /* 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){ */
                   9150:  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){
                   9151:   /* back1, year, month, day of starting backprojection
1.267     brouard  9152:      agemin, agemax range of age
                   9153:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  9154:      anback2 year of end of backprojection (same day and month as back1).
                   9155:      prevacurrent and prev are prevalences.
1.267     brouard  9156:   */
                   9157:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   9158:   double agec; /* generic age */
1.302     brouard  9159:   double agelim, ppij, ppi, yp,yp1,yp2; /* ,jintmean,mintmean,aintmean;*/
1.267     brouard  9160:   double *popeffectif,*popcount;
                   9161:   double ***p3mat;
                   9162:   /* double ***mobaverage; */
                   9163:   char fileresfb[FILENAMELENGTH];
                   9164:  
1.268     brouard  9165:   agelim=AGEINF;
1.267     brouard  9166:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9167:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9168:      We still use firstpass and lastpass as another selection.
                   9169:   */
                   9170:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9171:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   9172: 
                   9173:   /*Do we need to compute prevalence again?*/
                   9174: 
                   9175:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   9176:   
                   9177:   strcpy(fileresfb,"FB_");
                   9178:   strcat(fileresfb,fileresu);
                   9179:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   9180:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   9181:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   9182:   }
                   9183:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   9184:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   9185:   
                   9186:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   9187:   
                   9188:    
                   9189:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9190:   if (stepm<=12) stepsize=1;
                   9191:   if(estepm < stepm){
                   9192:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9193:   }
1.270     brouard  9194:   else{
                   9195:     hstepm=estepm;   
                   9196:   }
                   9197:   if(estepm >= stepm){ /* Yes every two year */
                   9198:     stepsize=2;
                   9199:   }
1.267     brouard  9200:   
                   9201:   hstepm=hstepm/stepm;
1.296     brouard  9202:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9203:   /*                              fractional in yp1 *\/ */
                   9204:   /* aintmean=yp; */
                   9205:   /* yp2=modf((yp1*12),&yp); */
                   9206:   /* mintmean=yp; */
                   9207:   /* yp1=modf((yp2*30.5),&yp); */
                   9208:   /* jintmean=yp; */
                   9209:   /* if(jintmean==0) jintmean=1; */
                   9210:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  9211:   
                   9212:   i1=pow(2,cptcoveff);
                   9213:   if (cptcovn < 1){i1=1;}
                   9214:   
1.296     brouard  9215:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   9216:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  9217:   
                   9218:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   9219:   
                   9220:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9221:   for(k=1; k<=i1;k++){
                   9222:     if(i1 != 1 && TKresult[nres]!= k)
                   9223:       continue;
                   9224:     if(invalidvarcomb[k]){
                   9225:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   9226:       continue;
                   9227:     }
1.268     brouard  9228:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.267     brouard  9229:     for(j=1;j<=cptcoveff;j++) {
1.332   ! brouard  9230:       fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.267     brouard  9231:     }
                   9232:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   9233:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9234:     }
                   9235:     fprintf(ficresfb," yearbproj age");
                   9236:     for(j=1; j<=nlstate+ndeath;j++){
                   9237:       for(i=1; i<=nlstate;i++)
1.268     brouard  9238:        fprintf(ficresfb," b%d%d",i,j);
                   9239:       fprintf(ficresfb," b.%d",j);
1.267     brouard  9240:     }
1.296     brouard  9241:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  9242:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   9243:       fprintf(ficresfb,"\n");
1.296     brouard  9244:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  9245:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  9246:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   9247:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  9248:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  9249:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  9250:        nhstepm = nhstepm/hstepm;
                   9251:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9252:        oldm=oldms;savm=savms;
1.268     brouard  9253:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  9254:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  9255:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  9256:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   9257:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   9258:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  9259:        for (h=0; h<=nhstepm; h++){
1.268     brouard  9260:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   9261:            break;
                   9262:          }
                   9263:        }
                   9264:        fprintf(ficresfb,"\n");
                   9265:        for(j=1;j<=cptcoveff;j++)
1.332   ! brouard  9266:          fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.296     brouard  9267:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  9268:        for(i=1; i<=nlstate+ndeath;i++) {
                   9269:          ppij=0.;ppi=0.;
                   9270:          for(j=1; j<=nlstate;j++) {
                   9271:            /* if (mobilav==1) */
1.269     brouard  9272:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   9273:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   9274:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   9275:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  9276:              /* else { */
                   9277:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   9278:              /* } */
1.268     brouard  9279:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   9280:          } /* end j */
                   9281:          if(ppi <0.99){
                   9282:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   9283:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   9284:          }
                   9285:          fprintf(ficresfb," %.3f", ppij);
                   9286:        }/* end j */
1.267     brouard  9287:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9288:       } /* end agec */
                   9289:     } /* end yearp */
                   9290:   } /* end k */
1.217     brouard  9291:   
1.267     brouard  9292:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  9293:   
1.267     brouard  9294:   fclose(ficresfb);
                   9295:   printf("End of Computing Back forecasting \n");
                   9296:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  9297:        
1.267     brouard  9298: }
1.217     brouard  9299: 
1.269     brouard  9300: /* Variance of prevalence limit: varprlim */
                   9301:  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  9302:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  9303:  
                   9304:    char fileresvpl[FILENAMELENGTH];  
                   9305:    FILE *ficresvpl;
                   9306:    double **oldm, **savm;
                   9307:    double **varpl; /* Variances of prevalence limits by age */   
                   9308:    int i1, k, nres, j ;
                   9309:    
                   9310:     strcpy(fileresvpl,"VPL_");
                   9311:     strcat(fileresvpl,fileresu);
                   9312:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  9313:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  9314:       exit(0);
                   9315:     }
1.288     brouard  9316:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   9317:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  9318:     
                   9319:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   9320:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   9321:     
                   9322:     i1=pow(2,cptcoveff);
                   9323:     if (cptcovn < 1){i1=1;}
                   9324: 
                   9325:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.332   ! brouard  9326:       for(k=1; k<=i1;k++){ /* We find the combination equivalent to result line values of dummies */
1.269     brouard  9327:       if(i1 != 1 && TKresult[nres]!= k)
                   9328:        continue;
                   9329:       fprintf(ficresvpl,"\n#****** ");
                   9330:       printf("\n#****** ");
                   9331:       fprintf(ficlog,"\n#****** ");
                   9332:       for(j=1;j<=cptcoveff;j++) {
1.332   ! brouard  9333:        fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
        !          9334:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
        !          9335:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.269     brouard  9336:       }
                   9337:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332   ! brouard  9338:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
        !          9339:        fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
        !          9340:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
1.269     brouard  9341:       }        
                   9342:       fprintf(ficresvpl,"******\n");
                   9343:       printf("******\n");
                   9344:       fprintf(ficlog,"******\n");
                   9345:       
                   9346:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9347:       oldm=oldms;savm=savms;
                   9348:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   9349:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   9350:       /*}*/
                   9351:     }
                   9352:     
                   9353:     fclose(ficresvpl);
1.288     brouard  9354:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   9355:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  9356: 
                   9357:  }
                   9358: /* Variance of back prevalence: varbprlim */
                   9359:  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){
                   9360:       /*------- Variance of back (stable) prevalence------*/
                   9361: 
                   9362:    char fileresvbl[FILENAMELENGTH];  
                   9363:    FILE  *ficresvbl;
                   9364: 
                   9365:    double **oldm, **savm;
                   9366:    double **varbpl; /* Variances of back prevalence limits by age */   
                   9367:    int i1, k, nres, j ;
                   9368: 
                   9369:    strcpy(fileresvbl,"VBL_");
                   9370:    strcat(fileresvbl,fileresu);
                   9371:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   9372:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   9373:      exit(0);
                   9374:    }
                   9375:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   9376:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   9377:    
                   9378:    
                   9379:    i1=pow(2,cptcoveff);
                   9380:    if (cptcovn < 1){i1=1;}
                   9381:    
                   9382:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9383:      for(k=1; k<=i1;k++){
                   9384:        if(i1 != 1 && TKresult[nres]!= k)
                   9385:         continue;
                   9386:        fprintf(ficresvbl,"\n#****** ");
                   9387:        printf("\n#****** ");
                   9388:        fprintf(ficlog,"\n#****** ");
                   9389:        for(j=1;j<=cptcoveff;j++) {
1.332   ! brouard  9390:         fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
        !          9391:         fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
        !          9392:         printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.269     brouard  9393:        }
                   9394:        for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332   ! brouard  9395:         printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
        !          9396:         fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
        !          9397:         fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
1.269     brouard  9398:        }
                   9399:        fprintf(ficresvbl,"******\n");
                   9400:        printf("******\n");
                   9401:        fprintf(ficlog,"******\n");
                   9402:        
                   9403:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9404:        oldm=oldms;savm=savms;
                   9405:        
                   9406:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   9407:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   9408:        /*}*/
                   9409:      }
                   9410:    
                   9411:    fclose(ficresvbl);
                   9412:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   9413:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   9414: 
                   9415:  } /* End of varbprlim */
                   9416: 
1.126     brouard  9417: /************** Forecasting *****not tested NB*************/
1.227     brouard  9418: /* 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  9419:   
1.227     brouard  9420: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   9421: /*   int *popage; */
                   9422: /*   double calagedatem, agelim, kk1, kk2; */
                   9423: /*   double *popeffectif,*popcount; */
                   9424: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   9425: /*   /\* double ***mobaverage; *\/ */
                   9426: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  9427: 
1.227     brouard  9428: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9429: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9430: /*   agelim=AGESUP; */
                   9431: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  9432:   
1.227     brouard  9433: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  9434:   
                   9435:   
1.227     brouard  9436: /*   strcpy(filerespop,"POP_");  */
                   9437: /*   strcat(filerespop,fileresu); */
                   9438: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   9439: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   9440: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   9441: /*   } */
                   9442: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   9443: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  9444: 
1.227     brouard  9445: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  9446: 
1.227     brouard  9447: /*   /\* if (mobilav!=0) { *\/ */
                   9448: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   9449: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   9450: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   9451: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   9452: /*   /\*   } *\/ */
                   9453: /*   /\* } *\/ */
1.126     brouard  9454: 
1.227     brouard  9455: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   9456: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  9457:   
1.227     brouard  9458: /*   agelim=AGESUP; */
1.126     brouard  9459:   
1.227     brouard  9460: /*   hstepm=1; */
                   9461: /*   hstepm=hstepm/stepm;  */
1.218     brouard  9462:        
1.227     brouard  9463: /*   if (popforecast==1) { */
                   9464: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   9465: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   9466: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   9467: /*     }  */
                   9468: /*     popage=ivector(0,AGESUP); */
                   9469: /*     popeffectif=vector(0,AGESUP); */
                   9470: /*     popcount=vector(0,AGESUP); */
1.126     brouard  9471:     
1.227     brouard  9472: /*     i=1;    */
                   9473: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  9474:     
1.227     brouard  9475: /*     imx=i; */
                   9476: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   9477: /*   } */
1.218     brouard  9478:   
1.227     brouard  9479: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   9480: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   9481: /*       k=k+1; */
                   9482: /*       fprintf(ficrespop,"\n#******"); */
                   9483: /*       for(j=1;j<=cptcoveff;j++) { */
                   9484: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   9485: /*       } */
                   9486: /*       fprintf(ficrespop,"******\n"); */
                   9487: /*       fprintf(ficrespop,"# Age"); */
                   9488: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   9489: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  9490:       
1.227     brouard  9491: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   9492: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  9493:        
1.227     brouard  9494: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   9495: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   9496: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  9497:          
1.227     brouard  9498: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9499: /*       oldm=oldms;savm=savms; */
                   9500: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  9501:          
1.227     brouard  9502: /*       for (h=0; h<=nhstepm; h++){ */
                   9503: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   9504: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   9505: /*         }  */
                   9506: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   9507: /*           kk1=0.;kk2=0; */
                   9508: /*           for(i=1; i<=nlstate;i++) {               */
                   9509: /*             if (mobilav==1)  */
                   9510: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   9511: /*             else { */
                   9512: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   9513: /*             } */
                   9514: /*           } */
                   9515: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   9516: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   9517: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   9518: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   9519: /*           } */
                   9520: /*         } */
                   9521: /*         for(i=1; i<=nlstate;i++){ */
                   9522: /*           kk1=0.; */
                   9523: /*           for(j=1; j<=nlstate;j++){ */
                   9524: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   9525: /*           } */
                   9526: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   9527: /*         } */
1.218     brouard  9528:            
1.227     brouard  9529: /*         if (h==(int)(calagedatem+12*cpt)) */
                   9530: /*           for(j=1; j<=nlstate;j++)  */
                   9531: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   9532: /*       } */
                   9533: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9534: /*     } */
                   9535: /*       } */
1.218     brouard  9536:       
1.227     brouard  9537: /*       /\******\/ */
1.218     brouard  9538:       
1.227     brouard  9539: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   9540: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   9541: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   9542: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   9543: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  9544:          
1.227     brouard  9545: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9546: /*       oldm=oldms;savm=savms; */
                   9547: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   9548: /*       for (h=0; h<=nhstepm; h++){ */
                   9549: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   9550: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   9551: /*         }  */
                   9552: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   9553: /*           kk1=0.;kk2=0; */
                   9554: /*           for(i=1; i<=nlstate;i++) {               */
                   9555: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   9556: /*           } */
                   9557: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   9558: /*         } */
                   9559: /*       } */
                   9560: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9561: /*     } */
                   9562: /*       } */
                   9563: /*     }  */
                   9564: /*   } */
1.218     brouard  9565:   
1.227     brouard  9566: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  9567:   
1.227     brouard  9568: /*   if (popforecast==1) { */
                   9569: /*     free_ivector(popage,0,AGESUP); */
                   9570: /*     free_vector(popeffectif,0,AGESUP); */
                   9571: /*     free_vector(popcount,0,AGESUP); */
                   9572: /*   } */
                   9573: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9574: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9575: /*   fclose(ficrespop); */
                   9576: /* } /\* End of popforecast *\/ */
1.218     brouard  9577:  
1.126     brouard  9578: int fileappend(FILE *fichier, char *optionfich)
                   9579: {
                   9580:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   9581:     printf("Problem with file: %s\n", optionfich);
                   9582:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   9583:     return (0);
                   9584:   }
                   9585:   fflush(fichier);
                   9586:   return (1);
                   9587: }
                   9588: 
                   9589: 
                   9590: /**************** function prwizard **********************/
                   9591: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   9592: {
                   9593: 
                   9594:   /* Wizard to print covariance matrix template */
                   9595: 
1.164     brouard  9596:   char ca[32], cb[32];
                   9597:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  9598:   int numlinepar;
                   9599: 
                   9600:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9601:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9602:   for(i=1; i <=nlstate; i++){
                   9603:     jj=0;
                   9604:     for(j=1; j <=nlstate+ndeath; j++){
                   9605:       if(j==i) continue;
                   9606:       jj++;
                   9607:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   9608:       printf("%1d%1d",i,j);
                   9609:       fprintf(ficparo,"%1d%1d",i,j);
                   9610:       for(k=1; k<=ncovmodel;k++){
                   9611:        /*        printf(" %lf",param[i][j][k]); */
                   9612:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   9613:        printf(" 0.");
                   9614:        fprintf(ficparo," 0.");
                   9615:       }
                   9616:       printf("\n");
                   9617:       fprintf(ficparo,"\n");
                   9618:     }
                   9619:   }
                   9620:   printf("# Scales (for hessian or gradient estimation)\n");
                   9621:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   9622:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   9623:   for(i=1; i <=nlstate; i++){
                   9624:     jj=0;
                   9625:     for(j=1; j <=nlstate+ndeath; j++){
                   9626:       if(j==i) continue;
                   9627:       jj++;
                   9628:       fprintf(ficparo,"%1d%1d",i,j);
                   9629:       printf("%1d%1d",i,j);
                   9630:       fflush(stdout);
                   9631:       for(k=1; k<=ncovmodel;k++){
                   9632:        /*      printf(" %le",delti3[i][j][k]); */
                   9633:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   9634:        printf(" 0.");
                   9635:        fprintf(ficparo," 0.");
                   9636:       }
                   9637:       numlinepar++;
                   9638:       printf("\n");
                   9639:       fprintf(ficparo,"\n");
                   9640:     }
                   9641:   }
                   9642:   printf("# Covariance matrix\n");
                   9643: /* # 121 Var(a12)\n\ */
                   9644: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   9645: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   9646: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   9647: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   9648: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   9649: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   9650: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   9651:   fflush(stdout);
                   9652:   fprintf(ficparo,"# Covariance matrix\n");
                   9653:   /* # 121 Var(a12)\n\ */
                   9654:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   9655:   /* #   ...\n\ */
                   9656:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   9657:   
                   9658:   for(itimes=1;itimes<=2;itimes++){
                   9659:     jj=0;
                   9660:     for(i=1; i <=nlstate; i++){
                   9661:       for(j=1; j <=nlstate+ndeath; j++){
                   9662:        if(j==i) continue;
                   9663:        for(k=1; k<=ncovmodel;k++){
                   9664:          jj++;
                   9665:          ca[0]= k+'a'-1;ca[1]='\0';
                   9666:          if(itimes==1){
                   9667:            printf("#%1d%1d%d",i,j,k);
                   9668:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   9669:          }else{
                   9670:            printf("%1d%1d%d",i,j,k);
                   9671:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   9672:            /*  printf(" %.5le",matcov[i][j]); */
                   9673:          }
                   9674:          ll=0;
                   9675:          for(li=1;li <=nlstate; li++){
                   9676:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   9677:              if(lj==li) continue;
                   9678:              for(lk=1;lk<=ncovmodel;lk++){
                   9679:                ll++;
                   9680:                if(ll<=jj){
                   9681:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   9682:                  if(ll<jj){
                   9683:                    if(itimes==1){
                   9684:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9685:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9686:                    }else{
                   9687:                      printf(" 0.");
                   9688:                      fprintf(ficparo," 0.");
                   9689:                    }
                   9690:                  }else{
                   9691:                    if(itimes==1){
                   9692:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   9693:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   9694:                    }else{
                   9695:                      printf(" 0.");
                   9696:                      fprintf(ficparo," 0.");
                   9697:                    }
                   9698:                  }
                   9699:                }
                   9700:              } /* end lk */
                   9701:            } /* end lj */
                   9702:          } /* end li */
                   9703:          printf("\n");
                   9704:          fprintf(ficparo,"\n");
                   9705:          numlinepar++;
                   9706:        } /* end k*/
                   9707:       } /*end j */
                   9708:     } /* end i */
                   9709:   } /* end itimes */
                   9710: 
                   9711: } /* end of prwizard */
                   9712: /******************* Gompertz Likelihood ******************************/
                   9713: double gompertz(double x[])
                   9714: { 
1.302     brouard  9715:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
1.126     brouard  9716:   int i,n=0; /* n is the size of the sample */
                   9717: 
1.220     brouard  9718:   for (i=1;i<=imx ; i++) {
1.126     brouard  9719:     sump=sump+weight[i];
                   9720:     /*    sump=sump+1;*/
                   9721:     num=num+1;
                   9722:   }
1.302     brouard  9723:   L=0.0;
                   9724:   /* agegomp=AGEGOMP; */
1.126     brouard  9725:   /* for (i=0; i<=imx; i++) 
                   9726:      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]);*/
                   9727: 
1.302     brouard  9728:   for (i=1;i<=imx ; i++) {
                   9729:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   9730:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   9731:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   9732:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   9733:      * +
                   9734:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   9735:      */
                   9736:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   9737:        if (cens[i] == 1){
                   9738:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   9739:        } else if (cens[i] == 0){
1.126     brouard  9740:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
1.302     brouard  9741:          +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   9742:       } else
                   9743:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
1.126     brouard  9744:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
1.302     brouard  9745:        L=L+A*weight[i];
1.126     brouard  9746:        /*      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  9747:      }
                   9748:   }
1.126     brouard  9749: 
1.302     brouard  9750:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
1.126     brouard  9751:  
                   9752:   return -2*L*num/sump;
                   9753: }
                   9754: 
1.136     brouard  9755: #ifdef GSL
                   9756: /******************* Gompertz_f Likelihood ******************************/
                   9757: double gompertz_f(const gsl_vector *v, void *params)
                   9758: { 
1.302     brouard  9759:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
1.136     brouard  9760:   double *x= (double *) v->data;
                   9761:   int i,n=0; /* n is the size of the sample */
                   9762: 
                   9763:   for (i=0;i<=imx-1 ; i++) {
                   9764:     sump=sump+weight[i];
                   9765:     /*    sump=sump+1;*/
                   9766:     num=num+1;
                   9767:   }
                   9768:  
                   9769:  
                   9770:   /* for (i=0; i<=imx; i++) 
                   9771:      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]);*/
                   9772:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   9773:   for (i=1;i<=imx ; i++)
                   9774:     {
                   9775:       if (cens[i] == 1 && wav[i]>1)
                   9776:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   9777:       
                   9778:       if (cens[i] == 0 && wav[i]>1)
                   9779:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   9780:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   9781:       
                   9782:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   9783:       if (wav[i] > 1 ) { /* ??? */
                   9784:        LL=LL+A*weight[i];
                   9785:        /*      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]);*/
                   9786:       }
                   9787:     }
                   9788: 
                   9789:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   9790:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   9791:  
                   9792:   return -2*LL*num/sump;
                   9793: }
                   9794: #endif
                   9795: 
1.126     brouard  9796: /******************* Printing html file ***********/
1.201     brouard  9797: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  9798:                  int lastpass, int stepm, int weightopt, char model[],\
                   9799:                  int imx,  double p[],double **matcov,double agemortsup){
                   9800:   int i,k;
                   9801: 
                   9802:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   9803:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   9804:   for (i=1;i<=2;i++) 
                   9805:     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  9806:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  9807:   fprintf(fichtm,"</ul>");
                   9808: 
                   9809: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   9810: 
                   9811:  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>");
                   9812: 
                   9813:  for (k=agegomp;k<(agemortsup-2);k++) 
                   9814:    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]);
                   9815: 
                   9816:  
                   9817:   fflush(fichtm);
                   9818: }
                   9819: 
                   9820: /******************* Gnuplot file **************/
1.201     brouard  9821: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  9822: 
                   9823:   char dirfileres[132],optfileres[132];
1.164     brouard  9824: 
1.126     brouard  9825:   int ng;
                   9826: 
                   9827: 
                   9828:   /*#ifdef windows */
                   9829:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   9830:     /*#endif */
                   9831: 
                   9832: 
                   9833:   strcpy(dirfileres,optionfilefiname);
                   9834:   strcpy(optfileres,"vpl");
1.199     brouard  9835:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  9836:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  9837:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  9838:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  9839:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   9840: 
                   9841: } 
                   9842: 
1.136     brouard  9843: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   9844: {
1.126     brouard  9845: 
1.136     brouard  9846:   /*-------- data file ----------*/
                   9847:   FILE *fic;
                   9848:   char dummy[]="                         ";
1.240     brouard  9849:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  9850:   int lstra;
1.136     brouard  9851:   int linei, month, year,iout;
1.302     brouard  9852:   int noffset=0; /* This is the offset if BOM data file */
1.136     brouard  9853:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  9854:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  9855:   char *stratrunc;
1.223     brouard  9856: 
1.240     brouard  9857:   DummyV=ivector(1,NCOVMAX); /* 1 to 3 */
                   9858:   FixedV=ivector(1,NCOVMAX); /* 1 to 3 */
1.328     brouard  9859:   for(v=1;v<NCOVMAX;v++){
                   9860:     DummyV[v]=0;
                   9861:     FixedV[v]=0;
                   9862:   }
1.126     brouard  9863: 
1.240     brouard  9864:   for(v=1; v <=ncovcol;v++){
                   9865:     DummyV[v]=0;
                   9866:     FixedV[v]=0;
                   9867:   }
                   9868:   for(v=ncovcol+1; v <=ncovcol+nqv;v++){
                   9869:     DummyV[v]=1;
                   9870:     FixedV[v]=0;
                   9871:   }
                   9872:   for(v=ncovcol+nqv+1; v <=ncovcol+nqv+ntv;v++){
                   9873:     DummyV[v]=0;
                   9874:     FixedV[v]=1;
                   9875:   }
                   9876:   for(v=ncovcol+nqv+ntv+1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   9877:     DummyV[v]=1;
                   9878:     FixedV[v]=1;
                   9879:   }
                   9880:   for(v=1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   9881:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   9882:     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]);
                   9883:   }
1.126     brouard  9884: 
1.136     brouard  9885:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  9886:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   9887:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  9888:   }
1.126     brouard  9889: 
1.302     brouard  9890:     /* Is it a BOM UTF-8 Windows file? */
                   9891:   /* First data line */
                   9892:   linei=0;
                   9893:   while(fgets(line, MAXLINE, fic)) {
                   9894:     noffset=0;
                   9895:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   9896:     {
                   9897:       noffset=noffset+3;
                   9898:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   9899:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   9900:       fflush(ficlog); return 1;
                   9901:     }
                   9902:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   9903:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   9904:     {
                   9905:       noffset=noffset+2;
1.304     brouard  9906:       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);
                   9907:       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  9908:       fflush(ficlog); return 1;
                   9909:     }
                   9910:     else if( line[0] == 0 && line[1] == 0)
                   9911:     {
                   9912:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   9913:        noffset=noffset+4;
1.304     brouard  9914:        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);
                   9915:        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  9916:        fflush(ficlog); return 1;
                   9917:       }
                   9918:     } else{
                   9919:       ;/*printf(" Not a BOM file\n");*/
                   9920:     }
                   9921:         /* If line starts with a # it is a comment */
                   9922:     if (line[noffset] == '#') {
                   9923:       linei=linei+1;
                   9924:       break;
                   9925:     }else{
                   9926:       break;
                   9927:     }
                   9928:   }
                   9929:   fclose(fic);
                   9930:   if((fic=fopen(datafile,"r"))==NULL)    {
                   9931:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   9932:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   9933:   }
                   9934:   /* Not a Bom file */
                   9935:   
1.136     brouard  9936:   i=1;
                   9937:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   9938:     linei=linei+1;
                   9939:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   9940:       if(line[j] == '\t')
                   9941:        line[j] = ' ';
                   9942:     }
                   9943:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   9944:       ;
                   9945:     };
                   9946:     line[j+1]=0;  /* Trims blanks at end of line */
                   9947:     if(line[0]=='#'){
                   9948:       fprintf(ficlog,"Comment line\n%s\n",line);
                   9949:       printf("Comment line\n%s\n",line);
                   9950:       continue;
                   9951:     }
                   9952:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  9953:     strcpy(line, linetmp);
1.223     brouard  9954:     
                   9955:     /* Loops on waves */
                   9956:     for (j=maxwav;j>=1;j--){
                   9957:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  9958:        cutv(stra, strb, line, ' '); 
                   9959:        if(strb[0]=='.') { /* Missing value */
                   9960:          lval=-1;
                   9961:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
                   9962:          cotvar[j][ntv+iv][i]=-1; /* For performance reasons */
                   9963:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   9964:            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);
                   9965:            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);
                   9966:            return 1;
                   9967:          }
                   9968:        }else{
                   9969:          errno=0;
                   9970:          /* what_kind_of_number(strb); */
                   9971:          dval=strtod(strb,&endptr); 
                   9972:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   9973:          /* if(strb != endptr && *endptr == '\0') */
                   9974:          /*    dval=dlval; */
                   9975:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   9976:          if( strb[0]=='\0' || (*endptr != '\0')){
                   9977:            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);
                   9978:            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);
                   9979:            return 1;
                   9980:          }
                   9981:          cotqvar[j][iv][i]=dval; 
                   9982:          cotvar[j][ntv+iv][i]=dval; 
                   9983:        }
                   9984:        strcpy(line,stra);
1.223     brouard  9985:       }/* end loop ntqv */
1.225     brouard  9986:       
1.223     brouard  9987:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  9988:        cutv(stra, strb, line, ' '); 
                   9989:        if(strb[0]=='.') { /* Missing value */
                   9990:          lval=-1;
                   9991:        }else{
                   9992:          errno=0;
                   9993:          lval=strtol(strb,&endptr,10); 
                   9994:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   9995:          if( strb[0]=='\0' || (*endptr != '\0')){
                   9996:            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);
                   9997:            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);
                   9998:            return 1;
                   9999:          }
                   10000:        }
                   10001:        if(lval <-1 || lval >1){
                   10002:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10003:  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  10004:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10005:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10006:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10007:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10008:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10009:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10010:  Exiting.\n",lval,linei, i,line,iv,j);
1.238     brouard  10011:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10012:  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  10013:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10014:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10015:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10016:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10017:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10018:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10019:  Exiting.\n",lval,linei, i,line,iv,j);fflush(ficlog);
1.238     brouard  10020:          return 1;
                   10021:        }
                   10022:        cotvar[j][iv][i]=(double)(lval);
                   10023:        strcpy(line,stra);
1.223     brouard  10024:       }/* end loop ntv */
1.225     brouard  10025:       
1.223     brouard  10026:       /* Statuses  at wave */
1.137     brouard  10027:       cutv(stra, strb, line, ' '); 
1.223     brouard  10028:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  10029:        lval=-1;
1.136     brouard  10030:       }else{
1.238     brouard  10031:        errno=0;
                   10032:        lval=strtol(strb,&endptr,10); 
                   10033:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   10034:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10035:          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);
                   10036:          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);
                   10037:          return 1;
                   10038:        }
1.136     brouard  10039:       }
1.225     brouard  10040:       
1.136     brouard  10041:       s[j][i]=lval;
1.225     brouard  10042:       
1.223     brouard  10043:       /* Date of Interview */
1.136     brouard  10044:       strcpy(line,stra);
                   10045:       cutv(stra, strb,line,' ');
1.169     brouard  10046:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10047:       }
1.169     brouard  10048:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  10049:        month=99;
                   10050:        year=9999;
1.136     brouard  10051:       }else{
1.225     brouard  10052:        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);
                   10053:        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);
                   10054:        return 1;
1.136     brouard  10055:       }
                   10056:       anint[j][i]= (double) year; 
1.302     brouard  10057:       mint[j][i]= (double)month;
                   10058:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   10059:       /*       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]); */
                   10060:       /*       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]); */
                   10061:       /* } */
1.136     brouard  10062:       strcpy(line,stra);
1.223     brouard  10063:     } /* End loop on waves */
1.225     brouard  10064:     
1.223     brouard  10065:     /* Date of death */
1.136     brouard  10066:     cutv(stra, strb,line,' '); 
1.169     brouard  10067:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10068:     }
1.169     brouard  10069:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  10070:       month=99;
                   10071:       year=9999;
                   10072:     }else{
1.141     brouard  10073:       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  10074:       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);
                   10075:       return 1;
1.136     brouard  10076:     }
                   10077:     andc[i]=(double) year; 
                   10078:     moisdc[i]=(double) month; 
                   10079:     strcpy(line,stra);
                   10080:     
1.223     brouard  10081:     /* Date of birth */
1.136     brouard  10082:     cutv(stra, strb,line,' '); 
1.169     brouard  10083:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10084:     }
1.169     brouard  10085:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  10086:       month=99;
                   10087:       year=9999;
                   10088:     }else{
1.141     brouard  10089:       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);
                   10090:       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  10091:       return 1;
1.136     brouard  10092:     }
                   10093:     if (year==9999) {
1.141     brouard  10094:       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);
                   10095:       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  10096:       return 1;
                   10097:       
1.136     brouard  10098:     }
                   10099:     annais[i]=(double)(year);
1.302     brouard  10100:     moisnais[i]=(double)(month);
                   10101:     for (j=1;j<=maxwav;j++){
                   10102:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   10103:        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]);
                   10104:        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]);
                   10105:       }
                   10106:     }
                   10107: 
1.136     brouard  10108:     strcpy(line,stra);
1.225     brouard  10109:     
1.223     brouard  10110:     /* Sample weight */
1.136     brouard  10111:     cutv(stra, strb,line,' '); 
                   10112:     errno=0;
                   10113:     dval=strtod(strb,&endptr); 
                   10114:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  10115:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   10116:       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  10117:       fflush(ficlog);
                   10118:       return 1;
                   10119:     }
                   10120:     weight[i]=dval; 
                   10121:     strcpy(line,stra);
1.225     brouard  10122:     
1.223     brouard  10123:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   10124:       cutv(stra, strb, line, ' '); 
                   10125:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  10126:        lval=-1;
1.311     brouard  10127:        coqvar[iv][i]=NAN; 
                   10128:        covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  10129:       }else{
1.225     brouard  10130:        errno=0;
                   10131:        /* what_kind_of_number(strb); */
                   10132:        dval=strtod(strb,&endptr);
                   10133:        /* if(strb != endptr && *endptr == '\0') */
                   10134:        /*   dval=dlval; */
                   10135:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10136:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10137:          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);
                   10138:          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);
                   10139:          return 1;
                   10140:        }
                   10141:        coqvar[iv][i]=dval; 
1.226     brouard  10142:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  10143:       }
                   10144:       strcpy(line,stra);
                   10145:     }/* end loop nqv */
1.136     brouard  10146:     
1.223     brouard  10147:     /* Covariate values */
1.136     brouard  10148:     for (j=ncovcol;j>=1;j--){
                   10149:       cutv(stra, strb,line,' '); 
1.223     brouard  10150:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  10151:        lval=-1;
1.136     brouard  10152:       }else{
1.225     brouard  10153:        errno=0;
                   10154:        lval=strtol(strb,&endptr,10); 
                   10155:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10156:          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);
                   10157:          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);
                   10158:          return 1;
                   10159:        }
1.136     brouard  10160:       }
                   10161:       if(lval <-1 || lval >1){
1.225     brouard  10162:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  10163:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   10164:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  10165:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10166:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10167:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  10168:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  10169:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  10170:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  10171:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  10172:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   10173:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  10174:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10175:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10176:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  10177:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  10178:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  10179:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  10180:        return 1;
1.136     brouard  10181:       }
                   10182:       covar[j][i]=(double)(lval);
                   10183:       strcpy(line,stra);
                   10184:     }  
                   10185:     lstra=strlen(stra);
1.225     brouard  10186:     
1.136     brouard  10187:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   10188:       stratrunc = &(stra[lstra-9]);
                   10189:       num[i]=atol(stratrunc);
                   10190:     }
                   10191:     else
                   10192:       num[i]=atol(stra);
                   10193:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   10194:       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;}*/
                   10195:     
                   10196:     i=i+1;
                   10197:   } /* End loop reading  data */
1.225     brouard  10198:   
1.136     brouard  10199:   *imax=i-1; /* Number of individuals */
                   10200:   fclose(fic);
1.225     brouard  10201:   
1.136     brouard  10202:   return (0);
1.164     brouard  10203:   /* endread: */
1.225     brouard  10204:   printf("Exiting readdata: ");
                   10205:   fclose(fic);
                   10206:   return (1);
1.223     brouard  10207: }
1.126     brouard  10208: 
1.234     brouard  10209: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  10210:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  10211:   while (*p2 == ' ')
1.234     brouard  10212:     p2++; 
                   10213:   /* while ((*p1++ = *p2++) !=0) */
                   10214:   /*   ; */
                   10215:   /* do */
                   10216:   /*   while (*p2 == ' ') */
                   10217:   /*     p2++; */
                   10218:   /* while (*p1++ == *p2++); */
                   10219:   *stri=p2; 
1.145     brouard  10220: }
                   10221: 
1.330     brouard  10222: int decoderesult( char resultline[], int nres)
1.230     brouard  10223: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   10224: {
1.235     brouard  10225:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  10226:   char resultsav[MAXLINE];
1.330     brouard  10227:   /* int resultmodel[MAXLINE]; */
1.234     brouard  10228:   int modelresult[MAXLINE];
1.230     brouard  10229:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   10230: 
1.234     brouard  10231:   removefirstspace(&resultline);
1.332   ! brouard  10232:   printf("decoderesult:%s\n",resultline);
1.230     brouard  10233: 
1.332   ! brouard  10234:   strcpy(resultsav,resultline);
        !          10235:   printf("Decoderesult resultsav=\"%s\" resultline=\"%s\"\n", resultsav, resultline);
1.230     brouard  10236:   if (strlen(resultsav) >1){
                   10237:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' */
                   10238:   }
1.253     brouard  10239:   if(j == 0){ /* Resultline but no = */
                   10240:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   10241:     return (0);
                   10242:   }
1.234     brouard  10243:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
1.332   ! brouard  10244:     printf("ERROR: the number of variables in the resultline which is %d, differs from the number %d of variables used in the model line, %s.\n",j, cptcovs, model);
        !          10245:     fprintf(ficlog,"ERROR: the number of variables in the resultline which is %d, differs from the number %d of variables used in the model line, %s.\n",j, cptcovs, model);
        !          10246:     /* return 1;*/
1.234     brouard  10247:   }
                   10248:   for(k=1; k<=j;k++){ /* Loop on any covariate of the result line */
                   10249:     if(nbocc(resultsav,'=') >1){
1.318     brouard  10250:       cutl(stra,strb,resultsav,' '); /* keeps in strb after the first ' ' (stra is the rest of the resultline to be analyzed in the next loop *//*     resultsav= "V4=1 V5=25.1 V3=0" stra= "V5=25.1 V3=0" strb= "V4=1" */
1.332   ! brouard  10251:       /* If resultsav= "V4= 1 V5=25.1 V3=0" with a blank then strb="V4=" and stra="1 V5=25.1 V3=0" */
1.318     brouard  10252:       cutl(strc,strd,strb,'=');  /* strb:"V4=1" strc="1" strd="V4" */
1.332   ! brouard  10253:       /* If a blank, then strc="V4=" and strd='\0' */
        !          10254:       if(strc[0]=='\0'){
        !          10255:       printf("Error in resultline, probably a blank after the \"%s\", \"result:%s\", stra=\"%s\" resultsav=\"%s\"\n",strb,resultline, stra, resultsav);
        !          10256:        fprintf(ficlog,"Error in resultline, probably a blank after the \"V%s=\", resultline=%s\n",strb,resultline);
        !          10257:        return 1;
        !          10258:       }
1.234     brouard  10259:     }else
                   10260:       cutl(strc,strd,resultsav,'=');
1.318     brouard  10261:     Tvalsel[k]=atof(strc); /* 1 */ /* Tvalsel of k is the float value of the kth covariate appearing in this result line */
1.234     brouard  10262:     
1.230     brouard  10263:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
1.318     brouard  10264:     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  10265:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   10266:     /* cptcovsel++;     */
                   10267:     if (nbocc(stra,'=') >0)
                   10268:       strcpy(resultsav,stra); /* and analyzes it */
                   10269:   }
1.235     brouard  10270:   /* Checking for missing or useless values in comparison of current model needs */
1.332   ! brouard  10271:   /* Feeds resultmodel[nres][k1]=k2 for k1th product covariate with age in the model equation fed by the index k2 of the resutline*/
1.318     brouard  10272:   for(k1=1; k1<= cptcovt ;k1++){ /* Loop on model. model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.332   ! brouard  10273:     if(Typevar[k1]==0){ /* Single covariate in model */
        !          10274:       /* 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.234     brouard  10275:       match=0;
1.318     brouard  10276:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10277:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.236     brouard  10278:          modelresult[k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.318     brouard  10279:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
1.234     brouard  10280:          break;
                   10281:        }
                   10282:       }
                   10283:       if(match == 0){
1.332   ! brouard  10284:        printf("Error in result line (Dummy single): V%d is missing in result: %s according to model=%s. Tvar[k1=%d]=%d is different from Tvarsel[k2=%d]=%d.\n",Tvar[k1], resultline, model,k1, Tvar[k1], k2, Tvarsel[k2]);
        !          10285:        fprintf(ficlog,"Error in result line (Dummy single): V%d is missing in result: %s according to model=%s\n",Tvar[k1], resultline, model);
1.310     brouard  10286:        return 1;
1.234     brouard  10287:       }
1.332   ! brouard  10288:     }else if(Typevar[k1]==1){ /* Product with age We want to get the position k2 in the resultline of the product k1 in the model line*/
        !          10289:       /* We feed resultmodel[k1]=k2; */
        !          10290:       match=0;
        !          10291:       for(k2=1; k2 <=j;k2++){/* Loop on resultline.  jth occurence of = signs in the result line. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
        !          10292:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
        !          10293:          modelresult[k2]=k1;/* we found a Vn=1 corrresponding to Vn*age in the model modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
        !          10294:          resultmodel[nres][k1]=k2; /* Added here */
        !          10295:          printf("Decoderesult first modelresult[k2=%d]=%d (k1) V%d*AGE\n",k2,k1,Tvar[k1]);
        !          10296:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
        !          10297:          break;
        !          10298:        }
        !          10299:       }
        !          10300:       if(match == 0){
        !          10301:        printf("Error in result line (Product with age): V%d is missing in result: %s according to model=%s (Tvarsel[k2=%d]=%d)\n",Tvar[k1], resultline, model, k2, Tvarsel[k2]);
        !          10302:        fprintf(ficlog,"Error in result line (Product with age): V%d is missing in result: %s according to model=%s\n",Tvar[k1], resultline, model, k2, Tvarsel[k2]);
        !          10303:       return 1;
        !          10304:       }
        !          10305:     }else if(Typevar[k1]==2){ /* Product No age We want to get the position in the resultline of the product in the model line*/
        !          10306:       /* resultmodel[nres][of such a Vn * Vm product k1] is not unique, so can't exist, we feed Tvard[k1][1] and [2] */ 
        !          10307:       match=0;
        !          10308:       printf("Decoderesult very first Product Tvardk[k1=%d][1]=%d Tvardk[k1=%d][2]=%d V%d * V%d\n",k1,Tvardk[k1][1],k1,Tvardk[k1][2],Tvardk[k1][1],Tvardk[k1][2]);
        !          10309:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
        !          10310:        if(Tvardk[k1][1]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
        !          10311:          /* modelresult[k2]=k1; */
        !          10312:          printf("Decoderesult first Product modelresult[k2=%d]=%d (k1) V%d * \n",k2,k1,Tvarsel[k2]);
        !          10313:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
        !          10314:        }
        !          10315:       }
        !          10316:       if(match == 0){
        !          10317:        printf("Error in result line (Product without age first variable): V%d is missing in result: %s according to model=%s\n",Tvardk[k1][1], resultline, model);
        !          10318:        fprintf(ficlog,"Error in result line (Product without age first variable): V%d is missing in result: %s according to model=%s\n",k1,Tvardk[k1][1], resultline, model);
        !          10319:        return 1;
        !          10320:       }
        !          10321:       match=0;
        !          10322:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
        !          10323:        if(Tvardk[k1][2]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
        !          10324:          /* modelresult[k2]=k1;*/
        !          10325:          printf("Decoderesult second Product modelresult[k2=%d]=%d (k1) * V%d \n ",k2,k1,Tvarsel[k2]);
        !          10326:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
        !          10327:          break;
        !          10328:        }
        !          10329:       }
        !          10330:       if(match == 0){
        !          10331:        printf("Error in result line (Product without age second variable): V%d is missing in result: %s according to model=%s\n",Tvardk[k1][2], resultline, model);
        !          10332:        fprintf(ficlog,"Error in result line (Product without age second variable): V%d is missing in result : %s according to model=%s\n",k1,Tvardk[k1][2], resultline, model);
        !          10333:        return 1;
        !          10334:       }
        !          10335:     }/* End of testing */
        !          10336:   }/* End loop cptcovt
1.235     brouard  10337:   /* Checking for missing or useless values in comparison of current model needs */
1.332   ! brouard  10338:   /* Feeds resultmodel[nres][k1]=k2 for single covariate (k1) in the model equation */
1.318     brouard  10339:   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  10340:     match=0;
1.318     brouard  10341:     for(k1=1; k1<= cptcovt ;k1++){ /* loop on model: model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.332   ! brouard  10342:       if(Typevar[k1]==0){ /* Single only */
1.237     brouard  10343:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4   */
1.330     brouard  10344:          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  10345:          ++match;
                   10346:        }
                   10347:       }
                   10348:     }
                   10349:     if(match == 0){
1.332   ! brouard  10350:       printf("Error in result line: variable V%d is missing in model; result: %s, model=%s\n",Tvarsel[k2], resultline, model);
        !          10351:       fprintf(ficlog,"Error in result line: variable V%d is missing in model; result: %s, model=%s\n",Tvarsel[k2], resultline, model);
1.310     brouard  10352:       return 1;
1.234     brouard  10353:     }else if(match > 1){
                   10354:       printf("Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
1.310     brouard  10355:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
                   10356:       return 1;
1.234     brouard  10357:     }
                   10358:   }
1.235     brouard  10359:       
1.234     brouard  10360:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  10361:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.330     brouard  10362:   /* nres=1st result line: V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   10363:   /* 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*/
                   10364:   /* nres=2nd result line: V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.235     brouard  10365:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   10366:   /*    1 0 0 0 */
                   10367:   /*    2 1 0 0 */
                   10368:   /*    3 0 1 0 */ 
1.330     brouard  10369:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 (nres=2)*/
1.235     brouard  10370:   /*    5 0 0 1 */
1.330     brouard  10371:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 (nres=1)*/
1.235     brouard  10372:   /*    7 0 1 1 */
                   10373:   /*    8 1 1 1 */
1.237     brouard  10374:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   10375:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   10376:   /* V5*age V5 known which value for nres?  */
                   10377:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.330     brouard  10378:   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  10379:     /* k counting number of combination of single dummies in the equation model */
                   10380:     /* k4 counting single dummies in the equation model */
                   10381:     /* k4q counting single quantitatives in the equation model */
                   10382:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Dummy and Single */
                   10383:        /* k4+1= position in the resultline V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) */
1.332   ! brouard  10384:       /* modelresult[k3]=k1: k3th position in the result line corresponds to the k1 position in the model line (doesn't work with products)*/
1.330     brouard  10385:       /* Value in the (current nres) resultline of the variable at the k1th position in the model equation resultmodel[nres][k1]= k3 */
1.332   ! brouard  10386:       /* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline                        */
        !          10387:       /*      k3 is the position in the nres result line of the k1th variable of the model equation                                  */
        !          10388:       /* Tvarsel[k3]: Name of the variable at the k3th position in the result line.                                                  */
        !          10389:       /* Tvalsel[k3]: Value of the variable at the k3th position in the result line.                                                 */
        !          10390:       /* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline                   */
        !          10391:       /* Tvresult[nres][result_position]= id of the dummy variable at the result_position in the nres resultline                     */
        !          10392:       /* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line                                        */
1.330     brouard  10393:       /* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line                                                      */
1.332   ! brouard  10394:       k3= resultmodel[nres][k1]; /* From position k1 in model get position k3 in result line */
        !          10395:       /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
        !          10396:       k2=(int)Tvarsel[k3]; /* from position k3 in resultline get name k2: nres=1 k1=2=>k3=1 Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 (V4); k1=3=>k3=2 Tvarsel[2]=3 (V3)*/
1.330     brouard  10397:       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.332   ! brouard  10398:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Stores the value into the name of the variable. */
        !          10399:       /* Tinvresult[nres][4]=1 */
1.330     brouard  10400:       Tresult[nres][k4+1]=Tvalsel[k3];/* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) */
1.237     brouard  10401:       Tvresult[nres][k4+1]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   10402:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.332   ! brouard  10403:       precov[nres][k1]=Tvalsel[k3];
        !          10404:       printf("Decoderesult Dummy k=%d, k1=%d precov[nres=%d][k1=%d]=%.f V(k2=V%d)= Tvalsel[%d]=%d, 2**(%d)\n",k, k1, nres, k1,precov[nres][k1], k2, k3, (int)Tvalsel[k3], k4);
1.235     brouard  10405:       k4++;;
1.331     brouard  10406:     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Quantitative and single */
1.330     brouard  10407:       /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 */
1.332   ! brouard  10408:       /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline                                 */
1.330     brouard  10409:       /* Tqinvresult[nres][Name of a quantitative variable]= value of the variable in the result line                                                      */
1.332   ! brouard  10410:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 5 =k3q */
        !          10411:       k2q=(int)Tvarsel[k3q]; /*  Name of variable at k3q th position in the resultline */
        !          10412:       /* Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.237     brouard  10413:       Tqresult[nres][k4q+1]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   10414:       Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
                   10415:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.330     brouard  10416:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.332   ! brouard  10417:       precov[nres][k1]=Tvalsel[k3q];
        !          10418:       printf("Decoderesult Quantitative nres=%d,precov[nres=%d][k1=%d]=%.f V(k2q=V%d)= Tvalsel[%d]=%d, Tvarsel[%d]=%f\n",nres, nres, k1,precov[nres][k1], k2q, k3q, Tvarsel[k3q], k3q, Tvalsel[k3q]);
1.235     brouard  10419:       k4q++;;
1.331     brouard  10420:     }else if( Dummy[k1]==2 ){ /* For dummy with age product */
                   10421:       /* Tvar[k1]; */ /* Age variable */
1.332   ! brouard  10422:       /* Wrong we want the value of variable name Tvar[k1] */
        !          10423:       
        !          10424:       k3= resultmodel[nres][k1]; /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
1.331     brouard  10425:       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)*/
                   10426:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.332   ! brouard  10427:       precov[nres][k1]=Tvalsel[k3];
        !          10428:       printf("Decoderesult Dummy with age k=%d, k1=%d precov[nres=%d][k1=%d]=%.f Tvar[%d]=V%d k2=Tvarsel[%d]=%d Tvalsel[%d]=%d\n",k, k1, nres, k1,precov[nres][k1], k1, Tvar[k1], k3,(int)Tvarsel[k3], k3, (int)Tvalsel[k3]);
1.331     brouard  10429:     }else if( Dummy[k1]==3 ){ /* For quant with age product */
1.332   ! brouard  10430:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 25.1=k3q */
1.331     brouard  10431:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
                   10432:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.332   ! brouard  10433:       precov[nres][k1]=Tvalsel[k3q];
        !          10434:       printf("Decoderesult Quantitative with age nres=%d, k1=%d, precov[nres=%d][k1=%d]=%.f Tvar[%d]=V%d V(k2q=%d)= Tvarsel[%d]=%d, Tvalsel[%d]=%f\n",nres, k1, nres, k1,precov[nres][k1], k1,  Tvar[k1], k2q, k3q, Tvarsel[k3q], k3q, Tvalsel[k3q]);
1.331     brouard  10435:     }else if(Typevar[k1]==2 ){ /* For product quant or dummy (not with age) */
1.332   ! brouard  10436:       precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
        !          10437:       printf("Decoderesult Quantitative or Dummy (not with age) nres=%d k1=%d precov[nres=%d][k1=%d]=%.f V%d(=%.f) * V%d(=%.f) \n",nres, k1, nres, k1,precov[nres][k1], Tvardk[k1][1], TinvDoQresult[nres][Tvardk[k1][1]], Tvardk[k1][2], TinvDoQresult[nres][Tvardk[k1][2]]);
1.330     brouard  10438:     }else{
1.332   ! brouard  10439:       printf("Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
        !          10440:       fprintf(ficlog,"Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
1.235     brouard  10441:     }
                   10442:   }
1.234     brouard  10443:   
1.235     brouard  10444:   TKresult[nres]=++k; /* Combination for the nresult and the model */
1.230     brouard  10445:   return (0);
                   10446: }
1.235     brouard  10447: 
1.230     brouard  10448: int decodemodel( char model[], int lastobs)
                   10449:  /**< This routine decodes the model and returns:
1.224     brouard  10450:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   10451:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   10452:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   10453:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   10454:        * - cptcovage number of covariates with age*products =2
                   10455:        * - cptcovs number of simple covariates
                   10456:        * - 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
                   10457:        *     which is a new column after the 9 (ncovcol) variables. 
1.319     brouard  10458:        * - if k is a product Vn*Vm, covar[k][i] is filled with correct values for each individual
1.224     brouard  10459:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   10460:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   10461:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   10462:        */
1.319     brouard  10463: /* 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  10464: {
1.238     brouard  10465:   int i, j, k, ks, v;
1.227     brouard  10466:   int  j1, k1, k2, k3, k4;
1.136     brouard  10467:   char modelsav[80];
1.145     brouard  10468:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  10469:   char *strpt;
1.136     brouard  10470: 
1.145     brouard  10471:   /*removespace(model);*/
1.136     brouard  10472:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  10473:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  10474:     if (strstr(model,"AGE") !=0){
1.192     brouard  10475:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   10476:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  10477:       return 1;
                   10478:     }
1.141     brouard  10479:     if (strstr(model,"v") !=0){
                   10480:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   10481:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   10482:       return 1;
                   10483:     }
1.187     brouard  10484:     strcpy(modelsav,model); 
                   10485:     if ((strpt=strstr(model,"age*age")) !=0){
                   10486:       printf(" strpt=%s, model=%s\n",strpt, model);
                   10487:       if(strpt != model){
1.234     brouard  10488:        printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  10489:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  10490:  corresponding column of parameters.\n",model);
1.234     brouard  10491:        fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  10492:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  10493:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  10494:        return 1;
1.225     brouard  10495:       }
1.187     brouard  10496:       nagesqr=1;
                   10497:       if (strstr(model,"+age*age") !=0)
1.234     brouard  10498:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  10499:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  10500:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  10501:       else 
1.234     brouard  10502:        substrchaine(modelsav, model, "age*age");
1.187     brouard  10503:     }else
                   10504:       nagesqr=0;
                   10505:     if (strlen(modelsav) >1){
                   10506:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   10507:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224     brouard  10508:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  10509:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  10510:                     * cst, age and age*age 
                   10511:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   10512:       /* including age products which are counted in cptcovage.
                   10513:        * but the covariates which are products must be treated 
                   10514:        * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  10515:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   10516:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.225     brouard  10517:       
                   10518:       
1.187     brouard  10519:       /*   Design
                   10520:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   10521:        *  <          ncovcol=8                >
                   10522:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   10523:        *   k=  1    2      3       4     5       6      7        8
                   10524:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   10525:        *  covar[k,i], value of kth covariate if not including age for individual i:
1.224     brouard  10526:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   10527:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  10528:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   10529:        *  Tage[++cptcovage]=k
                   10530:        *       if products, new covar are created after ncovcol with k1
                   10531:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   10532:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   10533:        *  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
                   10534:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   10535:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   10536:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   10537:        *  <          ncovcol=8                >
                   10538:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   10539:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   10540:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
1.319     brouard  10541:        * p Tvar[1]@12={2,   1,     3,      3,  11,     10,     8,       8,   7,   8,   5,  6}
1.187     brouard  10542:        * p Tprod[1]@2={                         6, 5}
                   10543:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   10544:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   10545:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1.319     brouard  10546:        *How to reorganize? Tvars(orted)
1.187     brouard  10547:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   10548:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   10549:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   10550:        * Struct []
                   10551:        */
1.225     brouard  10552:       
1.187     brouard  10553:       /* This loop fills the array Tvar from the string 'model'.*/
                   10554:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   10555:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   10556:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   10557:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   10558:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   10559:       /*       k=1 Tvar[1]=2 (from V2) */
                   10560:       /*       k=5 Tvar[5] */
                   10561:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  10562:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  10563:       /*       } */
1.198     brouard  10564:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  10565:       /*
                   10566:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  10567:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   10568:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   10569:       }
1.187     brouard  10570:       cptcovage=0;
1.319     brouard  10571:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model line */
                   10572:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' cutl from left to right
                   10573:                                         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" */
                   10574:        if (nbocc(modelsav,'+')==0)
                   10575:          strcpy(strb,modelsav); /* and analyzes it */
1.234     brouard  10576:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   10577:        /*scanf("%d",i);*/
1.319     brouard  10578:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V5*age+ V4+V3*age strb=V3*age */
                   10579:          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  10580:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   10581:            /* covar is not filled and then is empty */
                   10582:            cptcovprod--;
                   10583:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
1.319     brouard  10584:            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  10585:            Typevar[k]=1;  /* 1 for age product */
1.319     brouard  10586:            cptcovage++; /* Counts the number of covariates which include age as a product */
                   10587:            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  10588:            /*printf("stre=%s ", stre);*/
                   10589:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   10590:            cptcovprod--;
                   10591:            cutl(stre,strb,strc,'V');
                   10592:            Tvar[k]=atoi(stre);
                   10593:            Typevar[k]=1;  /* 1 for age product */
                   10594:            cptcovage++;
                   10595:            Tage[cptcovage]=k;
                   10596:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   10597:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   10598:            cptcovn++;
                   10599:            cptcovprodnoage++;k1++;
                   10600:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   10601:            Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* For model-covariate k tells which data-covariate to use but
                   10602:                                                because this model-covariate is a construction we invent a new column
                   10603:                                                which is after existing variables ncovcol+nqv+ntv+nqtv + k1
1.319     brouard  10604:                                                If already ncovcol=4 and model=V2 + V1 +V1*V4 +age*V3 +V3*V2
                   10605:                                                thus after V4 we invent V5 and V6 because age*V3 will be computed in 4
                   10606:                                                Tvar[3=V1*V4]=4+1=5 Tvar[5=V3*V2]=4 + 2= 6, Tvar[4=age*V3]=4 etc */
1.234     brouard  10607:            Typevar[k]=2;  /* 2 for double fixed dummy covariates */
                   10608:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   10609:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
1.319     brouard  10610:            Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 */
1.234     brouard  10611:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
1.330     brouard  10612:            Tvardk[k][1] =atoi(strc); /* m 1 for V1*/
1.234     brouard  10613:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
1.330     brouard  10614:            Tvardk[k][2] =atoi(stre); /* n 4 for V4*/
1.234     brouard  10615:            k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   10616:            /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   10617:            /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
1.225     brouard  10618:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
1.234     brouard  10619:            /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   10620:            for (i=1; i<=lastobs;i++){
                   10621:              /* Computes the new covariate which is a product of
                   10622:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   10623:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   10624:            }
                   10625:          } /* End age is not in the model */
                   10626:        } /* End if model includes a product */
1.319     brouard  10627:        else { /* not a product */
1.234     brouard  10628:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   10629:          /*  scanf("%d",i);*/
                   10630:          cutl(strd,strc,strb,'V');
                   10631:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   10632:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   10633:          Tvar[k]=atoi(strd);
                   10634:          Typevar[k]=0;  /* 0 for simple covariates */
                   10635:        }
                   10636:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  10637:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  10638:                                  scanf("%d",i);*/
1.187     brouard  10639:       } /* end of loop + on total covariates */
                   10640:     } /* end if strlen(modelsave == 0) age*age might exist */
                   10641:   } /* end if strlen(model == 0) */
1.136     brouard  10642:   
                   10643:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   10644:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  10645:   
1.136     brouard  10646:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  10647:      printf("cptcovprod=%d ", cptcovprod);
                   10648:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   10649:      scanf("%d ",i);*/
                   10650: 
                   10651: 
1.230     brouard  10652: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   10653:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  10654: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   10655:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   10656:    k =           1    2   3     4       5       6      7      8        9
                   10657:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
1.319     brouard  10658:    Typevar[k]=   0    0   0     2       1       0      2      1        0
1.227     brouard  10659:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   10660:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   10661:          Tmodelind[combination of covar]=k;
1.225     brouard  10662: */  
                   10663: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  10664:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  10665:   /* 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  10666:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.318     brouard  10667:   printf("Model=1+age+%s\n\
1.227     brouard  10668: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   10669: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   10670: 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  10671:   fprintf(ficlog,"Model=1+age+%s\n\
1.227     brouard  10672: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   10673: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   10674: 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  10675:   for(k=-1;k<=cptcovt; k++){ Fixed[k]=0; Dummy[k]=0;}
1.234     brouard  10676:   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 */
                   10677:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  10678:       Fixed[k]= 0;
                   10679:       Dummy[k]= 0;
1.225     brouard  10680:       ncoveff++;
1.232     brouard  10681:       ncovf++;
1.234     brouard  10682:       nsd++;
                   10683:       modell[k].maintype= FTYPE;
                   10684:       TvarsD[nsd]=Tvar[k];
                   10685:       TvarsDind[nsd]=k;
1.330     brouard  10686:       TnsdVar[Tvar[k]]=nsd;
1.234     brouard  10687:       TvarF[ncovf]=Tvar[k];
                   10688:       TvarFind[ncovf]=k;
                   10689:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   10690:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   10691:     }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /* Product of fixed dummy (<=ncovcol) covariates */
                   10692:       Fixed[k]= 0;
                   10693:       Dummy[k]= 0;
                   10694:       ncoveff++;
                   10695:       ncovf++;
                   10696:       modell[k].maintype= FTYPE;
                   10697:       TvarF[ncovf]=Tvar[k];
1.330     brouard  10698:       /* TnsdVar[Tvar[k]]=nsd; */ /* To be done */
1.234     brouard  10699:       TvarFind[ncovf]=k;
1.230     brouard  10700:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  10701:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.240     brouard  10702:     }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  10703:       Fixed[k]= 0;
                   10704:       Dummy[k]= 1;
1.230     brouard  10705:       nqfveff++;
1.234     brouard  10706:       modell[k].maintype= FTYPE;
                   10707:       modell[k].subtype= FQ;
                   10708:       nsq++;
                   10709:       TvarsQ[nsq]=Tvar[k];
                   10710:       TvarsQind[nsq]=k;
1.232     brouard  10711:       ncovf++;
1.234     brouard  10712:       TvarF[ncovf]=Tvar[k];
                   10713:       TvarFind[ncovf]=k;
1.231     brouard  10714:       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  10715:       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  10716:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.227     brouard  10717:       Fixed[k]= 1;
                   10718:       Dummy[k]= 0;
1.225     brouard  10719:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  10720:       modell[k].maintype= VTYPE;
                   10721:       modell[k].subtype= VD;
                   10722:       nsd++;
                   10723:       TvarsD[nsd]=Tvar[k];
                   10724:       TvarsDind[nsd]=k;
1.330     brouard  10725:       TnsdVar[Tvar[k]]=nsd; /* To be verified */
1.234     brouard  10726:       ncovv++; /* Only simple time varying variables */
                   10727:       TvarV[ncovv]=Tvar[k];
1.242     brouard  10728:       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  10729:       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 */
                   10730:       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  10731:       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);
                   10732:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  10733:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.234     brouard  10734:       Fixed[k]= 1;
                   10735:       Dummy[k]= 1;
                   10736:       nqtveff++;
                   10737:       modell[k].maintype= VTYPE;
                   10738:       modell[k].subtype= VQ;
                   10739:       ncovv++; /* Only simple time varying variables */
                   10740:       nsq++;
1.319     brouard  10741:       TvarsQ[nsq]=Tvar[k]; /* k=1 Tvar=5 nsq=1 TvarsQ[1]=5 */
1.332   ! brouard  10742:       TvarsQind[nsq]=k; /* For single quantitative covariate gives the model position of each single quantitative covariate */
1.234     brouard  10743:       TvarV[ncovv]=Tvar[k];
1.242     brouard  10744:       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  10745:       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 */
                   10746:       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  10747:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   10748:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
                   10749:       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  10750:       printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv);
1.227     brouard  10751:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  10752:       ncova++;
                   10753:       TvarA[ncova]=Tvar[k];
                   10754:       TvarAind[ncova]=k;
1.231     brouard  10755:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  10756:        Fixed[k]= 2;
                   10757:        Dummy[k]= 2;
                   10758:        modell[k].maintype= ATYPE;
                   10759:        modell[k].subtype= APFD;
                   10760:        /* ncoveff++; */
1.227     brouard  10761:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  10762:        Fixed[k]= 2;
                   10763:        Dummy[k]= 3;
                   10764:        modell[k].maintype= ATYPE;
                   10765:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   10766:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  10767:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  10768:        Fixed[k]= 3;
                   10769:        Dummy[k]= 2;
                   10770:        modell[k].maintype= ATYPE;
                   10771:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   10772:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  10773:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  10774:        Fixed[k]= 3;
                   10775:        Dummy[k]= 3;
                   10776:        modell[k].maintype= ATYPE;
                   10777:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   10778:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  10779:       }
                   10780:     }else if (Typevar[k] == 2) {  /* product without age */
                   10781:       k1=Tposprod[k];
                   10782:       if(Tvard[k1][1] <=ncovcol){
1.240     brouard  10783:        if(Tvard[k1][2] <=ncovcol){
                   10784:          Fixed[k]= 1;
                   10785:          Dummy[k]= 0;
                   10786:          modell[k].maintype= FTYPE;
                   10787:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
                   10788:          ncovf++; /* Fixed variables without age */
                   10789:          TvarF[ncovf]=Tvar[k];
                   10790:          TvarFind[ncovf]=k;
                   10791:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10792:          Fixed[k]= 0;  /* or 2 ?*/
                   10793:          Dummy[k]= 1;
                   10794:          modell[k].maintype= FTYPE;
                   10795:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
                   10796:          ncovf++; /* Varying variables without age */
                   10797:          TvarF[ncovf]=Tvar[k];
                   10798:          TvarFind[ncovf]=k;
                   10799:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10800:          Fixed[k]= 1;
                   10801:          Dummy[k]= 0;
                   10802:          modell[k].maintype= VTYPE;
                   10803:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
                   10804:          ncovv++; /* Varying variables without age */
                   10805:          TvarV[ncovv]=Tvar[k];
                   10806:          TvarVind[ncovv]=k;
                   10807:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10808:          Fixed[k]= 1;
                   10809:          Dummy[k]= 1;
                   10810:          modell[k].maintype= VTYPE;
                   10811:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
                   10812:          ncovv++; /* Varying variables without age */
                   10813:          TvarV[ncovv]=Tvar[k];
                   10814:          TvarVind[ncovv]=k;
                   10815:        }
1.227     brouard  10816:       }else if(Tvard[k1][1] <=ncovcol+nqv){
1.240     brouard  10817:        if(Tvard[k1][2] <=ncovcol){
                   10818:          Fixed[k]= 0;  /* or 2 ?*/
                   10819:          Dummy[k]= 1;
                   10820:          modell[k].maintype= FTYPE;
                   10821:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
                   10822:          ncovf++; /* Fixed variables without age */
                   10823:          TvarF[ncovf]=Tvar[k];
                   10824:          TvarFind[ncovf]=k;
                   10825:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10826:          Fixed[k]= 1;
                   10827:          Dummy[k]= 1;
                   10828:          modell[k].maintype= VTYPE;
                   10829:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
                   10830:          ncovv++; /* Varying variables without age */
                   10831:          TvarV[ncovv]=Tvar[k];
                   10832:          TvarVind[ncovv]=k;
                   10833:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10834:          Fixed[k]= 1;
                   10835:          Dummy[k]= 1;
                   10836:          modell[k].maintype= VTYPE;
                   10837:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
                   10838:          ncovv++; /* Varying variables without age */
                   10839:          TvarV[ncovv]=Tvar[k];
                   10840:          TvarVind[ncovv]=k;
                   10841:          ncovv++; /* Varying variables without age */
                   10842:          TvarV[ncovv]=Tvar[k];
                   10843:          TvarVind[ncovv]=k;
                   10844:        }
1.227     brouard  10845:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){
1.240     brouard  10846:        if(Tvard[k1][2] <=ncovcol){
                   10847:          Fixed[k]= 1;
                   10848:          Dummy[k]= 1;
                   10849:          modell[k].maintype= VTYPE;
                   10850:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
                   10851:          ncovv++; /* Varying variables without age */
                   10852:          TvarV[ncovv]=Tvar[k];
                   10853:          TvarVind[ncovv]=k;
                   10854:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10855:          Fixed[k]= 1;
                   10856:          Dummy[k]= 1;
                   10857:          modell[k].maintype= VTYPE;
                   10858:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
                   10859:          ncovv++; /* Varying variables without age */
                   10860:          TvarV[ncovv]=Tvar[k];
                   10861:          TvarVind[ncovv]=k;
                   10862:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10863:          Fixed[k]= 1;
                   10864:          Dummy[k]= 0;
                   10865:          modell[k].maintype= VTYPE;
                   10866:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
                   10867:          ncovv++; /* Varying variables without age */
                   10868:          TvarV[ncovv]=Tvar[k];
                   10869:          TvarVind[ncovv]=k;
                   10870:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10871:          Fixed[k]= 1;
                   10872:          Dummy[k]= 1;
                   10873:          modell[k].maintype= VTYPE;
                   10874:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
                   10875:          ncovv++; /* Varying variables without age */
                   10876:          TvarV[ncovv]=Tvar[k];
                   10877:          TvarVind[ncovv]=k;
                   10878:        }
1.227     brouard  10879:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  10880:        if(Tvard[k1][2] <=ncovcol){
                   10881:          Fixed[k]= 1;
                   10882:          Dummy[k]= 1;
                   10883:          modell[k].maintype= VTYPE;
                   10884:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
                   10885:          ncovv++; /* Varying variables without age */
                   10886:          TvarV[ncovv]=Tvar[k];
                   10887:          TvarVind[ncovv]=k;
                   10888:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10889:          Fixed[k]= 1;
                   10890:          Dummy[k]= 1;
                   10891:          modell[k].maintype= VTYPE;
                   10892:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
                   10893:          ncovv++; /* Varying variables without age */
                   10894:          TvarV[ncovv]=Tvar[k];
                   10895:          TvarVind[ncovv]=k;
                   10896:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10897:          Fixed[k]= 1;
                   10898:          Dummy[k]= 1;
                   10899:          modell[k].maintype= VTYPE;
                   10900:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
                   10901:          ncovv++; /* Varying variables without age */
                   10902:          TvarV[ncovv]=Tvar[k];
                   10903:          TvarVind[ncovv]=k;
                   10904:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10905:          Fixed[k]= 1;
                   10906:          Dummy[k]= 1;
                   10907:          modell[k].maintype= VTYPE;
                   10908:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
                   10909:          ncovv++; /* Varying variables without age */
                   10910:          TvarV[ncovv]=Tvar[k];
                   10911:          TvarVind[ncovv]=k;
                   10912:        }
1.227     brouard  10913:       }else{
1.240     brouard  10914:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   10915:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   10916:       } /*end k1*/
1.225     brouard  10917:     }else{
1.226     brouard  10918:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   10919:       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  10920:     }
1.227     brouard  10921:     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  10922:     printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype);
1.227     brouard  10923:     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]);
                   10924:   }
                   10925:   /* Searching for doublons in the model */
                   10926:   for(k1=1; k1<= cptcovt;k1++){
                   10927:     for(k2=1; k2 <k1;k2++){
1.285     brouard  10928:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   10929:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  10930:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   10931:          if(Tvar[k1]==Tvar[k2]){
1.285     brouard  10932:            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]);
                   10933:            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  10934:            return(1);
                   10935:          }
                   10936:        }else if (Typevar[k1] ==2){
                   10937:          k3=Tposprod[k1];
                   10938:          k4=Tposprod[k2];
                   10939:          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])) ){
                   10940:            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]]);
                   10941:            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);
                   10942:            return(1);
                   10943:          }
                   10944:        }
1.227     brouard  10945:       }
                   10946:     }
1.225     brouard  10947:   }
                   10948:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   10949:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  10950:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   10951:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.137     brouard  10952:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  10953:   /*endread:*/
1.225     brouard  10954:   printf("Exiting decodemodel: ");
                   10955:   return (1);
1.136     brouard  10956: }
                   10957: 
1.169     brouard  10958: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  10959: {/* Check ages at death */
1.136     brouard  10960:   int i, m;
1.218     brouard  10961:   int firstone=0;
                   10962:   
1.136     brouard  10963:   for (i=1; i<=imx; i++) {
                   10964:     for(m=2; (m<= maxwav); m++) {
                   10965:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   10966:        anint[m][i]=9999;
1.216     brouard  10967:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   10968:          s[m][i]=-1;
1.136     brouard  10969:       }
                   10970:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  10971:        *nberr = *nberr + 1;
1.218     brouard  10972:        if(firstone == 0){
                   10973:          firstone=1;
1.260     brouard  10974:        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  10975:        }
1.262     brouard  10976:        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  10977:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  10978:       }
                   10979:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  10980:        (*nberr)++;
1.259     brouard  10981:        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  10982:        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  10983:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  10984:       }
                   10985:     }
                   10986:   }
                   10987: 
                   10988:   for (i=1; i<=imx; i++)  {
                   10989:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   10990:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  10991:       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  10992:        if (s[m][i] >= nlstate+1) {
1.169     brouard  10993:          if(agedc[i]>0){
                   10994:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  10995:              agev[m][i]=agedc[i];
1.214     brouard  10996:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  10997:            }else {
1.136     brouard  10998:              if ((int)andc[i]!=9999){
                   10999:                nbwarn++;
                   11000:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   11001:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   11002:                agev[m][i]=-1;
                   11003:              }
                   11004:            }
1.169     brouard  11005:          } /* agedc > 0 */
1.214     brouard  11006:        } /* end if */
1.136     brouard  11007:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   11008:                                 years but with the precision of a month */
                   11009:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   11010:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   11011:            agev[m][i]=1;
                   11012:          else if(agev[m][i] < *agemin){ 
                   11013:            *agemin=agev[m][i];
                   11014:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   11015:          }
                   11016:          else if(agev[m][i] >*agemax){
                   11017:            *agemax=agev[m][i];
1.156     brouard  11018:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  11019:          }
                   11020:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   11021:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  11022:        } /* en if 9*/
1.136     brouard  11023:        else { /* =9 */
1.214     brouard  11024:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  11025:          agev[m][i]=1;
                   11026:          s[m][i]=-1;
                   11027:        }
                   11028:       }
1.214     brouard  11029:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  11030:        agev[m][i]=1;
1.214     brouard  11031:       else{
                   11032:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   11033:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   11034:        agev[m][i]=0;
                   11035:       }
                   11036:     } /* End for lastpass */
                   11037:   }
1.136     brouard  11038:     
                   11039:   for (i=1; i<=imx; i++)  {
                   11040:     for(m=firstpass; (m<=lastpass); m++){
                   11041:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  11042:        (*nberr)++;
1.136     brouard  11043:        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);     
                   11044:        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);     
                   11045:        return 1;
                   11046:       }
                   11047:     }
                   11048:   }
                   11049: 
                   11050:   /*for (i=1; i<=imx; i++){
                   11051:   for (m=firstpass; (m<lastpass); m++){
                   11052:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   11053: }
                   11054: 
                   11055: }*/
                   11056: 
                   11057: 
1.139     brouard  11058:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   11059:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  11060: 
                   11061:   return (0);
1.164     brouard  11062:  /* endread:*/
1.136     brouard  11063:     printf("Exiting calandcheckages: ");
                   11064:     return (1);
                   11065: }
                   11066: 
1.172     brouard  11067: #if defined(_MSC_VER)
                   11068: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   11069: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   11070: //#include "stdafx.h"
                   11071: //#include <stdio.h>
                   11072: //#include <tchar.h>
                   11073: //#include <windows.h>
                   11074: //#include <iostream>
                   11075: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   11076: 
                   11077: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   11078: 
                   11079: BOOL IsWow64()
                   11080: {
                   11081:        BOOL bIsWow64 = FALSE;
                   11082: 
                   11083:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   11084:        //  (HANDLE, PBOOL);
                   11085: 
                   11086:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   11087: 
                   11088:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   11089:        const char funcName[] = "IsWow64Process";
                   11090:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   11091:                GetProcAddress(module, funcName);
                   11092: 
                   11093:        if (NULL != fnIsWow64Process)
                   11094:        {
                   11095:                if (!fnIsWow64Process(GetCurrentProcess(),
                   11096:                        &bIsWow64))
                   11097:                        //throw std::exception("Unknown error");
                   11098:                        printf("Unknown error\n");
                   11099:        }
                   11100:        return bIsWow64 != FALSE;
                   11101: }
                   11102: #endif
1.177     brouard  11103: 
1.191     brouard  11104: void syscompilerinfo(int logged)
1.292     brouard  11105: {
                   11106: #include <stdint.h>
                   11107: 
                   11108:   /* #include "syscompilerinfo.h"*/
1.185     brouard  11109:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   11110:    /* /GS /W3 /Gy
                   11111:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   11112:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   11113:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  11114:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   11115:    */ 
                   11116:    /* 64 bits */
1.185     brouard  11117:    /*
                   11118:      /GS /W3 /Gy
                   11119:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   11120:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   11121:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   11122:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   11123:    /* Optimization are useless and O3 is slower than O2 */
                   11124:    /*
                   11125:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   11126:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   11127:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   11128:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   11129:    */
1.186     brouard  11130:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  11131:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   11132:       /PDB:"visual studio
                   11133:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   11134:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   11135:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   11136:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   11137:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   11138:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   11139:       uiAccess='false'"
                   11140:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   11141:       /NOLOGO /TLBID:1
                   11142:    */
1.292     brouard  11143: 
                   11144: 
1.177     brouard  11145: #if defined __INTEL_COMPILER
1.178     brouard  11146: #if defined(__GNUC__)
                   11147:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   11148: #endif
1.177     brouard  11149: #elif defined(__GNUC__) 
1.179     brouard  11150: #ifndef  __APPLE__
1.174     brouard  11151: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  11152: #endif
1.177     brouard  11153:    struct utsname sysInfo;
1.178     brouard  11154:    int cross = CROSS;
                   11155:    if (cross){
                   11156:           printf("Cross-");
1.191     brouard  11157:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  11158:    }
1.174     brouard  11159: #endif
                   11160: 
1.191     brouard  11161:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  11162: #if defined(__clang__)
1.191     brouard  11163:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  11164: #endif
                   11165: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  11166:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  11167: #endif
                   11168: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  11169:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  11170: #endif
                   11171: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  11172:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  11173: #endif
                   11174: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  11175:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  11176: #endif
                   11177: #if defined(_MSC_VER)
1.191     brouard  11178:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  11179: #endif
                   11180: #if defined(__PGI)
1.191     brouard  11181:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  11182: #endif
                   11183: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  11184:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  11185: #endif
1.191     brouard  11186:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  11187:    
1.167     brouard  11188: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   11189: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   11190:     // Windows (x64 and x86)
1.191     brouard  11191:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  11192: #elif __unix__ // all unices, not all compilers
                   11193:     // Unix
1.191     brouard  11194:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  11195: #elif __linux__
                   11196:     // linux
1.191     brouard  11197:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  11198: #elif __APPLE__
1.174     brouard  11199:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  11200:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  11201: #endif
                   11202: 
                   11203: /*  __MINGW32__          */
                   11204: /*  __CYGWIN__  */
                   11205: /* __MINGW64__  */
                   11206: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   11207: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   11208: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   11209: /* _WIN64  // Defined for applications for Win64. */
                   11210: /* _M_X64 // Defined for compilations that target x64 processors. */
                   11211: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  11212: 
1.167     brouard  11213: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  11214:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  11215: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  11216:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  11217: #else
1.191     brouard  11218:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  11219: #endif
                   11220: 
1.169     brouard  11221: #if defined(__GNUC__)
                   11222: # if defined(__GNUC_PATCHLEVEL__)
                   11223: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   11224:                             + __GNUC_MINOR__ * 100 \
                   11225:                             + __GNUC_PATCHLEVEL__)
                   11226: # else
                   11227: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   11228:                             + __GNUC_MINOR__ * 100)
                   11229: # endif
1.174     brouard  11230:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  11231:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  11232: 
                   11233:    if (uname(&sysInfo) != -1) {
                   11234:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  11235:         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  11236:    }
                   11237:    else
                   11238:       perror("uname() error");
1.179     brouard  11239:    //#ifndef __INTEL_COMPILER 
                   11240: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  11241:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  11242:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  11243: #endif
1.169     brouard  11244: #endif
1.172     brouard  11245: 
1.286     brouard  11246:    //   void main ()
1.172     brouard  11247:    //   {
1.169     brouard  11248: #if defined(_MSC_VER)
1.174     brouard  11249:    if (IsWow64()){
1.191     brouard  11250:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   11251:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  11252:    }
                   11253:    else{
1.191     brouard  11254:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   11255:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  11256:    }
1.172     brouard  11257:    //     printf("\nPress Enter to continue...");
                   11258:    //     getchar();
                   11259:    //   }
                   11260: 
1.169     brouard  11261: #endif
                   11262:    
1.167     brouard  11263: 
1.219     brouard  11264: }
1.136     brouard  11265: 
1.219     brouard  11266: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  11267:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.332   ! brouard  11268:   /* Computes the prevalence limit for each combination of the dummy covariates */
1.235     brouard  11269:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  11270:   /* double ftolpl = 1.e-10; */
1.180     brouard  11271:   double age, agebase, agelim;
1.203     brouard  11272:   double tot;
1.180     brouard  11273: 
1.202     brouard  11274:   strcpy(filerespl,"PL_");
                   11275:   strcat(filerespl,fileresu);
                   11276:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  11277:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   11278:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  11279:   }
1.288     brouard  11280:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   11281:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  11282:   pstamp(ficrespl);
1.288     brouard  11283:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  11284:   fprintf(ficrespl,"#Age ");
                   11285:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   11286:   fprintf(ficrespl,"\n");
1.180     brouard  11287:   
1.219     brouard  11288:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  11289: 
1.219     brouard  11290:   agebase=ageminpar;
                   11291:   agelim=agemaxpar;
1.180     brouard  11292: 
1.227     brouard  11293:   /* i1=pow(2,ncoveff); */
1.234     brouard  11294:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  11295:   if (cptcovn < 1){i1=1;}
1.180     brouard  11296: 
1.238     brouard  11297:   for(k=1; k<=i1;k++){ /* For each combination k of dummy covariates in the model */
                   11298:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  11299:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  11300:        continue;
1.235     brouard  11301: 
1.238     brouard  11302:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11303:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   11304:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   11305:       /* k=k+1; */
                   11306:       /* to clean */
1.332   ! brouard  11307:       /*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*/
1.238     brouard  11308:       fprintf(ficrespl,"#******");
                   11309:       printf("#******");
                   11310:       fprintf(ficlog,"#******");
                   11311:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
1.332   ! brouard  11312:        /* fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Here problem for varying dummy*\/ */
        !          11313:        fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /* Here problem for varying dummy*/
        !          11314:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
        !          11315:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.238     brouard  11316:       }
                   11317:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   11318:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   11319:        fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   11320:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   11321:       }
                   11322:       fprintf(ficrespl,"******\n");
                   11323:       printf("******\n");
                   11324:       fprintf(ficlog,"******\n");
                   11325:       if(invalidvarcomb[k]){
                   11326:        printf("\nCombination (%d) ignored because no case \n",k); 
                   11327:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   11328:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   11329:        continue;
                   11330:       }
1.219     brouard  11331: 
1.238     brouard  11332:       fprintf(ficrespl,"#Age ");
                   11333:       for(j=1;j<=cptcoveff;j++) {
1.332   ! brouard  11334:        fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.238     brouard  11335:       }
                   11336:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   11337:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  11338:     
1.238     brouard  11339:       for (age=agebase; age<=agelim; age++){
                   11340:        /* for (age=agebase; age<=agebase; age++){ */
                   11341:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres);
                   11342:        fprintf(ficrespl,"%.0f ",age );
                   11343:        for(j=1;j<=cptcoveff;j++)
1.332   ! brouard  11344:          fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.238     brouard  11345:        tot=0.;
                   11346:        for(i=1; i<=nlstate;i++){
                   11347:          tot +=  prlim[i][i];
                   11348:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   11349:        }
                   11350:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   11351:       } /* Age */
                   11352:       /* was end of cptcod */
                   11353:     } /* cptcov */
                   11354:   } /* nres */
1.219     brouard  11355:   return 0;
1.180     brouard  11356: }
                   11357: 
1.218     brouard  11358: 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  11359:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  11360:        
                   11361:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   11362:    * at any age between ageminpar and agemaxpar
                   11363:         */
1.235     brouard  11364:   int i, j, k, i1, nres=0 ;
1.217     brouard  11365:   /* double ftolpl = 1.e-10; */
                   11366:   double age, agebase, agelim;
                   11367:   double tot;
1.218     brouard  11368:   /* double ***mobaverage; */
                   11369:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  11370: 
                   11371:   strcpy(fileresplb,"PLB_");
                   11372:   strcat(fileresplb,fileresu);
                   11373:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  11374:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   11375:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  11376:   }
1.288     brouard  11377:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   11378:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  11379:   pstamp(ficresplb);
1.288     brouard  11380:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  11381:   fprintf(ficresplb,"#Age ");
                   11382:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   11383:   fprintf(ficresplb,"\n");
                   11384:   
1.218     brouard  11385:   
                   11386:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   11387:   
                   11388:   agebase=ageminpar;
                   11389:   agelim=agemaxpar;
                   11390:   
                   11391:   
1.227     brouard  11392:   i1=pow(2,cptcoveff);
1.218     brouard  11393:   if (cptcovn < 1){i1=1;}
1.227     brouard  11394:   
1.238     brouard  11395:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11396:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  11397:      if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  11398:        continue;
1.332   ! brouard  11399:      /*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*/
1.238     brouard  11400:       fprintf(ficresplb,"#******");
                   11401:       printf("#******");
                   11402:       fprintf(ficlog,"#******");
                   11403:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
1.332   ! brouard  11404:        fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
        !          11405:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
        !          11406:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.238     brouard  11407:       }
                   11408:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332   ! brouard  11409:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
        !          11410:        fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
        !          11411:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
1.238     brouard  11412:       }
                   11413:       fprintf(ficresplb,"******\n");
                   11414:       printf("******\n");
                   11415:       fprintf(ficlog,"******\n");
                   11416:       if(invalidvarcomb[k]){
                   11417:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   11418:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   11419:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   11420:        continue;
                   11421:       }
1.218     brouard  11422:     
1.238     brouard  11423:       fprintf(ficresplb,"#Age ");
                   11424:       for(j=1;j<=cptcoveff;j++) {
1.332   ! brouard  11425:        fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.238     brouard  11426:       }
                   11427:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   11428:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  11429:     
                   11430:     
1.238     brouard  11431:       for (age=agebase; age<=agelim; age++){
                   11432:        /* for (age=agebase; age<=agebase; age++){ */
                   11433:        if(mobilavproj > 0){
                   11434:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   11435:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  11436:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  11437:        }else if (mobilavproj == 0){
                   11438:          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);
                   11439:          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);
                   11440:          exit(1);
                   11441:        }else{
                   11442:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  11443:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  11444:          /* printf("TOTOT\n"); */
                   11445:           /* exit(1); */
1.238     brouard  11446:        }
                   11447:        fprintf(ficresplb,"%.0f ",age );
                   11448:        for(j=1;j<=cptcoveff;j++)
1.332   ! brouard  11449:          fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.238     brouard  11450:        tot=0.;
                   11451:        for(i=1; i<=nlstate;i++){
                   11452:          tot +=  bprlim[i][i];
                   11453:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   11454:        }
                   11455:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   11456:       } /* Age */
                   11457:       /* was end of cptcod */
1.255     brouard  11458:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.238     brouard  11459:     } /* end of any combination */
                   11460:   } /* end of nres */  
1.218     brouard  11461:   /* hBijx(p, bage, fage); */
                   11462:   /* fclose(ficrespijb); */
                   11463:   
                   11464:   return 0;
1.217     brouard  11465: }
1.218     brouard  11466:  
1.180     brouard  11467: int hPijx(double *p, int bage, int fage){
                   11468:     /*------------- h Pij x at various ages ------------*/
                   11469: 
                   11470:   int stepsize;
                   11471:   int agelim;
                   11472:   int hstepm;
                   11473:   int nhstepm;
1.235     brouard  11474:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  11475: 
                   11476:   double agedeb;
                   11477:   double ***p3mat;
                   11478: 
1.201     brouard  11479:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  11480:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   11481:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   11482:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   11483:     }
                   11484:     printf("Computing pij: result on file '%s' \n", filerespij);
                   11485:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   11486:   
                   11487:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   11488:     /*if (stepm<=24) stepsize=2;*/
                   11489: 
                   11490:     agelim=AGESUP;
                   11491:     hstepm=stepsize*YEARM; /* Every year of age */
                   11492:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
1.218     brouard  11493:                
1.180     brouard  11494:     /* hstepm=1;   aff par mois*/
                   11495:     pstamp(ficrespij);
                   11496:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
1.227     brouard  11497:     i1= pow(2,cptcoveff);
1.218     brouard  11498:                /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11499:                /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   11500:                /*      k=k+1;  */
1.235     brouard  11501:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   11502:     for(k=1; k<=i1;k++){
1.253     brouard  11503:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  11504:        continue;
1.183     brouard  11505:       fprintf(ficrespij,"\n#****** ");
1.227     brouard  11506:       for(j=1;j<=cptcoveff;j++) 
1.332   ! brouard  11507:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.235     brouard  11508:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   11509:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   11510:        fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   11511:       }
1.183     brouard  11512:       fprintf(ficrespij,"******\n");
                   11513:       
                   11514:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   11515:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   11516:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   11517:        
                   11518:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  11519:        
1.183     brouard  11520:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11521:        oldm=oldms;savm=savms;
1.235     brouard  11522:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
1.183     brouard  11523:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   11524:        for(i=1; i<=nlstate;i++)
                   11525:          for(j=1; j<=nlstate+ndeath;j++)
                   11526:            fprintf(ficrespij," %1d-%1d",i,j);
                   11527:        fprintf(ficrespij,"\n");
                   11528:        for (h=0; h<=nhstepm; h++){
                   11529:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   11530:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  11531:          for(i=1; i<=nlstate;i++)
                   11532:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  11533:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  11534:          fprintf(ficrespij,"\n");
                   11535:        }
1.183     brouard  11536:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11537:        fprintf(ficrespij,"\n");
                   11538:       }
1.180     brouard  11539:       /*}*/
                   11540:     }
1.218     brouard  11541:     return 0;
1.180     brouard  11542: }
1.218     brouard  11543:  
                   11544:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  11545:     /*------------- h Bij x at various ages ------------*/
                   11546: 
                   11547:   int stepsize;
1.218     brouard  11548:   /* int agelim; */
                   11549:        int ageminl;
1.217     brouard  11550:   int hstepm;
                   11551:   int nhstepm;
1.238     brouard  11552:   int h, i, i1, j, k, nres;
1.218     brouard  11553:        
1.217     brouard  11554:   double agedeb;
                   11555:   double ***p3mat;
1.218     brouard  11556:        
                   11557:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   11558:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   11559:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   11560:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   11561:   }
                   11562:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   11563:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   11564:   
                   11565:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   11566:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  11567:   
1.218     brouard  11568:   /* agelim=AGESUP; */
1.289     brouard  11569:   ageminl=AGEINF; /* was 30 */
1.218     brouard  11570:   hstepm=stepsize*YEARM; /* Every year of age */
                   11571:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   11572:   
                   11573:   /* hstepm=1;   aff par mois*/
                   11574:   pstamp(ficrespijb);
1.255     brouard  11575:   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  11576:   i1= pow(2,cptcoveff);
1.218     brouard  11577:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11578:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   11579:   /*   k=k+1;  */
1.238     brouard  11580:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11581:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  11582:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  11583:        continue;
                   11584:       fprintf(ficrespijb,"\n#****** ");
                   11585:       for(j=1;j<=cptcoveff;j++)
1.332   ! brouard  11586:        fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.238     brouard  11587:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332   ! brouard  11588:        fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
1.238     brouard  11589:       }
                   11590:       fprintf(ficrespijb,"******\n");
1.264     brouard  11591:       if(invalidvarcomb[k]){  /* Is it necessary here? */
1.238     brouard  11592:        fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   11593:        continue;
                   11594:       }
                   11595:       
                   11596:       /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   11597:       for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   11598:        /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
1.297     brouard  11599:        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 */
                   11600:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
1.238     brouard  11601:        
                   11602:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
                   11603:        
1.266     brouard  11604:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   11605:        /* and memory limitations if stepm is small */
                   11606: 
1.238     brouard  11607:        /* oldm=oldms;savm=savms; */
                   11608:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.325     brouard  11609:        hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);/* Bug valgrind */
1.238     brouard  11610:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
1.255     brouard  11611:        fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
1.217     brouard  11612:        for(i=1; i<=nlstate;i++)
                   11613:          for(j=1; j<=nlstate+ndeath;j++)
1.238     brouard  11614:            fprintf(ficrespijb," %1d-%1d",i,j);
1.217     brouard  11615:        fprintf(ficrespijb,"\n");
1.238     brouard  11616:        for (h=0; h<=nhstepm; h++){
                   11617:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   11618:          fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   11619:          /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
                   11620:          for(i=1; i<=nlstate;i++)
                   11621:            for(j=1; j<=nlstate+ndeath;j++)
1.325     brouard  11622:              fprintf(ficrespijb," %.5f", p3mat[i][j][h]);/* Bug valgrind */
1.238     brouard  11623:          fprintf(ficrespijb,"\n");
                   11624:        }
                   11625:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11626:        fprintf(ficrespijb,"\n");
                   11627:       } /* end age deb */
                   11628:     } /* end combination */
                   11629:   } /* end nres */
1.218     brouard  11630:   return 0;
                   11631:  } /*  hBijx */
1.217     brouard  11632: 
1.180     brouard  11633: 
1.136     brouard  11634: /***********************************************/
                   11635: /**************** Main Program *****************/
                   11636: /***********************************************/
                   11637: 
                   11638: int main(int argc, char *argv[])
                   11639: {
                   11640: #ifdef GSL
                   11641:   const gsl_multimin_fminimizer_type *T;
                   11642:   size_t iteri = 0, it;
                   11643:   int rval = GSL_CONTINUE;
                   11644:   int status = GSL_SUCCESS;
                   11645:   double ssval;
                   11646: #endif
                   11647:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  11648:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   11649:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  11650:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  11651:   int jj, ll, li, lj, lk;
1.136     brouard  11652:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  11653:   int num_filled;
1.136     brouard  11654:   int itimes;
                   11655:   int NDIM=2;
                   11656:   int vpopbased=0;
1.235     brouard  11657:   int nres=0;
1.258     brouard  11658:   int endishere=0;
1.277     brouard  11659:   int noffset=0;
1.274     brouard  11660:   int ncurrv=0; /* Temporary variable */
                   11661:   
1.164     brouard  11662:   char ca[32], cb[32];
1.136     brouard  11663:   /*  FILE *fichtm; *//* Html File */
                   11664:   /* FILE *ficgp;*/ /*Gnuplot File */
                   11665:   struct stat info;
1.191     brouard  11666:   double agedeb=0.;
1.194     brouard  11667: 
                   11668:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  11669:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  11670: 
1.165     brouard  11671:   double fret;
1.191     brouard  11672:   double dum=0.; /* Dummy variable */
1.136     brouard  11673:   double ***p3mat;
1.218     brouard  11674:   /* double ***mobaverage; */
1.319     brouard  11675:   double wald;
1.164     brouard  11676: 
                   11677:   char line[MAXLINE];
1.197     brouard  11678:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   11679: 
1.234     brouard  11680:   char  modeltemp[MAXLINE];
1.332   ! brouard  11681:   char resultline[MAXLINE], resultlineori[MAXLINE];
1.230     brouard  11682:   
1.136     brouard  11683:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  11684:   char *tok, *val; /* pathtot */
1.290     brouard  11685:   int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs declared globally ;*/
1.195     brouard  11686:   int c,  h , cpt, c2;
1.191     brouard  11687:   int jl=0;
                   11688:   int i1, j1, jk, stepsize=0;
1.194     brouard  11689:   int count=0;
                   11690: 
1.164     brouard  11691:   int *tab; 
1.136     brouard  11692:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  11693:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   11694:   /* double anprojf, mprojf, jprojf; */
                   11695:   /* double jintmean,mintmean,aintmean;   */
                   11696:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   11697:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   11698:   double yrfproj= 10.0; /* Number of years of forward projections */
                   11699:   double yrbproj= 10.0; /* Number of years of backward projections */
                   11700:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  11701:   int mobilav=0,popforecast=0;
1.191     brouard  11702:   int hstepm=0, nhstepm=0;
1.136     brouard  11703:   int agemortsup;
                   11704:   float  sumlpop=0.;
                   11705:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   11706:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   11707: 
1.191     brouard  11708:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  11709:   double ftolpl=FTOL;
                   11710:   double **prlim;
1.217     brouard  11711:   double **bprlim;
1.317     brouard  11712:   double ***param; /* Matrix of parameters, param[i][j][k] param=ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel) 
                   11713:                     state of origin, state of destination including death, for each covariate: constante, age, and V1 V2 etc. */
1.251     brouard  11714:   double ***paramstart; /* Matrix of starting parameter values */
                   11715:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  11716:   double **matcov; /* Matrix of covariance */
1.203     brouard  11717:   double **hess; /* Hessian matrix */
1.136     brouard  11718:   double ***delti3; /* Scale */
                   11719:   double *delti; /* Scale */
                   11720:   double ***eij, ***vareij;
                   11721:   double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  11722: 
1.136     brouard  11723:   double *epj, vepp;
1.164     brouard  11724: 
1.273     brouard  11725:   double dateprev1, dateprev2;
1.296     brouard  11726:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   11727:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   11728: 
1.217     brouard  11729: 
1.136     brouard  11730:   double **ximort;
1.145     brouard  11731:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  11732:   int *dcwave;
                   11733: 
1.164     brouard  11734:   char z[1]="c";
1.136     brouard  11735: 
                   11736:   /*char  *strt;*/
                   11737:   char strtend[80];
1.126     brouard  11738: 
1.164     brouard  11739: 
1.126     brouard  11740: /*   setlocale (LC_ALL, ""); */
                   11741: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   11742: /*   textdomain (PACKAGE); */
                   11743: /*   setlocale (LC_CTYPE, ""); */
                   11744: /*   setlocale (LC_MESSAGES, ""); */
                   11745: 
                   11746:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  11747:   rstart_time = time(NULL);  
                   11748:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   11749:   start_time = *localtime(&rstart_time);
1.126     brouard  11750:   curr_time=start_time;
1.157     brouard  11751:   /*tml = *localtime(&start_time.tm_sec);*/
                   11752:   /* strcpy(strstart,asctime(&tml)); */
                   11753:   strcpy(strstart,asctime(&start_time));
1.126     brouard  11754: 
                   11755: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  11756: /*  tp.tm_sec = tp.tm_sec +86400; */
                   11757: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  11758: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   11759: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   11760: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  11761: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  11762: /*   strt=asctime(&tmg); */
                   11763: /*   printf("Time(after) =%s",strstart);  */
                   11764: /*  (void) time (&time_value);
                   11765: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   11766: *  tm = *localtime(&time_value);
                   11767: *  strstart=asctime(&tm);
                   11768: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   11769: */
                   11770: 
                   11771:   nberr=0; /* Number of errors and warnings */
                   11772:   nbwarn=0;
1.184     brouard  11773: #ifdef WIN32
                   11774:   _getcwd(pathcd, size);
                   11775: #else
1.126     brouard  11776:   getcwd(pathcd, size);
1.184     brouard  11777: #endif
1.191     brouard  11778:   syscompilerinfo(0);
1.196     brouard  11779:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  11780:   if(argc <=1){
                   11781:     printf("\nEnter the parameter file name: ");
1.205     brouard  11782:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   11783:       printf("ERROR Empty parameter file name\n");
                   11784:       goto end;
                   11785:     }
1.126     brouard  11786:     i=strlen(pathr);
                   11787:     if(pathr[i-1]=='\n')
                   11788:       pathr[i-1]='\0';
1.156     brouard  11789:     i=strlen(pathr);
1.205     brouard  11790:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  11791:       pathr[i-1]='\0';
1.205     brouard  11792:     }
                   11793:     i=strlen(pathr);
                   11794:     if( i==0 ){
                   11795:       printf("ERROR Empty parameter file name\n");
                   11796:       goto end;
                   11797:     }
                   11798:     for (tok = pathr; tok != NULL; ){
1.126     brouard  11799:       printf("Pathr |%s|\n",pathr);
                   11800:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   11801:       printf("val= |%s| pathr=%s\n",val,pathr);
                   11802:       strcpy (pathtot, val);
                   11803:       if(pathr[0] == '\0') break; /* Dirty */
                   11804:     }
                   11805:   }
1.281     brouard  11806:   else if (argc<=2){
                   11807:     strcpy(pathtot,argv[1]);
                   11808:   }
1.126     brouard  11809:   else{
                   11810:     strcpy(pathtot,argv[1]);
1.281     brouard  11811:     strcpy(z,argv[2]);
                   11812:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  11813:   }
                   11814:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   11815:   /*cygwin_split_path(pathtot,path,optionfile);
                   11816:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   11817:   /* cutv(path,optionfile,pathtot,'\\');*/
                   11818: 
                   11819:   /* Split argv[0], imach program to get pathimach */
                   11820:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   11821:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   11822:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   11823:  /*   strcpy(pathimach,argv[0]); */
                   11824:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   11825:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   11826:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  11827: #ifdef WIN32
                   11828:   _chdir(path); /* Can be a relative path */
                   11829:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   11830: #else
1.126     brouard  11831:   chdir(path); /* Can be a relative path */
1.184     brouard  11832:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   11833: #endif
                   11834:   printf("Current directory %s!\n",pathcd);
1.126     brouard  11835:   strcpy(command,"mkdir ");
                   11836:   strcat(command,optionfilefiname);
                   11837:   if((outcmd=system(command)) != 0){
1.169     brouard  11838:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  11839:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   11840:     /* fclose(ficlog); */
                   11841: /*     exit(1); */
                   11842:   }
                   11843: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   11844: /*     perror("mkdir"); */
                   11845: /*   } */
                   11846: 
                   11847:   /*-------- arguments in the command line --------*/
                   11848: 
1.186     brouard  11849:   /* Main Log file */
1.126     brouard  11850:   strcat(filelog, optionfilefiname);
                   11851:   strcat(filelog,".log");    /* */
                   11852:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   11853:     printf("Problem with logfile %s\n",filelog);
                   11854:     goto end;
                   11855:   }
                   11856:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  11857:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  11858:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   11859:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   11860:  path=%s \n\
                   11861:  optionfile=%s\n\
                   11862:  optionfilext=%s\n\
1.156     brouard  11863:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  11864: 
1.197     brouard  11865:   syscompilerinfo(1);
1.167     brouard  11866: 
1.126     brouard  11867:   printf("Local time (at start):%s",strstart);
                   11868:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   11869:   fflush(ficlog);
                   11870: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  11871: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  11872: 
                   11873:   /* */
                   11874:   strcpy(fileres,"r");
                   11875:   strcat(fileres, optionfilefiname);
1.201     brouard  11876:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  11877:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  11878:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  11879: 
1.186     brouard  11880:   /* Main ---------arguments file --------*/
1.126     brouard  11881: 
                   11882:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  11883:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   11884:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  11885:     fflush(ficlog);
1.149     brouard  11886:     /* goto end; */
                   11887:     exit(70); 
1.126     brouard  11888:   }
                   11889: 
                   11890:   strcpy(filereso,"o");
1.201     brouard  11891:   strcat(filereso,fileresu);
1.126     brouard  11892:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   11893:     printf("Problem with Output resultfile: %s\n", filereso);
                   11894:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   11895:     fflush(ficlog);
                   11896:     goto end;
                   11897:   }
1.278     brouard  11898:       /*-------- Rewriting parameter file ----------*/
                   11899:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   11900:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   11901:   strcat(rfileres,".");    /* */
                   11902:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   11903:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   11904:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   11905:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   11906:     fflush(ficlog);
                   11907:     goto end;
                   11908:   }
                   11909:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  11910: 
1.278     brouard  11911:                                      
1.126     brouard  11912:   /* Reads comments: lines beginning with '#' */
                   11913:   numlinepar=0;
1.277     brouard  11914:   /* Is it a BOM UTF-8 Windows file? */
                   11915:   /* First parameter line */
1.197     brouard  11916:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  11917:     noffset=0;
                   11918:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   11919:     {
                   11920:       noffset=noffset+3;
                   11921:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   11922:     }
1.302     brouard  11923: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   11924:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
1.277     brouard  11925:     {
                   11926:       noffset=noffset+2;
                   11927:       printf("# File is an UTF16BE BOM file\n");
                   11928:     }
                   11929:     else if( line[0] == 0 && line[1] == 0)
                   11930:     {
                   11931:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   11932:        noffset=noffset+4;
                   11933:        printf("# File is an UTF16BE BOM file\n");
                   11934:       }
                   11935:     } else{
                   11936:       ;/*printf(" Not a BOM file\n");*/
                   11937:     }
                   11938:   
1.197     brouard  11939:     /* If line starts with a # it is a comment */
1.277     brouard  11940:     if (line[noffset] == '#') {
1.197     brouard  11941:       numlinepar++;
                   11942:       fputs(line,stdout);
                   11943:       fputs(line,ficparo);
1.278     brouard  11944:       fputs(line,ficres);
1.197     brouard  11945:       fputs(line,ficlog);
                   11946:       continue;
                   11947:     }else
                   11948:       break;
                   11949:   }
                   11950:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   11951:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   11952:     if (num_filled != 5) {
                   11953:       printf("Should be 5 parameters\n");
1.283     brouard  11954:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  11955:     }
1.126     brouard  11956:     numlinepar++;
1.197     brouard  11957:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  11958:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   11959:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   11960:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  11961:   }
                   11962:   /* Second parameter line */
                   11963:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  11964:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   11965:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  11966:     if (line[0] == '#') {
                   11967:       numlinepar++;
1.283     brouard  11968:       printf("%s",line);
                   11969:       fprintf(ficres,"%s",line);
                   11970:       fprintf(ficparo,"%s",line);
                   11971:       fprintf(ficlog,"%s",line);
1.197     brouard  11972:       continue;
                   11973:     }else
                   11974:       break;
                   11975:   }
1.223     brouard  11976:   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", \
                   11977:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   11978:     if (num_filled != 11) {
                   11979:       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  11980:       printf("but line=%s\n",line);
1.283     brouard  11981:       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");
                   11982:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  11983:     }
1.286     brouard  11984:     if( lastpass > maxwav){
                   11985:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   11986:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   11987:       fflush(ficlog);
                   11988:       goto end;
                   11989:     }
                   11990:       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  11991:     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  11992:     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  11993:     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  11994:   }
1.203     brouard  11995:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  11996:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  11997:   /* Third parameter line */
                   11998:   while(fgets(line, MAXLINE, ficpar)) {
                   11999:     /* If line starts with a # it is a comment */
                   12000:     if (line[0] == '#') {
                   12001:       numlinepar++;
1.283     brouard  12002:       printf("%s",line);
                   12003:       fprintf(ficres,"%s",line);
                   12004:       fprintf(ficparo,"%s",line);
                   12005:       fprintf(ficlog,"%s",line);
1.197     brouard  12006:       continue;
                   12007:     }else
                   12008:       break;
                   12009:   }
1.201     brouard  12010:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
1.279     brouard  12011:     if (num_filled != 1){
1.302     brouard  12012:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   12013:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
1.197     brouard  12014:       model[0]='\0';
                   12015:       goto end;
                   12016:     }
                   12017:     else{
                   12018:       if (model[0]=='+'){
                   12019:        for(i=1; i<=strlen(model);i++)
                   12020:          modeltemp[i-1]=model[i];
1.201     brouard  12021:        strcpy(model,modeltemp); 
1.197     brouard  12022:       }
                   12023:     }
1.199     brouard  12024:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  12025:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  12026:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   12027:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   12028:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  12029:   }
                   12030:   /* 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); */
                   12031:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   12032:   /* 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  12033:   /* 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); */
                   12034:   /* 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  12035:   fflush(ficlog);
1.190     brouard  12036:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   12037:   if(model[0]=='#'){
1.279     brouard  12038:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   12039:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   12040:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  12041:     if(mle != -1){
1.279     brouard  12042:       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  12043:       exit(1);
                   12044:     }
                   12045:   }
1.126     brouard  12046:   while((c=getc(ficpar))=='#' && c!= EOF){
                   12047:     ungetc(c,ficpar);
                   12048:     fgets(line, MAXLINE, ficpar);
                   12049:     numlinepar++;
1.195     brouard  12050:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   12051:       z[0]=line[1];
                   12052:     }
                   12053:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  12054:     fputs(line, stdout);
                   12055:     //puts(line);
1.126     brouard  12056:     fputs(line,ficparo);
                   12057:     fputs(line,ficlog);
                   12058:   }
                   12059:   ungetc(c,ficpar);
                   12060: 
                   12061:    
1.290     brouard  12062:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   12063:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   12064:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
                   12065:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /**< Time varying covariate (dummy and quantitative)*/
1.136     brouard  12066:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   12067:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   12068:      v1+v2*age+v2*v3 makes cptcovn = 3
                   12069:   */
                   12070:   if (strlen(model)>1) 
1.187     brouard  12071:     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  12072:   else
1.187     brouard  12073:     ncovmodel=2; /* Constant and age */
1.133     brouard  12074:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   12075:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  12076:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   12077:     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);
                   12078:     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);
                   12079:     fflush(stdout);
                   12080:     fclose (ficlog);
                   12081:     goto end;
                   12082:   }
1.126     brouard  12083:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   12084:   delti=delti3[1][1];
                   12085:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   12086:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  12087: /* We could also provide initial parameters values giving by simple logistic regression 
                   12088:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   12089:       /* for(i=1;i<nlstate;i++){ */
                   12090:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   12091:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   12092:       /* } */
1.126     brouard  12093:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  12094:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   12095:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  12096:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   12097:     fclose (ficparo);
                   12098:     fclose (ficlog);
                   12099:     goto end;
                   12100:     exit(0);
1.220     brouard  12101:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  12102:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  12103:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   12104:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  12105:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   12106:     matcov=matrix(1,npar,1,npar);
1.203     brouard  12107:     hess=matrix(1,npar,1,npar);
1.220     brouard  12108:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  12109:     /* Read guessed parameters */
1.126     brouard  12110:     /* Reads comments: lines beginning with '#' */
                   12111:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12112:       ungetc(c,ficpar);
                   12113:       fgets(line, MAXLINE, ficpar);
                   12114:       numlinepar++;
1.141     brouard  12115:       fputs(line,stdout);
1.126     brouard  12116:       fputs(line,ficparo);
                   12117:       fputs(line,ficlog);
                   12118:     }
                   12119:     ungetc(c,ficpar);
                   12120:     
                   12121:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  12122:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  12123:     for(i=1; i <=nlstate; i++){
1.234     brouard  12124:       j=0;
1.126     brouard  12125:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  12126:        if(jj==i) continue;
                   12127:        j++;
1.292     brouard  12128:        while((c=getc(ficpar))=='#' && c!= EOF){
                   12129:          ungetc(c,ficpar);
                   12130:          fgets(line, MAXLINE, ficpar);
                   12131:          numlinepar++;
                   12132:          fputs(line,stdout);
                   12133:          fputs(line,ficparo);
                   12134:          fputs(line,ficlog);
                   12135:        }
                   12136:        ungetc(c,ficpar);
1.234     brouard  12137:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   12138:        if ((i1 != i) || (j1 != jj)){
                   12139:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  12140: It might be a problem of design; if ncovcol and the model are correct\n \
                   12141: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  12142:          exit(1);
                   12143:        }
                   12144:        fprintf(ficparo,"%1d%1d",i1,j1);
                   12145:        if(mle==1)
                   12146:          printf("%1d%1d",i,jj);
                   12147:        fprintf(ficlog,"%1d%1d",i,jj);
                   12148:        for(k=1; k<=ncovmodel;k++){
                   12149:          fscanf(ficpar," %lf",&param[i][j][k]);
                   12150:          if(mle==1){
                   12151:            printf(" %lf",param[i][j][k]);
                   12152:            fprintf(ficlog," %lf",param[i][j][k]);
                   12153:          }
                   12154:          else
                   12155:            fprintf(ficlog," %lf",param[i][j][k]);
                   12156:          fprintf(ficparo," %lf",param[i][j][k]);
                   12157:        }
                   12158:        fscanf(ficpar,"\n");
                   12159:        numlinepar++;
                   12160:        if(mle==1)
                   12161:          printf("\n");
                   12162:        fprintf(ficlog,"\n");
                   12163:        fprintf(ficparo,"\n");
1.126     brouard  12164:       }
                   12165:     }  
                   12166:     fflush(ficlog);
1.234     brouard  12167:     
1.251     brouard  12168:     /* Reads parameters values */
1.126     brouard  12169:     p=param[1][1];
1.251     brouard  12170:     pstart=paramstart[1][1];
1.126     brouard  12171:     
                   12172:     /* Reads comments: lines beginning with '#' */
                   12173:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12174:       ungetc(c,ficpar);
                   12175:       fgets(line, MAXLINE, ficpar);
                   12176:       numlinepar++;
1.141     brouard  12177:       fputs(line,stdout);
1.126     brouard  12178:       fputs(line,ficparo);
                   12179:       fputs(line,ficlog);
                   12180:     }
                   12181:     ungetc(c,ficpar);
                   12182: 
                   12183:     for(i=1; i <=nlstate; i++){
                   12184:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  12185:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   12186:        if ( (i1-i) * (j1-j) != 0){
                   12187:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   12188:          exit(1);
                   12189:        }
                   12190:        printf("%1d%1d",i,j);
                   12191:        fprintf(ficparo,"%1d%1d",i1,j1);
                   12192:        fprintf(ficlog,"%1d%1d",i1,j1);
                   12193:        for(k=1; k<=ncovmodel;k++){
                   12194:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   12195:          printf(" %le",delti3[i][j][k]);
                   12196:          fprintf(ficparo," %le",delti3[i][j][k]);
                   12197:          fprintf(ficlog," %le",delti3[i][j][k]);
                   12198:        }
                   12199:        fscanf(ficpar,"\n");
                   12200:        numlinepar++;
                   12201:        printf("\n");
                   12202:        fprintf(ficparo,"\n");
                   12203:        fprintf(ficlog,"\n");
1.126     brouard  12204:       }
                   12205:     }
                   12206:     fflush(ficlog);
1.234     brouard  12207:     
1.145     brouard  12208:     /* Reads covariance matrix */
1.126     brouard  12209:     delti=delti3[1][1];
1.220     brouard  12210:                
                   12211:                
1.126     brouard  12212:     /* 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  12213:                
1.126     brouard  12214:     /* Reads comments: lines beginning with '#' */
                   12215:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12216:       ungetc(c,ficpar);
                   12217:       fgets(line, MAXLINE, ficpar);
                   12218:       numlinepar++;
1.141     brouard  12219:       fputs(line,stdout);
1.126     brouard  12220:       fputs(line,ficparo);
                   12221:       fputs(line,ficlog);
                   12222:     }
                   12223:     ungetc(c,ficpar);
1.220     brouard  12224:                
1.126     brouard  12225:     matcov=matrix(1,npar,1,npar);
1.203     brouard  12226:     hess=matrix(1,npar,1,npar);
1.131     brouard  12227:     for(i=1; i <=npar; i++)
                   12228:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  12229:                
1.194     brouard  12230:     /* Scans npar lines */
1.126     brouard  12231:     for(i=1; i <=npar; i++){
1.226     brouard  12232:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  12233:       if(count != 3){
1.226     brouard  12234:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  12235: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   12236: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  12237:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  12238: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   12239: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  12240:        exit(1);
1.220     brouard  12241:       }else{
1.226     brouard  12242:        if(mle==1)
                   12243:          printf("%1d%1d%d",i1,j1,jk);
                   12244:       }
                   12245:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   12246:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  12247:       for(j=1; j <=i; j++){
1.226     brouard  12248:        fscanf(ficpar," %le",&matcov[i][j]);
                   12249:        if(mle==1){
                   12250:          printf(" %.5le",matcov[i][j]);
                   12251:        }
                   12252:        fprintf(ficlog," %.5le",matcov[i][j]);
                   12253:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  12254:       }
                   12255:       fscanf(ficpar,"\n");
                   12256:       numlinepar++;
                   12257:       if(mle==1)
1.220     brouard  12258:                                printf("\n");
1.126     brouard  12259:       fprintf(ficlog,"\n");
                   12260:       fprintf(ficparo,"\n");
                   12261:     }
1.194     brouard  12262:     /* End of read covariance matrix npar lines */
1.126     brouard  12263:     for(i=1; i <=npar; i++)
                   12264:       for(j=i+1;j<=npar;j++)
1.226     brouard  12265:        matcov[i][j]=matcov[j][i];
1.126     brouard  12266:     
                   12267:     if(mle==1)
                   12268:       printf("\n");
                   12269:     fprintf(ficlog,"\n");
                   12270:     
                   12271:     fflush(ficlog);
                   12272:     
                   12273:   }    /* End of mle != -3 */
1.218     brouard  12274:   
1.186     brouard  12275:   /*  Main data
                   12276:    */
1.290     brouard  12277:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   12278:   /* num=lvector(1,n); */
                   12279:   /* moisnais=vector(1,n); */
                   12280:   /* annais=vector(1,n); */
                   12281:   /* moisdc=vector(1,n); */
                   12282:   /* andc=vector(1,n); */
                   12283:   /* weight=vector(1,n); */
                   12284:   /* agedc=vector(1,n); */
                   12285:   /* cod=ivector(1,n); */
                   12286:   /* for(i=1;i<=n;i++){ */
                   12287:   num=lvector(firstobs,lastobs);
                   12288:   moisnais=vector(firstobs,lastobs);
                   12289:   annais=vector(firstobs,lastobs);
                   12290:   moisdc=vector(firstobs,lastobs);
                   12291:   andc=vector(firstobs,lastobs);
                   12292:   weight=vector(firstobs,lastobs);
                   12293:   agedc=vector(firstobs,lastobs);
                   12294:   cod=ivector(firstobs,lastobs);
                   12295:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  12296:     num[i]=0;
                   12297:     moisnais[i]=0;
                   12298:     annais[i]=0;
                   12299:     moisdc[i]=0;
                   12300:     andc[i]=0;
                   12301:     agedc[i]=0;
                   12302:     cod[i]=0;
                   12303:     weight[i]=1.0; /* Equal weights, 1 by default */
                   12304:   }
1.290     brouard  12305:   mint=matrix(1,maxwav,firstobs,lastobs);
                   12306:   anint=matrix(1,maxwav,firstobs,lastobs);
1.325     brouard  12307:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */
                   12308:   printf("BUG ncovmodel=%d NCOVMAX=%d 2**ncovmodel=%f BUG\n",ncovmodel,NCOVMAX,pow(2,ncovmodel));
1.126     brouard  12309:   tab=ivector(1,NCOVMAX);
1.144     brouard  12310:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  12311:   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  12312: 
1.136     brouard  12313:   /* Reads data from file datafile */
                   12314:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   12315:     goto end;
                   12316: 
                   12317:   /* Calculation of the number of parameters from char model */
1.234     brouard  12318:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  12319:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   12320:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   12321:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   12322:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  12323:   */
                   12324:   
                   12325:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   12326:   TvarsDind=ivector(1,NCOVMAX); /*  */
1.330     brouard  12327:   TnsdVar=ivector(1,NCOVMAX); /*  */
1.234     brouard  12328:   TvarsD=ivector(1,NCOVMAX); /*  */
                   12329:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   12330:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  12331:   TvarF=ivector(1,NCOVMAX); /*  */
                   12332:   TvarFind=ivector(1,NCOVMAX); /*  */
                   12333:   TvarV=ivector(1,NCOVMAX); /*  */
                   12334:   TvarVind=ivector(1,NCOVMAX); /*  */
                   12335:   TvarA=ivector(1,NCOVMAX); /*  */
                   12336:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  12337:   TvarFD=ivector(1,NCOVMAX); /*  */
                   12338:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   12339:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   12340:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   12341:   TvarVD=ivector(1,NCOVMAX); /*  */
                   12342:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   12343:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   12344:   TvarVQind=ivector(1,NCOVMAX); /*  */
                   12345: 
1.230     brouard  12346:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  12347:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  12348:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   12349:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   12350:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.137     brouard  12351:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   12352:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   12353:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   12354:   */
                   12355:   /* For model-covariate k tells which data-covariate to use but
                   12356:     because this model-covariate is a construction we invent a new column
                   12357:     ncovcol + k1
                   12358:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   12359:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  12360:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   12361:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  12362:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   12363:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  12364:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  12365:   */
1.145     brouard  12366:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   12367:   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  12368:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   12369:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.330     brouard  12370:   Tvardk=imatrix(1,NCOVMAX,1,2);
1.145     brouard  12371:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  12372:                         4 covariates (3 plus signs)
                   12373:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
1.328     brouard  12374:                           */  
                   12375:   for(i=1;i<NCOVMAX;i++)
                   12376:     Tage[i]=0;
1.230     brouard  12377:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  12378:                                * individual dummy, fixed or varying:
                   12379:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   12380:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  12381:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   12382:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   12383:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   12384:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   12385:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  12386:                                * individual quantitative, fixed or varying:
                   12387:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   12388:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   12389:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.186     brouard  12390: /* Main decodemodel */
                   12391: 
1.187     brouard  12392: 
1.223     brouard  12393:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  12394:     goto end;
                   12395: 
1.137     brouard  12396:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   12397:     nbwarn++;
                   12398:     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); 
                   12399:     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); 
                   12400:   }
1.136     brouard  12401:     /*  if(mle==1){*/
1.137     brouard  12402:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   12403:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  12404:   }
                   12405: 
                   12406:     /*-calculation of age at interview from date of interview and age at death -*/
                   12407:   agev=matrix(1,maxwav,1,imx);
                   12408: 
                   12409:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   12410:     goto end;
                   12411: 
1.126     brouard  12412: 
1.136     brouard  12413:   agegomp=(int)agemin;
1.290     brouard  12414:   free_vector(moisnais,firstobs,lastobs);
                   12415:   free_vector(annais,firstobs,lastobs);
1.126     brouard  12416:   /* free_matrix(mint,1,maxwav,1,n);
                   12417:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  12418:   /* free_vector(moisdc,1,n); */
                   12419:   /* free_vector(andc,1,n); */
1.145     brouard  12420:   /* */
                   12421:   
1.126     brouard  12422:   wav=ivector(1,imx);
1.214     brouard  12423:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   12424:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   12425:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   12426:   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.*/
                   12427:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   12428:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  12429:    
                   12430:   /* Concatenates waves */
1.214     brouard  12431:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   12432:      Death is a valid wave (if date is known).
                   12433:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   12434:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   12435:      and mw[mi+1][i]. dh depends on stepm.
                   12436:   */
                   12437: 
1.126     brouard  12438:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  12439:   /* Concatenates waves */
1.145     brouard  12440:  
1.290     brouard  12441:   free_vector(moisdc,firstobs,lastobs);
                   12442:   free_vector(andc,firstobs,lastobs);
1.215     brouard  12443: 
1.126     brouard  12444:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   12445:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   12446:   ncodemax[1]=1;
1.145     brouard  12447:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  12448:   cptcoveff=0;
1.220     brouard  12449:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
                   12450:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.227     brouard  12451:   }
                   12452:   
                   12453:   ncovcombmax=pow(2,cptcoveff);
                   12454:   invalidvarcomb=ivector(1, ncovcombmax); 
                   12455:   for(i=1;i<ncovcombmax;i++)
                   12456:     invalidvarcomb[i]=0;
                   12457:   
1.211     brouard  12458:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  12459:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  12460:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  12461:   
1.200     brouard  12462:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  12463:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  12464:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  12465:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   12466:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   12467:    * (currently 0 or 1) in the data.
                   12468:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   12469:    * corresponding modality (h,j).
                   12470:    */
                   12471: 
1.145     brouard  12472:   h=0;
                   12473:   /*if (cptcovn > 0) */
1.126     brouard  12474:   m=pow(2,cptcoveff);
                   12475:  
1.144     brouard  12476:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  12477:           * For k=4 covariates, h goes from 1 to m=2**k
                   12478:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   12479:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.329     brouard  12480:           *     h\k   1     2     3     4   *  h-1\k-1  4  3  2  1          
                   12481:           *______________________________   *______________________
                   12482:           *     1 i=1 1 i=1 1 i=1 1 i=1 1   *     0     0  0  0  0 
                   12483:           *     2     2     1     1     1   *     1     0  0  0  1 
                   12484:           *     3 i=2 1     2     1     1   *     2     0  0  1  0 
                   12485:           *     4     2     2     1     1   *     3     0  0  1  1 
                   12486:           *     5 i=3 1 i=2 1     2     1   *     4     0  1  0  0 
                   12487:           *     6     2     1     2     1   *     5     0  1  0  1 
                   12488:           *     7 i=4 1     2     2     1   *     6     0  1  1  0 
                   12489:           *     8     2     2     2     1   *     7     0  1  1  1 
                   12490:           *     9 i=5 1 i=3 1 i=2 1     2   *     8     1  0  0  0 
                   12491:           *    10     2     1     1     2   *     9     1  0  0  1 
                   12492:           *    11 i=6 1     2     1     2   *    10     1  0  1  0 
                   12493:           *    12     2     2     1     2   *    11     1  0  1  1 
                   12494:           *    13 i=7 1 i=4 1     2     2   *    12     1  1  0  0  
                   12495:           *    14     2     1     2     2   *    13     1  1  0  1 
                   12496:           *    15 i=8 1     2     2     2   *    14     1  1  1  0 
                   12497:           *    16     2     2     2     2   *    15     1  1  1  1          
                   12498:           */                                     
1.212     brouard  12499:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  12500:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   12501:      * and the value of each covariate?
                   12502:      * V1=1, V2=1, V3=2, V4=1 ?
                   12503:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   12504:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   12505:      * In order to get the real value in the data, we use nbcode
                   12506:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   12507:      * We are keeping this crazy system in order to be able (in the future?) 
                   12508:      * to have more than 2 values (0 or 1) for a covariate.
                   12509:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   12510:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   12511:      *              bbbbbbbb
                   12512:      *              76543210     
                   12513:      *   h-1        00000101 (6-1=5)
1.219     brouard  12514:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  12515:      *           &
                   12516:      *     1        00000001 (1)
1.219     brouard  12517:      *              00000000        = 1 & ((h-1) >> (k-1))
                   12518:      *          +1= 00000001 =1 
1.211     brouard  12519:      *
                   12520:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   12521:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   12522:      *    >>k'            11
                   12523:      *          &   00000001
                   12524:      *            = 00000001
                   12525:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   12526:      * Reverse h=6 and m=16?
                   12527:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   12528:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   12529:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   12530:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   12531:      * V3=decodtabm(14,3,2**4)=2
                   12532:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   12533:      *(h-1) >> (j-1)    0011 =13 >> 2
                   12534:      *          &1 000000001
                   12535:      *           = 000000001
                   12536:      *         +1= 000000010 =2
                   12537:      *                  2211
                   12538:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   12539:      *                  V3=2
1.220     brouard  12540:                 * codtabm and decodtabm are identical
1.211     brouard  12541:      */
                   12542: 
1.145     brouard  12543: 
                   12544:  free_ivector(Ndum,-1,NCOVMAX);
                   12545: 
                   12546: 
1.126     brouard  12547:     
1.186     brouard  12548:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  12549:   strcpy(optionfilegnuplot,optionfilefiname);
                   12550:   if(mle==-3)
1.201     brouard  12551:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  12552:   strcat(optionfilegnuplot,".gp");
                   12553: 
                   12554:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   12555:     printf("Problem with file %s",optionfilegnuplot);
                   12556:   }
                   12557:   else{
1.204     brouard  12558:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  12559:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  12560:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   12561:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  12562:   }
                   12563:   /*  fclose(ficgp);*/
1.186     brouard  12564: 
                   12565: 
                   12566:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  12567: 
                   12568:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   12569:   if(mle==-3)
1.201     brouard  12570:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  12571:   strcat(optionfilehtm,".htm");
                   12572:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  12573:     printf("Problem with %s \n",optionfilehtm);
                   12574:     exit(0);
1.126     brouard  12575:   }
                   12576: 
                   12577:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   12578:   strcat(optionfilehtmcov,"-cov.htm");
                   12579:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   12580:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   12581:   }
                   12582:   else{
                   12583:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   12584: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  12585: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  12586:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   12587:   }
                   12588: 
1.332   ! brouard  12589:   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-2022-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  12590: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   12591: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  12592: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  12593: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  12594: \n\
                   12595: <hr  size=\"2\" color=\"#EC5E5E\">\
                   12596:  <ul><li><h4>Parameter files</h4>\n\
                   12597:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   12598:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   12599:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   12600:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   12601:  - Date and time at start: %s</ul>\n",\
                   12602:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   12603:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   12604:          fileres,fileres,\
                   12605:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   12606:   fflush(fichtm);
                   12607: 
                   12608:   strcpy(pathr,path);
                   12609:   strcat(pathr,optionfilefiname);
1.184     brouard  12610: #ifdef WIN32
                   12611:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   12612: #else
1.126     brouard  12613:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  12614: #endif
                   12615:          
1.126     brouard  12616:   
1.220     brouard  12617:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   12618:                 and for any valid combination of covariates
1.126     brouard  12619:      and prints on file fileres'p'. */
1.251     brouard  12620:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  12621:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  12622: 
                   12623:   fprintf(fichtm,"\n");
1.286     brouard  12624:   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  12625:          ftol, stepm);
                   12626:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   12627:   ncurrv=1;
                   12628:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   12629:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   12630:   ncurrv=i;
                   12631:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  12632:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  12633:   ncurrv=i;
                   12634:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  12635:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  12636:   ncurrv=i;
                   12637:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   12638:   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", \
                   12639:           nlstate, ndeath, maxwav, mle, weightopt);
                   12640: 
                   12641:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   12642: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   12643: 
                   12644:   
1.317     brouard  12645:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Number of (used) observations=%d <br>\n\
1.126     brouard  12646: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   12647: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  12648:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  12649:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  12650:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   12651:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   12652:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   12653:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  12654: 
1.126     brouard  12655:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   12656:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   12657:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   12658: 
                   12659:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  12660:   /* For mortality only */
1.126     brouard  12661:   if (mle==-3){
1.136     brouard  12662:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  12663:     for(i=1;i<=NDIM;i++)
                   12664:       for(j=1;j<=NDIM;j++)
                   12665:        ximort[i][j]=0.;
1.186     brouard  12666:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  12667:     cens=ivector(firstobs,lastobs);
                   12668:     ageexmed=vector(firstobs,lastobs);
                   12669:     agecens=vector(firstobs,lastobs);
                   12670:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  12671:                
1.126     brouard  12672:     for (i=1; i<=imx; i++){
                   12673:       dcwave[i]=-1;
                   12674:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  12675:        if (s[m][i]>nlstate) {
                   12676:          dcwave[i]=m;
                   12677:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   12678:          break;
                   12679:        }
1.126     brouard  12680:     }
1.226     brouard  12681:     
1.126     brouard  12682:     for (i=1; i<=imx; i++) {
                   12683:       if (wav[i]>0){
1.226     brouard  12684:        ageexmed[i]=agev[mw[1][i]][i];
                   12685:        j=wav[i];
                   12686:        agecens[i]=1.; 
                   12687:        
                   12688:        if (ageexmed[i]> 1 && wav[i] > 0){
                   12689:          agecens[i]=agev[mw[j][i]][i];
                   12690:          cens[i]= 1;
                   12691:        }else if (ageexmed[i]< 1) 
                   12692:          cens[i]= -1;
                   12693:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   12694:          cens[i]=0 ;
1.126     brouard  12695:       }
                   12696:       else cens[i]=-1;
                   12697:     }
                   12698:     
                   12699:     for (i=1;i<=NDIM;i++) {
                   12700:       for (j=1;j<=NDIM;j++)
1.226     brouard  12701:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  12702:     }
                   12703:     
1.302     brouard  12704:     p[1]=0.0268; p[NDIM]=0.083;
                   12705:     /* printf("%lf %lf", p[1], p[2]); */
1.126     brouard  12706:     
                   12707:     
1.136     brouard  12708: #ifdef GSL
                   12709:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  12710: #else
1.126     brouard  12711:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  12712: #endif
1.201     brouard  12713:     strcpy(filerespow,"POW-MORT_"); 
                   12714:     strcat(filerespow,fileresu);
1.126     brouard  12715:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   12716:       printf("Problem with resultfile: %s\n", filerespow);
                   12717:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   12718:     }
1.136     brouard  12719: #ifdef GSL
                   12720:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  12721: #else
1.126     brouard  12722:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  12723: #endif
1.126     brouard  12724:     /*  for (i=1;i<=nlstate;i++)
                   12725:        for(j=1;j<=nlstate+ndeath;j++)
                   12726:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   12727:     */
                   12728:     fprintf(ficrespow,"\n");
1.136     brouard  12729: #ifdef GSL
                   12730:     /* gsl starts here */ 
                   12731:     T = gsl_multimin_fminimizer_nmsimplex;
                   12732:     gsl_multimin_fminimizer *sfm = NULL;
                   12733:     gsl_vector *ss, *x;
                   12734:     gsl_multimin_function minex_func;
                   12735: 
                   12736:     /* Initial vertex size vector */
                   12737:     ss = gsl_vector_alloc (NDIM);
                   12738:     
                   12739:     if (ss == NULL){
                   12740:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   12741:     }
                   12742:     /* Set all step sizes to 1 */
                   12743:     gsl_vector_set_all (ss, 0.001);
                   12744: 
                   12745:     /* Starting point */
1.126     brouard  12746:     
1.136     brouard  12747:     x = gsl_vector_alloc (NDIM);
                   12748:     
                   12749:     if (x == NULL){
                   12750:       gsl_vector_free(ss);
                   12751:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   12752:     }
                   12753:   
                   12754:     /* Initialize method and iterate */
                   12755:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  12756:     /*     gsl_vector_set(x, 0, 0.0268); */
                   12757:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  12758:     gsl_vector_set(x, 0, p[1]);
                   12759:     gsl_vector_set(x, 1, p[2]);
                   12760: 
                   12761:     minex_func.f = &gompertz_f;
                   12762:     minex_func.n = NDIM;
                   12763:     minex_func.params = (void *)&p; /* ??? */
                   12764:     
                   12765:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   12766:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   12767:     
                   12768:     printf("Iterations beginning .....\n\n");
                   12769:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   12770: 
                   12771:     iteri=0;
                   12772:     while (rval == GSL_CONTINUE){
                   12773:       iteri++;
                   12774:       status = gsl_multimin_fminimizer_iterate(sfm);
                   12775:       
                   12776:       if (status) printf("error: %s\n", gsl_strerror (status));
                   12777:       fflush(0);
                   12778:       
                   12779:       if (status) 
                   12780:         break;
                   12781:       
                   12782:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   12783:       ssval = gsl_multimin_fminimizer_size (sfm);
                   12784:       
                   12785:       if (rval == GSL_SUCCESS)
                   12786:         printf ("converged to a local maximum at\n");
                   12787:       
                   12788:       printf("%5d ", iteri);
                   12789:       for (it = 0; it < NDIM; it++){
                   12790:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   12791:       }
                   12792:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   12793:     }
                   12794:     
                   12795:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   12796:     
                   12797:     gsl_vector_free(x); /* initial values */
                   12798:     gsl_vector_free(ss); /* inital step size */
                   12799:     for (it=0; it<NDIM; it++){
                   12800:       p[it+1]=gsl_vector_get(sfm->x,it);
                   12801:       fprintf(ficrespow," %.12lf", p[it]);
                   12802:     }
                   12803:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   12804: #endif
                   12805: #ifdef POWELL
                   12806:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   12807: #endif  
1.126     brouard  12808:     fclose(ficrespow);
                   12809:     
1.203     brouard  12810:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  12811: 
                   12812:     for(i=1; i <=NDIM; i++)
                   12813:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  12814:                                matcov[i][j]=matcov[j][i];
1.126     brouard  12815:     
                   12816:     printf("\nCovariance matrix\n ");
1.203     brouard  12817:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  12818:     for(i=1; i <=NDIM; i++) {
                   12819:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  12820:                                printf("%f ",matcov[i][j]);
                   12821:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  12822:       }
1.203     brouard  12823:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  12824:     }
                   12825:     
                   12826:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  12827:     for (i=1;i<=NDIM;i++) {
1.126     brouard  12828:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  12829:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   12830:     }
1.302     brouard  12831:     lsurv=vector(agegomp,AGESUP);
                   12832:     lpop=vector(agegomp,AGESUP);
                   12833:     tpop=vector(agegomp,AGESUP);
1.126     brouard  12834:     lsurv[agegomp]=100000;
                   12835:     
                   12836:     for (k=agegomp;k<=AGESUP;k++) {
                   12837:       agemortsup=k;
                   12838:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   12839:     }
                   12840:     
                   12841:     for (k=agegomp;k<agemortsup;k++)
                   12842:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   12843:     
                   12844:     for (k=agegomp;k<agemortsup;k++){
                   12845:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   12846:       sumlpop=sumlpop+lpop[k];
                   12847:     }
                   12848:     
                   12849:     tpop[agegomp]=sumlpop;
                   12850:     for (k=agegomp;k<(agemortsup-3);k++){
                   12851:       /*  tpop[k+1]=2;*/
                   12852:       tpop[k+1]=tpop[k]-lpop[k];
                   12853:     }
                   12854:     
                   12855:     
                   12856:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   12857:     for (k=agegomp;k<(agemortsup-2);k++) 
                   12858:       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]);
                   12859:     
                   12860:     
                   12861:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  12862:                ageminpar=50;
                   12863:                agemaxpar=100;
1.194     brouard  12864:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   12865:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   12866: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12867: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   12868:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   12869: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12870: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  12871:     }else{
                   12872:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   12873:                        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  12874:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  12875:                }
1.201     brouard  12876:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  12877:                     stepm, weightopt,\
                   12878:                     model,imx,p,matcov,agemortsup);
                   12879:     
1.302     brouard  12880:     free_vector(lsurv,agegomp,AGESUP);
                   12881:     free_vector(lpop,agegomp,AGESUP);
                   12882:     free_vector(tpop,agegomp,AGESUP);
1.220     brouard  12883:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  12884:     free_ivector(dcwave,firstobs,lastobs);
                   12885:     free_vector(agecens,firstobs,lastobs);
                   12886:     free_vector(ageexmed,firstobs,lastobs);
                   12887:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  12888: #ifdef GSL
1.136     brouard  12889: #endif
1.186     brouard  12890:   } /* Endof if mle==-3 mortality only */
1.205     brouard  12891:   /* Standard  */
                   12892:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   12893:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   12894:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  12895:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  12896:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   12897:     for (k=1; k<=npar;k++)
                   12898:       printf(" %d %8.5f",k,p[k]);
                   12899:     printf("\n");
1.205     brouard  12900:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   12901:       /* mlikeli uses func not funcone */
1.247     brouard  12902:       /* for(i=1;i<nlstate;i++){ */
                   12903:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   12904:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   12905:       /* } */
1.205     brouard  12906:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   12907:     }
                   12908:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   12909:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   12910:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   12911:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   12912:     }
                   12913:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  12914:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   12915:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   12916:     for (k=1; k<=npar;k++)
                   12917:       printf(" %d %8.5f",k,p[k]);
                   12918:     printf("\n");
                   12919:     
                   12920:     /*--------- results files --------------*/
1.283     brouard  12921:     /* 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  12922:     
                   12923:     
                   12924:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  12925:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); /* Printing model equation */
1.126     brouard  12926:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  12927: 
                   12928:     printf("#model=  1      +     age ");
                   12929:     fprintf(ficres,"#model=  1      +     age ");
                   12930:     fprintf(ficlog,"#model=  1      +     age ");
                   12931:     fprintf(fichtm,"\n<ul><li> model=1+age+%s\n \
                   12932: </ul>", model);
                   12933: 
                   12934:     fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">\n");
                   12935:     fprintf(fichtm, "<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   12936:     if(nagesqr==1){
                   12937:       printf("  + age*age  ");
                   12938:       fprintf(ficres,"  + age*age  ");
                   12939:       fprintf(ficlog,"  + age*age  ");
                   12940:       fprintf(fichtm, "<th>+ age*age</th>");
                   12941:     }
                   12942:     for(j=1;j <=ncovmodel-2;j++){
                   12943:       if(Typevar[j]==0) {
                   12944:        printf("  +      V%d  ",Tvar[j]);
                   12945:        fprintf(ficres,"  +      V%d  ",Tvar[j]);
                   12946:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   12947:        fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   12948:       }else if(Typevar[j]==1) {
                   12949:        printf("  +    V%d*age ",Tvar[j]);
                   12950:        fprintf(ficres,"  +    V%d*age ",Tvar[j]);
                   12951:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   12952:        fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   12953:       }else if(Typevar[j]==2) {
                   12954:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   12955:        fprintf(ficres,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   12956:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   12957:        fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   12958:       }
                   12959:     }
                   12960:     printf("\n");
                   12961:     fprintf(ficres,"\n");
                   12962:     fprintf(ficlog,"\n");
                   12963:     fprintf(fichtm, "</tr>");
                   12964:     fprintf(fichtm, "\n");
                   12965:     
                   12966:     
1.126     brouard  12967:     for(i=1,jk=1; i <=nlstate; i++){
                   12968:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  12969:        if (k != i) {
1.319     brouard  12970:          fprintf(fichtm, "<tr>");
1.225     brouard  12971:          printf("%d%d ",i,k);
                   12972:          fprintf(ficlog,"%d%d ",i,k);
                   12973:          fprintf(ficres,"%1d%1d ",i,k);
1.319     brouard  12974:          fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  12975:          for(j=1; j <=ncovmodel; j++){
                   12976:            printf("%12.7f ",p[jk]);
                   12977:            fprintf(ficlog,"%12.7f ",p[jk]);
                   12978:            fprintf(ficres,"%12.7f ",p[jk]);
1.319     brouard  12979:            fprintf(fichtm, "<td>%12.7f</td>",p[jk]);
1.225     brouard  12980:            jk++; 
                   12981:          }
                   12982:          printf("\n");
                   12983:          fprintf(ficlog,"\n");
                   12984:          fprintf(ficres,"\n");
1.319     brouard  12985:          fprintf(fichtm, "</tr>\n");
1.225     brouard  12986:        }
1.126     brouard  12987:       }
                   12988:     }
1.319     brouard  12989:     /* fprintf(fichtm,"</tr>\n"); */
                   12990:     fprintf(fichtm,"</table>\n");
                   12991:     fprintf(fichtm, "\n");
                   12992: 
1.203     brouard  12993:     if(mle != 0){
                   12994:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  12995:       ftolhess=ftol; /* Usually correct */
1.203     brouard  12996:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   12997:       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");
                   12998:       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  12999:       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  13000:       fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">");
                   13001:       fprintf(fichtm, "\n<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   13002:       if(nagesqr==1){
                   13003:        printf("  + age*age  ");
                   13004:        fprintf(ficres,"  + age*age  ");
                   13005:        fprintf(ficlog,"  + age*age  ");
                   13006:        fprintf(fichtm, "<th>+ age*age</th>");
                   13007:       }
                   13008:       for(j=1;j <=ncovmodel-2;j++){
                   13009:        if(Typevar[j]==0) {
                   13010:          printf("  +      V%d  ",Tvar[j]);
                   13011:          fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   13012:        }else if(Typevar[j]==1) {
                   13013:          printf("  +    V%d*age ",Tvar[j]);
                   13014:          fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   13015:        }else if(Typevar[j]==2) {
                   13016:          fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13017:        }
                   13018:       }
                   13019:       fprintf(fichtm, "</tr>\n");
                   13020:  
1.203     brouard  13021:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  13022:        for(k=1; k <=(nlstate+ndeath); k++){
                   13023:          if (k != i) {
1.319     brouard  13024:            fprintf(fichtm, "<tr valign=top>");
1.225     brouard  13025:            printf("%d%d ",i,k);
                   13026:            fprintf(ficlog,"%d%d ",i,k);
1.319     brouard  13027:            fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  13028:            for(j=1; j <=ncovmodel; j++){
1.319     brouard  13029:              wald=p[jk]/sqrt(matcov[jk][jk]);
1.324     brouard  13030:              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]));
                   13031:              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  13032:              if(fabs(wald) > 1.96){
1.321     brouard  13033:                fprintf(fichtm, "<td><b>%12.7f</b></br> (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
1.319     brouard  13034:              }else{
                   13035:                fprintf(fichtm, "<td>%12.7f (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
                   13036:              }
1.324     brouard  13037:              fprintf(fichtm,"W=%8.3f</br>",wald);
1.319     brouard  13038:              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  13039:              jk++; 
                   13040:            }
                   13041:            printf("\n");
                   13042:            fprintf(ficlog,"\n");
1.319     brouard  13043:            fprintf(fichtm, "</tr>\n");
1.225     brouard  13044:          }
                   13045:        }
1.193     brouard  13046:       }
1.203     brouard  13047:     } /* end of hesscov and Wald tests */
1.319     brouard  13048:     fprintf(fichtm,"</table>\n");
1.225     brouard  13049:     
1.203     brouard  13050:     /*  */
1.126     brouard  13051:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   13052:     printf("# Scales (for hessian or gradient estimation)\n");
                   13053:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   13054:     for(i=1,jk=1; i <=nlstate; i++){
                   13055:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  13056:        if (j!=i) {
                   13057:          fprintf(ficres,"%1d%1d",i,j);
                   13058:          printf("%1d%1d",i,j);
                   13059:          fprintf(ficlog,"%1d%1d",i,j);
                   13060:          for(k=1; k<=ncovmodel;k++){
                   13061:            printf(" %.5e",delti[jk]);
                   13062:            fprintf(ficlog," %.5e",delti[jk]);
                   13063:            fprintf(ficres," %.5e",delti[jk]);
                   13064:            jk++;
                   13065:          }
                   13066:          printf("\n");
                   13067:          fprintf(ficlog,"\n");
                   13068:          fprintf(ficres,"\n");
                   13069:        }
1.126     brouard  13070:       }
                   13071:     }
                   13072:     
                   13073:     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  13074:     if(mle >= 1) /* To big for the screen */
1.126     brouard  13075:       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");
                   13076:     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");
                   13077:     /* # 121 Var(a12)\n\ */
                   13078:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   13079:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   13080:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   13081:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   13082:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   13083:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   13084:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   13085:     
                   13086:     
                   13087:     /* Just to have a covariance matrix which will be more understandable
                   13088:        even is we still don't want to manage dictionary of variables
                   13089:     */
                   13090:     for(itimes=1;itimes<=2;itimes++){
                   13091:       jj=0;
                   13092:       for(i=1; i <=nlstate; i++){
1.225     brouard  13093:        for(j=1; j <=nlstate+ndeath; j++){
                   13094:          if(j==i) continue;
                   13095:          for(k=1; k<=ncovmodel;k++){
                   13096:            jj++;
                   13097:            ca[0]= k+'a'-1;ca[1]='\0';
                   13098:            if(itimes==1){
                   13099:              if(mle>=1)
                   13100:                printf("#%1d%1d%d",i,j,k);
                   13101:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   13102:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   13103:            }else{
                   13104:              if(mle>=1)
                   13105:                printf("%1d%1d%d",i,j,k);
                   13106:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   13107:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   13108:            }
                   13109:            ll=0;
                   13110:            for(li=1;li <=nlstate; li++){
                   13111:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   13112:                if(lj==li) continue;
                   13113:                for(lk=1;lk<=ncovmodel;lk++){
                   13114:                  ll++;
                   13115:                  if(ll<=jj){
                   13116:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   13117:                    if(ll<jj){
                   13118:                      if(itimes==1){
                   13119:                        if(mle>=1)
                   13120:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13121:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13122:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13123:                      }else{
                   13124:                        if(mle>=1)
                   13125:                          printf(" %.5e",matcov[jj][ll]); 
                   13126:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   13127:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   13128:                      }
                   13129:                    }else{
                   13130:                      if(itimes==1){
                   13131:                        if(mle>=1)
                   13132:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   13133:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   13134:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   13135:                      }else{
                   13136:                        if(mle>=1)
                   13137:                          printf(" %.7e",matcov[jj][ll]); 
                   13138:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   13139:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   13140:                      }
                   13141:                    }
                   13142:                  }
                   13143:                } /* end lk */
                   13144:              } /* end lj */
                   13145:            } /* end li */
                   13146:            if(mle>=1)
                   13147:              printf("\n");
                   13148:            fprintf(ficlog,"\n");
                   13149:            fprintf(ficres,"\n");
                   13150:            numlinepar++;
                   13151:          } /* end k*/
                   13152:        } /*end j */
1.126     brouard  13153:       } /* end i */
                   13154:     } /* end itimes */
                   13155:     
                   13156:     fflush(ficlog);
                   13157:     fflush(ficres);
1.225     brouard  13158:     while(fgets(line, MAXLINE, ficpar)) {
                   13159:       /* If line starts with a # it is a comment */
                   13160:       if (line[0] == '#') {
                   13161:        numlinepar++;
                   13162:        fputs(line,stdout);
                   13163:        fputs(line,ficparo);
                   13164:        fputs(line,ficlog);
1.299     brouard  13165:        fputs(line,ficres);
1.225     brouard  13166:        continue;
                   13167:       }else
                   13168:        break;
                   13169:     }
                   13170:     
1.209     brouard  13171:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   13172:     /*   ungetc(c,ficpar); */
                   13173:     /*   fgets(line, MAXLINE, ficpar); */
                   13174:     /*   fputs(line,stdout); */
                   13175:     /*   fputs(line,ficparo); */
                   13176:     /* } */
                   13177:     /* ungetc(c,ficpar); */
1.126     brouard  13178:     
                   13179:     estepm=0;
1.209     brouard  13180:     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  13181:       
                   13182:       if (num_filled != 6) {
                   13183:        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);
                   13184:        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);
                   13185:        goto end;
                   13186:       }
                   13187:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   13188:     }
                   13189:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   13190:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   13191:     
1.209     brouard  13192:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  13193:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   13194:     if (fage <= 2) {
                   13195:       bage = ageminpar;
                   13196:       fage = agemaxpar;
                   13197:     }
                   13198:     
                   13199:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  13200:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   13201:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  13202:                
1.186     brouard  13203:     /* Other stuffs, more or less useful */    
1.254     brouard  13204:     while(fgets(line, MAXLINE, ficpar)) {
                   13205:       /* If line starts with a # it is a comment */
                   13206:       if (line[0] == '#') {
                   13207:        numlinepar++;
                   13208:        fputs(line,stdout);
                   13209:        fputs(line,ficparo);
                   13210:        fputs(line,ficlog);
1.299     brouard  13211:        fputs(line,ficres);
1.254     brouard  13212:        continue;
                   13213:       }else
                   13214:        break;
                   13215:     }
                   13216: 
                   13217:     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){
                   13218:       
                   13219:       if (num_filled != 7) {
                   13220:        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);
                   13221:        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);
                   13222:        goto end;
                   13223:       }
                   13224:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   13225:       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);
                   13226:       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);
                   13227:       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  13228:     }
1.254     brouard  13229: 
                   13230:     while(fgets(line, MAXLINE, ficpar)) {
                   13231:       /* If line starts with a # it is a comment */
                   13232:       if (line[0] == '#') {
                   13233:        numlinepar++;
                   13234:        fputs(line,stdout);
                   13235:        fputs(line,ficparo);
                   13236:        fputs(line,ficlog);
1.299     brouard  13237:        fputs(line,ficres);
1.254     brouard  13238:        continue;
                   13239:       }else
                   13240:        break;
1.126     brouard  13241:     }
                   13242:     
                   13243:     
                   13244:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   13245:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   13246:     
1.254     brouard  13247:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   13248:       if (num_filled != 1) {
                   13249:        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);
                   13250:        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);
                   13251:        goto end;
                   13252:       }
                   13253:       printf("pop_based=%d\n",popbased);
                   13254:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   13255:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   13256:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   13257:     }
                   13258:      
1.258     brouard  13259:     /* Results */
1.332   ! brouard  13260:     /* Value of covariate in each resultine will be compututed (if product) and sorted according to model rank */
        !          13261:     /* It is precov[] because we need the varying age in order to compute the real cov[] of the model equation */  
        !          13262:     precov=matrix(1,MAXRESULTLINESPONE,1,NCOVMAX+1);
1.307     brouard  13263:     endishere=0;
1.258     brouard  13264:     nresult=0;
1.308     brouard  13265:     parameterline=0;
1.258     brouard  13266:     do{
                   13267:       if(!fgets(line, MAXLINE, ficpar)){
                   13268:        endishere=1;
1.308     brouard  13269:        parameterline=15;
1.258     brouard  13270:       }else if (line[0] == '#') {
                   13271:        /* If line starts with a # it is a comment */
1.254     brouard  13272:        numlinepar++;
                   13273:        fputs(line,stdout);
                   13274:        fputs(line,ficparo);
                   13275:        fputs(line,ficlog);
1.299     brouard  13276:        fputs(line,ficres);
1.254     brouard  13277:        continue;
1.258     brouard  13278:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   13279:        parameterline=11;
1.296     brouard  13280:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  13281:        parameterline=12;
1.307     brouard  13282:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
1.258     brouard  13283:        parameterline=13;
1.307     brouard  13284:       }
1.258     brouard  13285:       else{
                   13286:        parameterline=14;
1.254     brouard  13287:       }
1.308     brouard  13288:       switch (parameterline){ /* =0 only if only comments */
1.258     brouard  13289:       case 11:
1.296     brouard  13290:        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)){
                   13291:                  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  13292:          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);
                   13293:          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);
                   13294:          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);
                   13295:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  13296:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   13297:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  13298:           prvforecast = 1;
                   13299:        } 
                   13300:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.313     brouard  13301:          printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   13302:          fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   13303:          fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  13304:           prvforecast = 2;
                   13305:        }
                   13306:        else {
                   13307:          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);
                   13308:          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);
                   13309:          goto end;
1.258     brouard  13310:        }
1.254     brouard  13311:        break;
1.258     brouard  13312:       case 12:
1.296     brouard  13313:        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)){
                   13314:           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);
                   13315:          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);
                   13316:          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);
                   13317:          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);
                   13318:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  13319:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   13320:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  13321:           prvbackcast = 1;
                   13322:        } 
                   13323:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.313     brouard  13324:          printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   13325:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   13326:          fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  13327:           prvbackcast = 2;
                   13328:        }
                   13329:        else {
                   13330:          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);
                   13331:          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);
                   13332:          goto end;
1.258     brouard  13333:        }
1.230     brouard  13334:        break;
1.258     brouard  13335:       case 13:
1.332   ! brouard  13336:        num_filled=sscanf(line,"result:%[^\n]\n",resultlineori);
1.307     brouard  13337:        nresult++; /* Sum of resultlines */
1.332   ! brouard  13338:        printf("Result %d: result:%s\n",nresult, resultlineori);
        !          13339:        /* removefirstspace(&resultlineori); */
        !          13340:        
        !          13341:        if(strstr(resultlineori,"v") !=0){
        !          13342:          printf("Error. 'v' must be in upper case 'V' result: %s ",resultlineori);
        !          13343:          fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultlineori);fflush(ficlog);
        !          13344:          return 1;
        !          13345:        }
        !          13346:        trimbb(resultline, resultlineori); /* Suppressing double blank in the resultline */
        !          13347:        printf("Decoderesult resultline=\"%s\" resultlineori=\"%s\"\n", resultline, resultlineori);
1.318     brouard  13348:        if(nresult > MAXRESULTLINESPONE-1){
                   13349:          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);
                   13350:          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  13351:          goto end;
                   13352:        }
1.332   ! brouard  13353:        
1.310     brouard  13354:        if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.314     brouard  13355:          fprintf(ficparo,"result: %s\n",resultline);
                   13356:          fprintf(ficres,"result: %s\n",resultline);
                   13357:          fprintf(ficlog,"result: %s\n",resultline);
1.310     brouard  13358:        } else
                   13359:          goto end;
1.307     brouard  13360:        break;
                   13361:       case 14:
                   13362:        printf("Error: Unknown command '%s'\n",line);
                   13363:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
1.314     brouard  13364:        if(line[0] == ' ' || line[0] == '\n'){
                   13365:          printf("It should not be an empty line '%s'\n",line);
                   13366:          fprintf(ficlog,"It should not be an empty line '%s'\n",line);
                   13367:        }         
1.307     brouard  13368:        if(ncovmodel >=2 && nresult==0 ){
                   13369:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   13370:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  13371:        }
1.307     brouard  13372:        /* goto end; */
                   13373:        break;
1.308     brouard  13374:       case 15:
                   13375:        printf("End of resultlines.\n");
                   13376:        fprintf(ficlog,"End of resultlines.\n");
                   13377:        break;
                   13378:       default: /* parameterline =0 */
1.307     brouard  13379:        nresult=1;
                   13380:        decoderesult(".",nresult ); /* No covariate */
1.258     brouard  13381:       } /* End switch parameterline */
                   13382:     }while(endishere==0); /* End do */
1.126     brouard  13383:     
1.230     brouard  13384:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  13385:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  13386:     
                   13387:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  13388:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  13389:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  13390: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13391: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  13392:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  13393: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13394: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  13395:     }else{
1.270     brouard  13396:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  13397:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   13398:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   13399:       if(prvforecast==1){
                   13400:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   13401:         jprojd=jproj1;
                   13402:         mprojd=mproj1;
                   13403:         anprojd=anproj1;
                   13404:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   13405:         jprojf=jproj2;
                   13406:         mprojf=mproj2;
                   13407:         anprojf=anproj2;
                   13408:       } else if(prvforecast == 2){
                   13409:         dateprojd=dateintmean;
                   13410:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   13411:         dateprojf=dateintmean+yrfproj;
                   13412:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   13413:       }
                   13414:       if(prvbackcast==1){
                   13415:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   13416:         jbackd=jback1;
                   13417:         mbackd=mback1;
                   13418:         anbackd=anback1;
                   13419:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   13420:         jbackf=jback2;
                   13421:         mbackf=mback2;
                   13422:         anbackf=anback2;
                   13423:       } else if(prvbackcast == 2){
                   13424:         datebackd=dateintmean;
                   13425:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   13426:         datebackf=dateintmean-yrbproj;
                   13427:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   13428:       }
                   13429:       
                   13430:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);
1.220     brouard  13431:     }
                   13432:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  13433:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   13434:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  13435:                
1.225     brouard  13436:     /*------------ free_vector  -------------*/
                   13437:     /*  chdir(path); */
1.220     brouard  13438:                
1.215     brouard  13439:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   13440:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   13441:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   13442:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  13443:     free_lvector(num,firstobs,lastobs);
                   13444:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  13445:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   13446:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   13447:     fclose(ficparo);
                   13448:     fclose(ficres);
1.220     brouard  13449:                
                   13450:                
1.186     brouard  13451:     /* Other results (useful)*/
1.220     brouard  13452:                
                   13453:                
1.126     brouard  13454:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  13455:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   13456:     prlim=matrix(1,nlstate,1,nlstate);
1.332   ! brouard  13457:     /* Computes the prevalence limit for each combination k of the dummy covariates by calling prevalim(k) */
1.209     brouard  13458:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  13459:     fclose(ficrespl);
                   13460: 
                   13461:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  13462:     /*#include "hpijx.h"*/
1.332   ! brouard  13463:     /** h Pij x Probability to be in state j at age x+h being in i at x, for each combination k of dummies in the model line or to nres?*/
        !          13464:     /* calls hpxij with combination k */
1.180     brouard  13465:     hPijx(p, bage, fage);
1.145     brouard  13466:     fclose(ficrespij);
1.227     brouard  13467:     
1.220     brouard  13468:     /* ncovcombmax=  pow(2,cptcoveff); */
1.332   ! brouard  13469:     /*-------------- Variance of one-step probabilities for a combination ij or for nres ?---*/
1.145     brouard  13470:     k=1;
1.126     brouard  13471:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  13472:     
1.269     brouard  13473:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   13474:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   13475:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  13476:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  13477:        for(k=1;k<=ncovcombmax;k++)
                   13478:          probs[i][j][k]=0.;
1.269     brouard  13479:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   13480:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  13481:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  13482:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   13483:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  13484:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  13485:          for(k=1;k<=ncovcombmax;k++)
                   13486:            mobaverages[i][j][k]=0.;
1.219     brouard  13487:       mobaverage=mobaverages;
                   13488:       if (mobilav!=0) {
1.235     brouard  13489:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  13490:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  13491:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   13492:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   13493:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   13494:        }
1.269     brouard  13495:       } else if (mobilavproj !=0) {
1.235     brouard  13496:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  13497:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  13498:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   13499:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   13500:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   13501:        }
1.269     brouard  13502:       }else{
                   13503:        printf("Internal error moving average\n");
                   13504:        fflush(stdout);
                   13505:        exit(1);
1.219     brouard  13506:       }
                   13507:     }/* end if moving average */
1.227     brouard  13508:     
1.126     brouard  13509:     /*---------- Forecasting ------------------*/
1.296     brouard  13510:     if(prevfcast==1){ 
                   13511:       /*   /\*    if(stepm ==1){*\/ */
                   13512:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   13513:       /*This done previously after freqsummary.*/
                   13514:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   13515:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   13516:       
                   13517:       /* } else if (prvforecast==2){ */
                   13518:       /*   /\*    if(stepm ==1){*\/ */
                   13519:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   13520:       /* } */
                   13521:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   13522:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  13523:     }
1.269     brouard  13524: 
1.296     brouard  13525:     /* Prevbcasting */
                   13526:     if(prevbcast==1){
1.219     brouard  13527:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   13528:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   13529:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   13530: 
                   13531:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   13532: 
                   13533:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  13534: 
1.219     brouard  13535:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   13536:       fclose(ficresplb);
                   13537: 
1.222     brouard  13538:       hBijx(p, bage, fage, mobaverage);
                   13539:       fclose(ficrespijb);
1.219     brouard  13540: 
1.296     brouard  13541:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   13542:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   13543:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   13544:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   13545:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   13546:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   13547: 
                   13548:       
1.269     brouard  13549:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  13550: 
                   13551:       
1.269     brouard  13552:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  13553:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   13554:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   13555:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  13556:     }    /* end  Prevbcasting */
1.268     brouard  13557:  
1.186     brouard  13558:  
                   13559:     /* ------ Other prevalence ratios------------ */
1.126     brouard  13560: 
1.215     brouard  13561:     free_ivector(wav,1,imx);
                   13562:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   13563:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   13564:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  13565:                
                   13566:                
1.127     brouard  13567:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  13568:                
1.201     brouard  13569:     strcpy(filerese,"E_");
                   13570:     strcat(filerese,fileresu);
1.126     brouard  13571:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   13572:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   13573:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   13574:     }
1.208     brouard  13575:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   13576:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  13577: 
                   13578:     pstamp(ficreseij);
1.219     brouard  13579:                
1.235     brouard  13580:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   13581:     if (cptcovn < 1){i1=1;}
                   13582:     
                   13583:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   13584:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  13585:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  13586:        continue;
1.219     brouard  13587:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  13588:       printf("\n#****** ");
1.225     brouard  13589:       for(j=1;j<=cptcoveff;j++) {
1.332   ! brouard  13590:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
        !          13591:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.235     brouard  13592:       }
                   13593:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332   ! brouard  13594:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
        !          13595:        fprintf(ficreseij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
1.219     brouard  13596:       }
                   13597:       fprintf(ficreseij,"******\n");
1.235     brouard  13598:       printf("******\n");
1.219     brouard  13599:       
                   13600:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   13601:       oldm=oldms;savm=savms;
1.330     brouard  13602:       /* 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  13603:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  13604:       
1.219     brouard  13605:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  13606:     }
                   13607:     fclose(ficreseij);
1.208     brouard  13608:     printf("done evsij\n");fflush(stdout);
                   13609:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  13610: 
1.218     brouard  13611:                
1.227     brouard  13612:     /*---------- State-specific expectancies and variances ------------*/
1.218     brouard  13613:                
1.201     brouard  13614:     strcpy(filerest,"T_");
                   13615:     strcat(filerest,fileresu);
1.127     brouard  13616:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   13617:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   13618:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   13619:     }
1.208     brouard  13620:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   13621:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  13622:     strcpy(fileresstde,"STDE_");
                   13623:     strcat(fileresstde,fileresu);
1.126     brouard  13624:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  13625:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   13626:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  13627:     }
1.227     brouard  13628:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   13629:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  13630: 
1.201     brouard  13631:     strcpy(filerescve,"CVE_");
                   13632:     strcat(filerescve,fileresu);
1.126     brouard  13633:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  13634:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   13635:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  13636:     }
1.227     brouard  13637:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   13638:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  13639: 
1.201     brouard  13640:     strcpy(fileresv,"V_");
                   13641:     strcat(fileresv,fileresu);
1.126     brouard  13642:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   13643:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   13644:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   13645:     }
1.227     brouard  13646:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   13647:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  13648: 
1.235     brouard  13649:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   13650:     if (cptcovn < 1){i1=1;}
                   13651:     
                   13652:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   13653:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  13654:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  13655:        continue;
1.321     brouard  13656:       printf("\n# model %s \n#****** Result for:", model);
                   13657:       fprintf(ficrest,"\n# model %s \n#****** Result for:", model);
                   13658:       fprintf(ficlog,"\n# model %s \n#****** Result for:", model);
1.227     brouard  13659:       for(j=1;j<=cptcoveff;j++){ 
1.332   ! brouard  13660:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
        !          13661:        fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
        !          13662:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.227     brouard  13663:       }
1.235     brouard  13664:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332   ! brouard  13665:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
        !          13666:        fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
        !          13667:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
1.235     brouard  13668:       }        
1.208     brouard  13669:       fprintf(ficrest,"******\n");
1.227     brouard  13670:       fprintf(ficlog,"******\n");
                   13671:       printf("******\n");
1.208     brouard  13672:       
                   13673:       fprintf(ficresstdeij,"\n#****** ");
                   13674:       fprintf(ficrescveij,"\n#****** ");
1.225     brouard  13675:       for(j=1;j<=cptcoveff;j++) {
1.332   ! brouard  13676:        fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
        !          13677:        fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.208     brouard  13678:       }
1.235     brouard  13679:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332   ! brouard  13680:        fprintf(ficresstdeij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
        !          13681:        fprintf(ficrescveij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
1.235     brouard  13682:       }        
1.208     brouard  13683:       fprintf(ficresstdeij,"******\n");
                   13684:       fprintf(ficrescveij,"******\n");
                   13685:       
                   13686:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  13687:       /* pstamp(ficresvij); */
1.225     brouard  13688:       for(j=1;j<=cptcoveff;j++) 
1.332   ! brouard  13689:        fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[TnsdVar[Tvaraff[j]]])]);
1.235     brouard  13690:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332   ! brouard  13691:        /* fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]); /\* To solve *\/ */
        !          13692:        fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /* Solved */
1.235     brouard  13693:       }        
1.208     brouard  13694:       fprintf(ficresvij,"******\n");
                   13695:       
                   13696:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   13697:       oldm=oldms;savm=savms;
1.235     brouard  13698:       printf(" cvevsij ");
                   13699:       fprintf(ficlog, " cvevsij ");
                   13700:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  13701:       printf(" end cvevsij \n ");
                   13702:       fprintf(ficlog, " end cvevsij \n ");
                   13703:       
                   13704:       /*
                   13705:        */
                   13706:       /* goto endfree; */
                   13707:       
                   13708:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   13709:       pstamp(ficrest);
                   13710:       
1.269     brouard  13711:       epj=vector(1,nlstate+1);
1.208     brouard  13712:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  13713:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   13714:        cptcod= 0; /* To be deleted */
                   13715:        printf("varevsij vpopbased=%d \n",vpopbased);
                   13716:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  13717:        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  13718:        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 ");
                   13719:        if(vpopbased==1)
                   13720:          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);
                   13721:        else
1.288     brouard  13722:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  13723:        fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
                   13724:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   13725:        fprintf(ficrest,"\n");
                   13726:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  13727:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   13728:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  13729:        for(age=bage; age <=fage ;age++){
1.235     brouard  13730:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  13731:          if (vpopbased==1) {
                   13732:            if(mobilav ==0){
                   13733:              for(i=1; i<=nlstate;i++)
                   13734:                prlim[i][i]=probs[(int)age][i][k];
                   13735:            }else{ /* mobilav */ 
                   13736:              for(i=1; i<=nlstate;i++)
                   13737:                prlim[i][i]=mobaverage[(int)age][i][k];
                   13738:            }
                   13739:          }
1.219     brouard  13740:          
1.227     brouard  13741:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   13742:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   13743:          /* printf(" age %4.0f ",age); */
                   13744:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   13745:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   13746:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   13747:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   13748:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   13749:            }
                   13750:            epj[nlstate+1] +=epj[j];
                   13751:          }
                   13752:          /* printf(" age %4.0f \n",age); */
1.219     brouard  13753:          
1.227     brouard  13754:          for(i=1, vepp=0.;i <=nlstate;i++)
                   13755:            for(j=1;j <=nlstate;j++)
                   13756:              vepp += vareij[i][j][(int)age];
                   13757:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   13758:          for(j=1;j <=nlstate;j++){
                   13759:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   13760:          }
                   13761:          fprintf(ficrest,"\n");
                   13762:        }
1.208     brouard  13763:       } /* End vpopbased */
1.269     brouard  13764:       free_vector(epj,1,nlstate+1);
1.208     brouard  13765:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   13766:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  13767:       printf("done selection\n");fflush(stdout);
                   13768:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  13769:       
1.235     brouard  13770:     } /* End k selection */
1.227     brouard  13771: 
                   13772:     printf("done State-specific expectancies\n");fflush(stdout);
                   13773:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   13774: 
1.288     brouard  13775:     /* variance-covariance of forward period prevalence*/
1.269     brouard  13776:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  13777: 
1.227     brouard  13778:     
1.290     brouard  13779:     free_vector(weight,firstobs,lastobs);
1.330     brouard  13780:     free_imatrix(Tvardk,1,NCOVMAX,1,2);
1.227     brouard  13781:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  13782:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   13783:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   13784:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   13785:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  13786:     free_ivector(tab,1,NCOVMAX);
                   13787:     fclose(ficresstdeij);
                   13788:     fclose(ficrescveij);
                   13789:     fclose(ficresvij);
                   13790:     fclose(ficrest);
                   13791:     fclose(ficpar);
                   13792:     
                   13793:     
1.126     brouard  13794:     /*---------- End : free ----------------*/
1.219     brouard  13795:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  13796:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   13797:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  13798:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   13799:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  13800:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  13801:   /* endfree:*/
                   13802:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   13803:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   13804:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.290     brouard  13805:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs);
                   13806:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   13807:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   13808:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  13809:   free_matrix(matcov,1,npar,1,npar);
                   13810:   free_matrix(hess,1,npar,1,npar);
                   13811:   /*free_vector(delti,1,npar);*/
                   13812:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   13813:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  13814:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  13815:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   13816:   
                   13817:   free_ivector(ncodemax,1,NCOVMAX);
                   13818:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   13819:   free_ivector(Dummy,-1,NCOVMAX);
                   13820:   free_ivector(Fixed,-1,NCOVMAX);
1.238     brouard  13821:   free_ivector(DummyV,1,NCOVMAX);
                   13822:   free_ivector(FixedV,1,NCOVMAX);
1.227     brouard  13823:   free_ivector(Typevar,-1,NCOVMAX);
                   13824:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  13825:   free_ivector(TvarsQ,1,NCOVMAX);
                   13826:   free_ivector(TvarsQind,1,NCOVMAX);
                   13827:   free_ivector(TvarsD,1,NCOVMAX);
1.330     brouard  13828:   free_ivector(TnsdVar,1,NCOVMAX);
1.234     brouard  13829:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  13830:   free_ivector(TvarFD,1,NCOVMAX);
                   13831:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  13832:   free_ivector(TvarF,1,NCOVMAX);
                   13833:   free_ivector(TvarFind,1,NCOVMAX);
                   13834:   free_ivector(TvarV,1,NCOVMAX);
                   13835:   free_ivector(TvarVind,1,NCOVMAX);
                   13836:   free_ivector(TvarA,1,NCOVMAX);
                   13837:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  13838:   free_ivector(TvarFQ,1,NCOVMAX);
                   13839:   free_ivector(TvarFQind,1,NCOVMAX);
                   13840:   free_ivector(TvarVD,1,NCOVMAX);
                   13841:   free_ivector(TvarVDind,1,NCOVMAX);
                   13842:   free_ivector(TvarVQ,1,NCOVMAX);
                   13843:   free_ivector(TvarVQind,1,NCOVMAX);
1.230     brouard  13844:   free_ivector(Tvarsel,1,NCOVMAX);
                   13845:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  13846:   free_ivector(Tposprod,1,NCOVMAX);
                   13847:   free_ivector(Tprod,1,NCOVMAX);
                   13848:   free_ivector(Tvaraff,1,NCOVMAX);
                   13849:   free_ivector(invalidvarcomb,1,ncovcombmax);
                   13850:   free_ivector(Tage,1,NCOVMAX);
                   13851:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  13852:   free_ivector(TmodelInvind,1,NCOVMAX);
                   13853:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.332   ! brouard  13854: 
        !          13855:   free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /* Could be elsewhere ?*/
        !          13856: 
1.227     brouard  13857:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   13858:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  13859:   fflush(fichtm);
                   13860:   fflush(ficgp);
                   13861:   
1.227     brouard  13862:   
1.126     brouard  13863:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  13864:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   13865:     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  13866:   }else{
                   13867:     printf("End of Imach\n");
                   13868:     fprintf(ficlog,"End of Imach\n");
                   13869:   }
                   13870:   printf("See log file on %s\n",filelog);
                   13871:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  13872:   /*(void) gettimeofday(&end_time,&tzp);*/
                   13873:   rend_time = time(NULL);  
                   13874:   end_time = *localtime(&rend_time);
                   13875:   /* tml = *localtime(&end_time.tm_sec); */
                   13876:   strcpy(strtend,asctime(&end_time));
1.126     brouard  13877:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   13878:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  13879:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  13880:   
1.157     brouard  13881:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   13882:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   13883:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  13884:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   13885: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   13886:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   13887:   fclose(fichtm);
                   13888:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   13889:   fclose(fichtmcov);
                   13890:   fclose(ficgp);
                   13891:   fclose(ficlog);
                   13892:   /*------ End -----------*/
1.227     brouard  13893:   
1.281     brouard  13894: 
                   13895: /* Executes gnuplot */
1.227     brouard  13896:   
                   13897:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  13898: #ifdef WIN32
1.227     brouard  13899:   if (_chdir(pathcd) != 0)
                   13900:     printf("Can't move to directory %s!\n",path);
                   13901:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  13902: #else
1.227     brouard  13903:     if(chdir(pathcd) != 0)
                   13904:       printf("Can't move to directory %s!\n", path);
                   13905:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  13906: #endif 
1.126     brouard  13907:     printf("Current directory %s!\n",pathcd);
                   13908:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   13909:   sprintf(plotcmd,"gnuplot");
1.157     brouard  13910: #ifdef _WIN32
1.126     brouard  13911:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   13912: #endif
                   13913:   if(!stat(plotcmd,&info)){
1.158     brouard  13914:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  13915:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  13916:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  13917:     }else
                   13918:       strcpy(pplotcmd,plotcmd);
1.157     brouard  13919: #ifdef __unix
1.126     brouard  13920:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   13921:     if(!stat(plotcmd,&info)){
1.158     brouard  13922:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  13923:     }else
                   13924:       strcpy(pplotcmd,plotcmd);
                   13925: #endif
                   13926:   }else
                   13927:     strcpy(pplotcmd,plotcmd);
                   13928:   
                   13929:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  13930:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  13931:   strcpy(pplotcmd,plotcmd);
1.227     brouard  13932:   
1.126     brouard  13933:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  13934:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  13935:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  13936:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  13937:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  13938:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  13939:       strcpy(plotcmd,pplotcmd);
                   13940:     }
1.126     brouard  13941:   }
1.158     brouard  13942:   printf(" Successful, please wait...");
1.126     brouard  13943:   while (z[0] != 'q') {
                   13944:     /* chdir(path); */
1.154     brouard  13945:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  13946:     scanf("%s",z);
                   13947: /*     if (z[0] == 'c') system("./imach"); */
                   13948:     if (z[0] == 'e') {
1.158     brouard  13949: #ifdef __APPLE__
1.152     brouard  13950:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  13951: #elif __linux
                   13952:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  13953: #else
1.152     brouard  13954:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  13955: #endif
                   13956:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   13957:       system(pplotcmd);
1.126     brouard  13958:     }
                   13959:     else if (z[0] == 'g') system(plotcmd);
                   13960:     else if (z[0] == 'q') exit(0);
                   13961:   }
1.227     brouard  13962: end:
1.126     brouard  13963:   while (z[0] != 'q') {
1.195     brouard  13964:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  13965:     scanf("%s",z);
                   13966:   }
1.283     brouard  13967:   printf("End\n");
1.282     brouard  13968:   exit(0);
1.126     brouard  13969: }

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