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

1.327   ! brouard     1: /* $Id: imach.c,v 1.326 2022/07/26 17:33:55 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.327   ! brouard     4:   Revision 1.326  2022/07/26 17:33:55  brouard
        !             5:   Summary: some test with nres=1
        !             6: 
1.326     brouard     7:   Revision 1.325  2022/07/25 14:27:23  brouard
                      8:   Summary: r30
                      9: 
                     10:   * imach.c (Module): Error cptcovn instead of nsd in bmij (was
                     11:   coredumped, revealed by Feiuno, thank you.
                     12: 
1.325     brouard    13:   Revision 1.324  2022/07/23 17:44:26  brouard
                     14:   *** empty log message ***
                     15: 
1.324     brouard    16:   Revision 1.323  2022/07/22 12:30:08  brouard
                     17:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                     18: 
1.323     brouard    19:   Revision 1.322  2022/07/22 12:27:48  brouard
                     20:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                     21: 
1.322     brouard    22:   Revision 1.321  2022/07/22 12:04:24  brouard
                     23:   Summary: r28
                     24: 
                     25:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                     26: 
1.321     brouard    27:   Revision 1.320  2022/06/02 05:10:11  brouard
                     28:   *** empty log message ***
                     29: 
1.320     brouard    30:   Revision 1.319  2022/06/02 04:45:11  brouard
                     31:   * imach.c (Module): Adding the Wald tests from the log to the main
                     32:   htm for better display of the maximum likelihood estimators.
                     33: 
1.319     brouard    34:   Revision 1.318  2022/05/24 08:10:59  brouard
                     35:   * imach.c (Module): Some attempts to find a bug of wrong estimates
                     36:   of confidencce intervals with product in the equation modelC
                     37: 
1.318     brouard    38:   Revision 1.317  2022/05/15 15:06:23  brouard
                     39:   * imach.c (Module):  Some minor improvements
                     40: 
1.317     brouard    41:   Revision 1.316  2022/05/11 15:11:31  brouard
                     42:   Summary: r27
                     43: 
1.316     brouard    44:   Revision 1.315  2022/05/11 15:06:32  brouard
                     45:   *** empty log message ***
                     46: 
1.315     brouard    47:   Revision 1.314  2022/04/13 17:43:09  brouard
                     48:   * imach.c (Module): Adding link to text data files
                     49: 
1.314     brouard    50:   Revision 1.313  2022/04/11 15:57:42  brouard
                     51:   * imach.c (Module): Error in rewriting the 'r' file with yearsfproj or yearsbproj fixed
                     52: 
1.313     brouard    53:   Revision 1.312  2022/04/05 21:24:39  brouard
                     54:   *** empty log message ***
                     55: 
1.312     brouard    56:   Revision 1.311  2022/04/05 21:03:51  brouard
                     57:   Summary: Fixed quantitative covariates
                     58: 
                     59:          Fixed covariates (dummy or quantitative)
                     60:        with missing values have never been allowed but are ERRORS and
                     61:        program quits. Standard deviations of fixed covariates were
                     62:        wrongly computed. Mean and standard deviations of time varying
                     63:        covariates are still not computed.
                     64: 
1.311     brouard    65:   Revision 1.310  2022/03/17 08:45:53  brouard
                     66:   Summary: 99r25
                     67: 
                     68:   Improving detection of errors: result lines should be compatible with
                     69:   the model.
                     70: 
1.310     brouard    71:   Revision 1.309  2021/05/20 12:39:14  brouard
                     72:   Summary: Version 0.99r24
                     73: 
1.309     brouard    74:   Revision 1.308  2021/03/31 13:11:57  brouard
                     75:   Summary: Version 0.99r23
                     76: 
                     77: 
                     78:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
                     79: 
1.308     brouard    80:   Revision 1.307  2021/03/08 18:11:32  brouard
                     81:   Summary: 0.99r22 fixed bug on result:
                     82: 
1.307     brouard    83:   Revision 1.306  2021/02/20 15:44:02  brouard
                     84:   Summary: Version 0.99r21
                     85: 
                     86:   * imach.c (Module): Fix bug on quitting after result lines!
                     87:   (Module): Version 0.99r21
                     88: 
1.306     brouard    89:   Revision 1.305  2021/02/20 15:28:30  brouard
                     90:   * imach.c (Module): Fix bug on quitting after result lines!
                     91: 
1.305     brouard    92:   Revision 1.304  2021/02/12 11:34:20  brouard
                     93:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
                     94: 
1.304     brouard    95:   Revision 1.303  2021/02/11 19:50:15  brouard
                     96:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
                     97: 
1.303     brouard    98:   Revision 1.302  2020/02/22 21:00:05  brouard
                     99:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
                    100:   and life table from the data without any state)
                    101: 
1.302     brouard   102:   Revision 1.301  2019/06/04 13:51:20  brouard
                    103:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                    104: 
1.301     brouard   105:   Revision 1.300  2019/05/22 19:09:45  brouard
                    106:   Summary: version 0.99r19 of May 2019
                    107: 
1.300     brouard   108:   Revision 1.299  2019/05/22 18:37:08  brouard
                    109:   Summary: Cleaned 0.99r19
                    110: 
1.299     brouard   111:   Revision 1.298  2019/05/22 18:19:56  brouard
                    112:   *** empty log message ***
                    113: 
1.298     brouard   114:   Revision 1.297  2019/05/22 17:56:10  brouard
                    115:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                    116: 
1.297     brouard   117:   Revision 1.296  2019/05/20 13:03:18  brouard
                    118:   Summary: Projection syntax simplified
                    119: 
                    120: 
                    121:   We can now start projections, forward or backward, from the mean date
                    122:   of inteviews up to or down to a number of years of projection:
                    123:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                    124:   or
                    125:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                    126:   or
                    127:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                    128:   or
                    129:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                    130: 
1.296     brouard   131:   Revision 1.295  2019/05/18 09:52:50  brouard
                    132:   Summary: doxygen tex bug
                    133: 
1.295     brouard   134:   Revision 1.294  2019/05/16 14:54:33  brouard
                    135:   Summary: There was some wrong lines added
                    136: 
1.294     brouard   137:   Revision 1.293  2019/05/09 15:17:34  brouard
                    138:   *** empty log message ***
                    139: 
1.293     brouard   140:   Revision 1.292  2019/05/09 14:17:20  brouard
                    141:   Summary: Some updates
                    142: 
1.292     brouard   143:   Revision 1.291  2019/05/09 13:44:18  brouard
                    144:   Summary: Before ncovmax
                    145: 
1.291     brouard   146:   Revision 1.290  2019/05/09 13:39:37  brouard
                    147:   Summary: 0.99r18 unlimited number of individuals
                    148: 
                    149:   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.
                    150: 
1.290     brouard   151:   Revision 1.289  2018/12/13 09:16:26  brouard
                    152:   Summary: Bug for young ages (<-30) will be in r17
                    153: 
1.289     brouard   154:   Revision 1.288  2018/05/02 20:58:27  brouard
                    155:   Summary: Some bugs fixed
                    156: 
1.288     brouard   157:   Revision 1.287  2018/05/01 17:57:25  brouard
                    158:   Summary: Bug fixed by providing frequencies only for non missing covariates
                    159: 
1.287     brouard   160:   Revision 1.286  2018/04/27 14:27:04  brouard
                    161:   Summary: some minor bugs
                    162: 
1.286     brouard   163:   Revision 1.285  2018/04/21 21:02:16  brouard
                    164:   Summary: Some bugs fixed, valgrind tested
                    165: 
1.285     brouard   166:   Revision 1.284  2018/04/20 05:22:13  brouard
                    167:   Summary: Computing mean and stdeviation of fixed quantitative variables
                    168: 
1.284     brouard   169:   Revision 1.283  2018/04/19 14:49:16  brouard
                    170:   Summary: Some minor bugs fixed
                    171: 
1.283     brouard   172:   Revision 1.282  2018/02/27 22:50:02  brouard
                    173:   *** empty log message ***
                    174: 
1.282     brouard   175:   Revision 1.281  2018/02/27 19:25:23  brouard
                    176:   Summary: Adding second argument for quitting
                    177: 
1.281     brouard   178:   Revision 1.280  2018/02/21 07:58:13  brouard
                    179:   Summary: 0.99r15
                    180: 
                    181:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                    182: 
1.280     brouard   183:   Revision 1.279  2017/07/20 13:35:01  brouard
                    184:   Summary: temporary working
                    185: 
1.279     brouard   186:   Revision 1.278  2017/07/19 14:09:02  brouard
                    187:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                    188: 
1.278     brouard   189:   Revision 1.277  2017/07/17 08:53:49  brouard
                    190:   Summary: BOM files can be read now
                    191: 
1.277     brouard   192:   Revision 1.276  2017/06/30 15:48:31  brouard
                    193:   Summary: Graphs improvements
                    194: 
1.276     brouard   195:   Revision 1.275  2017/06/30 13:39:33  brouard
                    196:   Summary: Saito's color
                    197: 
1.275     brouard   198:   Revision 1.274  2017/06/29 09:47:08  brouard
                    199:   Summary: Version 0.99r14
                    200: 
1.274     brouard   201:   Revision 1.273  2017/06/27 11:06:02  brouard
                    202:   Summary: More documentation on projections
                    203: 
1.273     brouard   204:   Revision 1.272  2017/06/27 10:22:40  brouard
                    205:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    206: 
1.272     brouard   207:   Revision 1.271  2017/06/27 10:17:50  brouard
                    208:   Summary: Some bug with rint
                    209: 
1.271     brouard   210:   Revision 1.270  2017/05/24 05:45:29  brouard
                    211:   *** empty log message ***
                    212: 
1.270     brouard   213:   Revision 1.269  2017/05/23 08:39:25  brouard
                    214:   Summary: Code into subroutine, cleanings
                    215: 
1.269     brouard   216:   Revision 1.268  2017/05/18 20:09:32  brouard
                    217:   Summary: backprojection and confidence intervals of backprevalence
                    218: 
1.268     brouard   219:   Revision 1.267  2017/05/13 10:25:05  brouard
                    220:   Summary: temporary save for backprojection
                    221: 
1.267     brouard   222:   Revision 1.266  2017/05/13 07:26:12  brouard
                    223:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    224: 
1.266     brouard   225:   Revision 1.265  2017/04/26 16:22:11  brouard
                    226:   Summary: imach 0.99r13 Some bugs fixed
                    227: 
1.265     brouard   228:   Revision 1.264  2017/04/26 06:01:29  brouard
                    229:   Summary: Labels in graphs
                    230: 
1.264     brouard   231:   Revision 1.263  2017/04/24 15:23:15  brouard
                    232:   Summary: to save
                    233: 
1.263     brouard   234:   Revision 1.262  2017/04/18 16:48:12  brouard
                    235:   *** empty log message ***
                    236: 
1.262     brouard   237:   Revision 1.261  2017/04/05 10:14:09  brouard
                    238:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    239: 
1.261     brouard   240:   Revision 1.260  2017/04/04 17:46:59  brouard
                    241:   Summary: Gnuplot indexations fixed (humm)
                    242: 
1.260     brouard   243:   Revision 1.259  2017/04/04 13:01:16  brouard
                    244:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    245: 
1.259     brouard   246:   Revision 1.258  2017/04/03 10:17:47  brouard
                    247:   Summary: Version 0.99r12
                    248: 
                    249:   Some cleanings, conformed with updated documentation.
                    250: 
1.258     brouard   251:   Revision 1.257  2017/03/29 16:53:30  brouard
                    252:   Summary: Temp
                    253: 
1.257     brouard   254:   Revision 1.256  2017/03/27 05:50:23  brouard
                    255:   Summary: Temporary
                    256: 
1.256     brouard   257:   Revision 1.255  2017/03/08 16:02:28  brouard
                    258:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    259: 
1.255     brouard   260:   Revision 1.254  2017/03/08 07:13:00  brouard
                    261:   Summary: Fixing data parameter line
                    262: 
1.254     brouard   263:   Revision 1.253  2016/12/15 11:59:41  brouard
                    264:   Summary: 0.99 in progress
                    265: 
1.253     brouard   266:   Revision 1.252  2016/09/15 21:15:37  brouard
                    267:   *** empty log message ***
                    268: 
1.252     brouard   269:   Revision 1.251  2016/09/15 15:01:13  brouard
                    270:   Summary: not working
                    271: 
1.251     brouard   272:   Revision 1.250  2016/09/08 16:07:27  brouard
                    273:   Summary: continue
                    274: 
1.250     brouard   275:   Revision 1.249  2016/09/07 17:14:18  brouard
                    276:   Summary: Starting values from frequencies
                    277: 
1.249     brouard   278:   Revision 1.248  2016/09/07 14:10:18  brouard
                    279:   *** empty log message ***
                    280: 
1.248     brouard   281:   Revision 1.247  2016/09/02 11:11:21  brouard
                    282:   *** empty log message ***
                    283: 
1.247     brouard   284:   Revision 1.246  2016/09/02 08:49:22  brouard
                    285:   *** empty log message ***
                    286: 
1.246     brouard   287:   Revision 1.245  2016/09/02 07:25:01  brouard
                    288:   *** empty log message ***
                    289: 
1.245     brouard   290:   Revision 1.244  2016/09/02 07:17:34  brouard
                    291:   *** empty log message ***
                    292: 
1.244     brouard   293:   Revision 1.243  2016/09/02 06:45:35  brouard
                    294:   *** empty log message ***
                    295: 
1.243     brouard   296:   Revision 1.242  2016/08/30 15:01:20  brouard
                    297:   Summary: Fixing a lots
                    298: 
1.242     brouard   299:   Revision 1.241  2016/08/29 17:17:25  brouard
                    300:   Summary: gnuplot problem in Back projection to fix
                    301: 
1.241     brouard   302:   Revision 1.240  2016/08/29 07:53:18  brouard
                    303:   Summary: Better
                    304: 
1.240     brouard   305:   Revision 1.239  2016/08/26 15:51:03  brouard
                    306:   Summary: Improvement in Powell output in order to copy and paste
                    307: 
                    308:   Author:
                    309: 
1.239     brouard   310:   Revision 1.238  2016/08/26 14:23:35  brouard
                    311:   Summary: Starting tests of 0.99
                    312: 
1.238     brouard   313:   Revision 1.237  2016/08/26 09:20:19  brouard
                    314:   Summary: to valgrind
                    315: 
1.237     brouard   316:   Revision 1.236  2016/08/25 10:50:18  brouard
                    317:   *** empty log message ***
                    318: 
1.236     brouard   319:   Revision 1.235  2016/08/25 06:59:23  brouard
                    320:   *** empty log message ***
                    321: 
1.235     brouard   322:   Revision 1.234  2016/08/23 16:51:20  brouard
                    323:   *** empty log message ***
                    324: 
1.234     brouard   325:   Revision 1.233  2016/08/23 07:40:50  brouard
                    326:   Summary: not working
                    327: 
1.233     brouard   328:   Revision 1.232  2016/08/22 14:20:21  brouard
                    329:   Summary: not working
                    330: 
1.232     brouard   331:   Revision 1.231  2016/08/22 07:17:15  brouard
                    332:   Summary: not working
                    333: 
1.231     brouard   334:   Revision 1.230  2016/08/22 06:55:53  brouard
                    335:   Summary: Not working
                    336: 
1.230     brouard   337:   Revision 1.229  2016/07/23 09:45:53  brouard
                    338:   Summary: Completing for func too
                    339: 
1.229     brouard   340:   Revision 1.228  2016/07/22 17:45:30  brouard
                    341:   Summary: Fixing some arrays, still debugging
                    342: 
1.227     brouard   343:   Revision 1.226  2016/07/12 18:42:34  brouard
                    344:   Summary: temp
                    345: 
1.226     brouard   346:   Revision 1.225  2016/07/12 08:40:03  brouard
                    347:   Summary: saving but not running
                    348: 
1.225     brouard   349:   Revision 1.224  2016/07/01 13:16:01  brouard
                    350:   Summary: Fixes
                    351: 
1.224     brouard   352:   Revision 1.223  2016/02/19 09:23:35  brouard
                    353:   Summary: temporary
                    354: 
1.223     brouard   355:   Revision 1.222  2016/02/17 08:14:50  brouard
                    356:   Summary: Probably last 0.98 stable version 0.98r6
                    357: 
1.222     brouard   358:   Revision 1.221  2016/02/15 23:35:36  brouard
                    359:   Summary: minor bug
                    360: 
1.220     brouard   361:   Revision 1.219  2016/02/15 00:48:12  brouard
                    362:   *** empty log message ***
                    363: 
1.219     brouard   364:   Revision 1.218  2016/02/12 11:29:23  brouard
                    365:   Summary: 0.99 Back projections
                    366: 
1.218     brouard   367:   Revision 1.217  2015/12/23 17:18:31  brouard
                    368:   Summary: Experimental backcast
                    369: 
1.217     brouard   370:   Revision 1.216  2015/12/18 17:32:11  brouard
                    371:   Summary: 0.98r4 Warning and status=-2
                    372: 
                    373:   Version 0.98r4 is now:
                    374:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    375:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    376:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    377: 
1.216     brouard   378:   Revision 1.215  2015/12/16 08:52:24  brouard
                    379:   Summary: 0.98r4 working
                    380: 
1.215     brouard   381:   Revision 1.214  2015/12/16 06:57:54  brouard
                    382:   Summary: temporary not working
                    383: 
1.214     brouard   384:   Revision 1.213  2015/12/11 18:22:17  brouard
                    385:   Summary: 0.98r4
                    386: 
1.213     brouard   387:   Revision 1.212  2015/11/21 12:47:24  brouard
                    388:   Summary: minor typo
                    389: 
1.212     brouard   390:   Revision 1.211  2015/11/21 12:41:11  brouard
                    391:   Summary: 0.98r3 with some graph of projected cross-sectional
                    392: 
                    393:   Author: Nicolas Brouard
                    394: 
1.211     brouard   395:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   396:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   397:   Summary: Adding ftolpl parameter
                    398:   Author: N Brouard
                    399: 
                    400:   We had difficulties to get smoothed confidence intervals. It was due
                    401:   to the period prevalence which wasn't computed accurately. The inner
                    402:   parameter ftolpl is now an outer parameter of the .imach parameter
                    403:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    404:   computation are long.
                    405: 
1.209     brouard   406:   Revision 1.208  2015/11/17 14:31:57  brouard
                    407:   Summary: temporary
                    408: 
1.208     brouard   409:   Revision 1.207  2015/10/27 17:36:57  brouard
                    410:   *** empty log message ***
                    411: 
1.207     brouard   412:   Revision 1.206  2015/10/24 07:14:11  brouard
                    413:   *** empty log message ***
                    414: 
1.206     brouard   415:   Revision 1.205  2015/10/23 15:50:53  brouard
                    416:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    417: 
1.205     brouard   418:   Revision 1.204  2015/10/01 16:20:26  brouard
                    419:   Summary: Some new graphs of contribution to likelihood
                    420: 
1.204     brouard   421:   Revision 1.203  2015/09/30 17:45:14  brouard
                    422:   Summary: looking at better estimation of the hessian
                    423: 
                    424:   Also a better criteria for convergence to the period prevalence And
                    425:   therefore adding the number of years needed to converge. (The
                    426:   prevalence in any alive state shold sum to one
                    427: 
1.203     brouard   428:   Revision 1.202  2015/09/22 19:45:16  brouard
                    429:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    430: 
1.202     brouard   431:   Revision 1.201  2015/09/15 17:34:58  brouard
                    432:   Summary: 0.98r0
                    433: 
                    434:   - Some new graphs like suvival functions
                    435:   - Some bugs fixed like model=1+age+V2.
                    436: 
1.201     brouard   437:   Revision 1.200  2015/09/09 16:53:55  brouard
                    438:   Summary: Big bug thanks to Flavia
                    439: 
                    440:   Even model=1+age+V2. did not work anymore
                    441: 
1.200     brouard   442:   Revision 1.199  2015/09/07 14:09:23  brouard
                    443:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    444: 
1.199     brouard   445:   Revision 1.198  2015/09/03 07:14:39  brouard
                    446:   Summary: 0.98q5 Flavia
                    447: 
1.198     brouard   448:   Revision 1.197  2015/09/01 18:24:39  brouard
                    449:   *** empty log message ***
                    450: 
1.197     brouard   451:   Revision 1.196  2015/08/18 23:17:52  brouard
                    452:   Summary: 0.98q5
                    453: 
1.196     brouard   454:   Revision 1.195  2015/08/18 16:28:39  brouard
                    455:   Summary: Adding a hack for testing purpose
                    456: 
                    457:   After reading the title, ftol and model lines, if the comment line has
                    458:   a q, starting with #q, the answer at the end of the run is quit. It
                    459:   permits to run test files in batch with ctest. The former workaround was
                    460:   $ echo q | imach foo.imach
                    461: 
1.195     brouard   462:   Revision 1.194  2015/08/18 13:32:00  brouard
                    463:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    464: 
1.194     brouard   465:   Revision 1.193  2015/08/04 07:17:42  brouard
                    466:   Summary: 0.98q4
                    467: 
1.193     brouard   468:   Revision 1.192  2015/07/16 16:49:02  brouard
                    469:   Summary: Fixing some outputs
                    470: 
1.192     brouard   471:   Revision 1.191  2015/07/14 10:00:33  brouard
                    472:   Summary: Some fixes
                    473: 
1.191     brouard   474:   Revision 1.190  2015/05/05 08:51:13  brouard
                    475:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    476: 
                    477:   Fix 1+age+.
                    478: 
1.190     brouard   479:   Revision 1.189  2015/04/30 14:45:16  brouard
                    480:   Summary: 0.98q2
                    481: 
1.189     brouard   482:   Revision 1.188  2015/04/30 08:27:53  brouard
                    483:   *** empty log message ***
                    484: 
1.188     brouard   485:   Revision 1.187  2015/04/29 09:11:15  brouard
                    486:   *** empty log message ***
                    487: 
1.187     brouard   488:   Revision 1.186  2015/04/23 12:01:52  brouard
                    489:   Summary: V1*age is working now, version 0.98q1
                    490: 
                    491:   Some codes had been disabled in order to simplify and Vn*age was
                    492:   working in the optimization phase, ie, giving correct MLE parameters,
                    493:   but, as usual, outputs were not correct and program core dumped.
                    494: 
1.186     brouard   495:   Revision 1.185  2015/03/11 13:26:42  brouard
                    496:   Summary: Inclusion of compile and links command line for Intel Compiler
                    497: 
1.185     brouard   498:   Revision 1.184  2015/03/11 11:52:39  brouard
                    499:   Summary: Back from Windows 8. Intel Compiler
                    500: 
1.184     brouard   501:   Revision 1.183  2015/03/10 20:34:32  brouard
                    502:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    503: 
                    504:   We use directest instead of original Powell test; probably no
                    505:   incidence on the results, but better justifications;
                    506:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    507:   wrong results.
                    508: 
1.183     brouard   509:   Revision 1.182  2015/02/12 08:19:57  brouard
                    510:   Summary: Trying to keep directest which seems simpler and more general
                    511:   Author: Nicolas Brouard
                    512: 
1.182     brouard   513:   Revision 1.181  2015/02/11 23:22:24  brouard
                    514:   Summary: Comments on Powell added
                    515: 
                    516:   Author:
                    517: 
1.181     brouard   518:   Revision 1.180  2015/02/11 17:33:45  brouard
                    519:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    520: 
1.180     brouard   521:   Revision 1.179  2015/01/04 09:57:06  brouard
                    522:   Summary: back to OS/X
                    523: 
1.179     brouard   524:   Revision 1.178  2015/01/04 09:35:48  brouard
                    525:   *** empty log message ***
                    526: 
1.178     brouard   527:   Revision 1.177  2015/01/03 18:40:56  brouard
                    528:   Summary: Still testing ilc32 on OSX
                    529: 
1.177     brouard   530:   Revision 1.176  2015/01/03 16:45:04  brouard
                    531:   *** empty log message ***
                    532: 
1.176     brouard   533:   Revision 1.175  2015/01/03 16:33:42  brouard
                    534:   *** empty log message ***
                    535: 
1.175     brouard   536:   Revision 1.174  2015/01/03 16:15:49  brouard
                    537:   Summary: Still in cross-compilation
                    538: 
1.174     brouard   539:   Revision 1.173  2015/01/03 12:06:26  brouard
                    540:   Summary: trying to detect cross-compilation
                    541: 
1.173     brouard   542:   Revision 1.172  2014/12/27 12:07:47  brouard
                    543:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    544: 
1.172     brouard   545:   Revision 1.171  2014/12/23 13:26:59  brouard
                    546:   Summary: Back from Visual C
                    547: 
                    548:   Still problem with utsname.h on Windows
                    549: 
1.171     brouard   550:   Revision 1.170  2014/12/23 11:17:12  brouard
                    551:   Summary: Cleaning some \%% back to %%
                    552: 
                    553:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    554: 
1.170     brouard   555:   Revision 1.169  2014/12/22 23:08:31  brouard
                    556:   Summary: 0.98p
                    557: 
                    558:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    559: 
1.169     brouard   560:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   561:   Summary: update
1.169     brouard   562: 
1.168     brouard   563:   Revision 1.167  2014/12/22 13:50:56  brouard
                    564:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    565: 
                    566:   Testing on Linux 64
                    567: 
1.167     brouard   568:   Revision 1.166  2014/12/22 11:40:47  brouard
                    569:   *** empty log message ***
                    570: 
1.166     brouard   571:   Revision 1.165  2014/12/16 11:20:36  brouard
                    572:   Summary: After compiling on Visual C
                    573: 
                    574:   * imach.c (Module): Merging 1.61 to 1.162
                    575: 
1.165     brouard   576:   Revision 1.164  2014/12/16 10:52:11  brouard
                    577:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    578: 
                    579:   * imach.c (Module): Merging 1.61 to 1.162
                    580: 
1.164     brouard   581:   Revision 1.163  2014/12/16 10:30:11  brouard
                    582:   * imach.c (Module): Merging 1.61 to 1.162
                    583: 
1.163     brouard   584:   Revision 1.162  2014/09/25 11:43:39  brouard
                    585:   Summary: temporary backup 0.99!
                    586: 
1.162     brouard   587:   Revision 1.1  2014/09/16 11:06:58  brouard
                    588:   Summary: With some code (wrong) for nlopt
                    589: 
                    590:   Author:
                    591: 
                    592:   Revision 1.161  2014/09/15 20:41:41  brouard
                    593:   Summary: Problem with macro SQR on Intel compiler
                    594: 
1.161     brouard   595:   Revision 1.160  2014/09/02 09:24:05  brouard
                    596:   *** empty log message ***
                    597: 
1.160     brouard   598:   Revision 1.159  2014/09/01 10:34:10  brouard
                    599:   Summary: WIN32
                    600:   Author: Brouard
                    601: 
1.159     brouard   602:   Revision 1.158  2014/08/27 17:11:51  brouard
                    603:   *** empty log message ***
                    604: 
1.158     brouard   605:   Revision 1.157  2014/08/27 16:26:55  brouard
                    606:   Summary: Preparing windows Visual studio version
                    607:   Author: Brouard
                    608: 
                    609:   In order to compile on Visual studio, time.h is now correct and time_t
                    610:   and tm struct should be used. difftime should be used but sometimes I
                    611:   just make the differences in raw time format (time(&now).
                    612:   Trying to suppress #ifdef LINUX
                    613:   Add xdg-open for __linux in order to open default browser.
                    614: 
1.157     brouard   615:   Revision 1.156  2014/08/25 20:10:10  brouard
                    616:   *** empty log message ***
                    617: 
1.156     brouard   618:   Revision 1.155  2014/08/25 18:32:34  brouard
                    619:   Summary: New compile, minor changes
                    620:   Author: Brouard
                    621: 
1.155     brouard   622:   Revision 1.154  2014/06/20 17:32:08  brouard
                    623:   Summary: Outputs now all graphs of convergence to period prevalence
                    624: 
1.154     brouard   625:   Revision 1.153  2014/06/20 16:45:46  brouard
                    626:   Summary: If 3 live state, convergence to period prevalence on same graph
                    627:   Author: Brouard
                    628: 
1.153     brouard   629:   Revision 1.152  2014/06/18 17:54:09  brouard
                    630:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    631: 
1.152     brouard   632:   Revision 1.151  2014/06/18 16:43:30  brouard
                    633:   *** empty log message ***
                    634: 
1.151     brouard   635:   Revision 1.150  2014/06/18 16:42:35  brouard
                    636:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    637:   Author: brouard
                    638: 
1.150     brouard   639:   Revision 1.149  2014/06/18 15:51:14  brouard
                    640:   Summary: Some fixes in parameter files errors
                    641:   Author: Nicolas Brouard
                    642: 
1.149     brouard   643:   Revision 1.148  2014/06/17 17:38:48  brouard
                    644:   Summary: Nothing new
                    645:   Author: Brouard
                    646: 
                    647:   Just a new packaging for OS/X version 0.98nS
                    648: 
1.148     brouard   649:   Revision 1.147  2014/06/16 10:33:11  brouard
                    650:   *** empty log message ***
                    651: 
1.147     brouard   652:   Revision 1.146  2014/06/16 10:20:28  brouard
                    653:   Summary: Merge
                    654:   Author: Brouard
                    655: 
                    656:   Merge, before building revised version.
                    657: 
1.146     brouard   658:   Revision 1.145  2014/06/10 21:23:15  brouard
                    659:   Summary: Debugging with valgrind
                    660:   Author: Nicolas Brouard
                    661: 
                    662:   Lot of changes in order to output the results with some covariates
                    663:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    664:   improve the code.
                    665:   No more memory valgrind error but a lot has to be done in order to
                    666:   continue the work of splitting the code into subroutines.
                    667:   Also, decodemodel has been improved. Tricode is still not
                    668:   optimal. nbcode should be improved. Documentation has been added in
                    669:   the source code.
                    670: 
1.144     brouard   671:   Revision 1.143  2014/01/26 09:45:38  brouard
                    672:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    673: 
                    674:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    675:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    676: 
1.143     brouard   677:   Revision 1.142  2014/01/26 03:57:36  brouard
                    678:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    679: 
                    680:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    681: 
1.142     brouard   682:   Revision 1.141  2014/01/26 02:42:01  brouard
                    683:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    684: 
1.141     brouard   685:   Revision 1.140  2011/09/02 10:37:54  brouard
                    686:   Summary: times.h is ok with mingw32 now.
                    687: 
1.140     brouard   688:   Revision 1.139  2010/06/14 07:50:17  brouard
                    689:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    690:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    691: 
1.139     brouard   692:   Revision 1.138  2010/04/30 18:19:40  brouard
                    693:   *** empty log message ***
                    694: 
1.138     brouard   695:   Revision 1.137  2010/04/29 18:11:38  brouard
                    696:   (Module): Checking covariates for more complex models
                    697:   than V1+V2. A lot of change to be done. Unstable.
                    698: 
1.137     brouard   699:   Revision 1.136  2010/04/26 20:30:53  brouard
                    700:   (Module): merging some libgsl code. Fixing computation
                    701:   of likelione (using inter/intrapolation if mle = 0) in order to
                    702:   get same likelihood as if mle=1.
                    703:   Some cleaning of code and comments added.
                    704: 
1.136     brouard   705:   Revision 1.135  2009/10/29 15:33:14  brouard
                    706:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    707: 
1.135     brouard   708:   Revision 1.134  2009/10/29 13:18:53  brouard
                    709:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    710: 
1.134     brouard   711:   Revision 1.133  2009/07/06 10:21:25  brouard
                    712:   just nforces
                    713: 
1.133     brouard   714:   Revision 1.132  2009/07/06 08:22:05  brouard
                    715:   Many tings
                    716: 
1.132     brouard   717:   Revision 1.131  2009/06/20 16:22:47  brouard
                    718:   Some dimensions resccaled
                    719: 
1.131     brouard   720:   Revision 1.130  2009/05/26 06:44:34  brouard
                    721:   (Module): Max Covariate is now set to 20 instead of 8. A
                    722:   lot of cleaning with variables initialized to 0. Trying to make
                    723:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    724: 
1.130     brouard   725:   Revision 1.129  2007/08/31 13:49:27  lievre
                    726:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    727: 
1.129     lievre    728:   Revision 1.128  2006/06/30 13:02:05  brouard
                    729:   (Module): Clarifications on computing e.j
                    730: 
1.128     brouard   731:   Revision 1.127  2006/04/28 18:11:50  brouard
                    732:   (Module): Yes the sum of survivors was wrong since
                    733:   imach-114 because nhstepm was no more computed in the age
                    734:   loop. Now we define nhstepma in the age loop.
                    735:   (Module): In order to speed up (in case of numerous covariates) we
                    736:   compute health expectancies (without variances) in a first step
                    737:   and then all the health expectancies with variances or standard
                    738:   deviation (needs data from the Hessian matrices) which slows the
                    739:   computation.
                    740:   In the future we should be able to stop the program is only health
                    741:   expectancies and graph are needed without standard deviations.
                    742: 
1.127     brouard   743:   Revision 1.126  2006/04/28 17:23:28  brouard
                    744:   (Module): Yes the sum of survivors was wrong since
                    745:   imach-114 because nhstepm was no more computed in the age
                    746:   loop. Now we define nhstepma in the age loop.
                    747:   Version 0.98h
                    748: 
1.126     brouard   749:   Revision 1.125  2006/04/04 15:20:31  lievre
                    750:   Errors in calculation of health expectancies. Age was not initialized.
                    751:   Forecasting file added.
                    752: 
                    753:   Revision 1.124  2006/03/22 17:13:53  lievre
                    754:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    755:   The log-likelihood is printed in the log file
                    756: 
                    757:   Revision 1.123  2006/03/20 10:52:43  brouard
                    758:   * imach.c (Module): <title> changed, corresponds to .htm file
                    759:   name. <head> headers where missing.
                    760: 
                    761:   * imach.c (Module): Weights can have a decimal point as for
                    762:   English (a comma might work with a correct LC_NUMERIC environment,
                    763:   otherwise the weight is truncated).
                    764:   Modification of warning when the covariates values are not 0 or
                    765:   1.
                    766:   Version 0.98g
                    767: 
                    768:   Revision 1.122  2006/03/20 09:45:41  brouard
                    769:   (Module): Weights can have a decimal point as for
                    770:   English (a comma might work with a correct LC_NUMERIC environment,
                    771:   otherwise the weight is truncated).
                    772:   Modification of warning when the covariates values are not 0 or
                    773:   1.
                    774:   Version 0.98g
                    775: 
                    776:   Revision 1.121  2006/03/16 17:45:01  lievre
                    777:   * imach.c (Module): Comments concerning covariates added
                    778: 
                    779:   * imach.c (Module): refinements in the computation of lli if
                    780:   status=-2 in order to have more reliable computation if stepm is
                    781:   not 1 month. Version 0.98f
                    782: 
                    783:   Revision 1.120  2006/03/16 15:10:38  lievre
                    784:   (Module): refinements in the computation of lli if
                    785:   status=-2 in order to have more reliable computation if stepm is
                    786:   not 1 month. Version 0.98f
                    787: 
                    788:   Revision 1.119  2006/03/15 17:42:26  brouard
                    789:   (Module): Bug if status = -2, the loglikelihood was
                    790:   computed as likelihood omitting the logarithm. Version O.98e
                    791: 
                    792:   Revision 1.118  2006/03/14 18:20:07  brouard
                    793:   (Module): varevsij Comments added explaining the second
                    794:   table of variances if popbased=1 .
                    795:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    796:   (Module): Function pstamp added
                    797:   (Module): Version 0.98d
                    798: 
                    799:   Revision 1.117  2006/03/14 17:16:22  brouard
                    800:   (Module): varevsij Comments added explaining the second
                    801:   table of variances if popbased=1 .
                    802:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    803:   (Module): Function pstamp added
                    804:   (Module): Version 0.98d
                    805: 
                    806:   Revision 1.116  2006/03/06 10:29:27  brouard
                    807:   (Module): Variance-covariance wrong links and
                    808:   varian-covariance of ej. is needed (Saito).
                    809: 
                    810:   Revision 1.115  2006/02/27 12:17:45  brouard
                    811:   (Module): One freematrix added in mlikeli! 0.98c
                    812: 
                    813:   Revision 1.114  2006/02/26 12:57:58  brouard
                    814:   (Module): Some improvements in processing parameter
                    815:   filename with strsep.
                    816: 
                    817:   Revision 1.113  2006/02/24 14:20:24  brouard
                    818:   (Module): Memory leaks checks with valgrind and:
                    819:   datafile was not closed, some imatrix were not freed and on matrix
                    820:   allocation too.
                    821: 
                    822:   Revision 1.112  2006/01/30 09:55:26  brouard
                    823:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    824: 
                    825:   Revision 1.111  2006/01/25 20:38:18  brouard
                    826:   (Module): Lots of cleaning and bugs added (Gompertz)
                    827:   (Module): Comments can be added in data file. Missing date values
                    828:   can be a simple dot '.'.
                    829: 
                    830:   Revision 1.110  2006/01/25 00:51:50  brouard
                    831:   (Module): Lots of cleaning and bugs added (Gompertz)
                    832: 
                    833:   Revision 1.109  2006/01/24 19:37:15  brouard
                    834:   (Module): Comments (lines starting with a #) are allowed in data.
                    835: 
                    836:   Revision 1.108  2006/01/19 18:05:42  lievre
                    837:   Gnuplot problem appeared...
                    838:   To be fixed
                    839: 
                    840:   Revision 1.107  2006/01/19 16:20:37  brouard
                    841:   Test existence of gnuplot in imach path
                    842: 
                    843:   Revision 1.106  2006/01/19 13:24:36  brouard
                    844:   Some cleaning and links added in html output
                    845: 
                    846:   Revision 1.105  2006/01/05 20:23:19  lievre
                    847:   *** empty log message ***
                    848: 
                    849:   Revision 1.104  2005/09/30 16:11:43  lievre
                    850:   (Module): sump fixed, loop imx fixed, and simplifications.
                    851:   (Module): If the status is missing at the last wave but we know
                    852:   that the person is alive, then we can code his/her status as -2
                    853:   (instead of missing=-1 in earlier versions) and his/her
                    854:   contributions to the likelihood is 1 - Prob of dying from last
                    855:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    856:   the healthy state at last known wave). Version is 0.98
                    857: 
                    858:   Revision 1.103  2005/09/30 15:54:49  lievre
                    859:   (Module): sump fixed, loop imx fixed, and simplifications.
                    860: 
                    861:   Revision 1.102  2004/09/15 17:31:30  brouard
                    862:   Add the possibility to read data file including tab characters.
                    863: 
                    864:   Revision 1.101  2004/09/15 10:38:38  brouard
                    865:   Fix on curr_time
                    866: 
                    867:   Revision 1.100  2004/07/12 18:29:06  brouard
                    868:   Add version for Mac OS X. Just define UNIX in Makefile
                    869: 
                    870:   Revision 1.99  2004/06/05 08:57:40  brouard
                    871:   *** empty log message ***
                    872: 
                    873:   Revision 1.98  2004/05/16 15:05:56  brouard
                    874:   New version 0.97 . First attempt to estimate force of mortality
                    875:   directly from the data i.e. without the need of knowing the health
                    876:   state at each age, but using a Gompertz model: log u =a + b*age .
                    877:   This is the basic analysis of mortality and should be done before any
                    878:   other analysis, in order to test if the mortality estimated from the
                    879:   cross-longitudinal survey is different from the mortality estimated
                    880:   from other sources like vital statistic data.
                    881: 
                    882:   The same imach parameter file can be used but the option for mle should be -3.
                    883: 
1.324     brouard   884:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   885:   former routines in order to include the new code within the former code.
                    886: 
                    887:   The output is very simple: only an estimate of the intercept and of
                    888:   the slope with 95% confident intervals.
                    889: 
                    890:   Current limitations:
                    891:   A) Even if you enter covariates, i.e. with the
                    892:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    893:   B) There is no computation of Life Expectancy nor Life Table.
                    894: 
                    895:   Revision 1.97  2004/02/20 13:25:42  lievre
                    896:   Version 0.96d. Population forecasting command line is (temporarily)
                    897:   suppressed.
                    898: 
                    899:   Revision 1.96  2003/07/15 15:38:55  brouard
                    900:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    901:   rewritten within the same printf. Workaround: many printfs.
                    902: 
                    903:   Revision 1.95  2003/07/08 07:54:34  brouard
                    904:   * imach.c (Repository):
                    905:   (Repository): Using imachwizard code to output a more meaningful covariance
                    906:   matrix (cov(a12,c31) instead of numbers.
                    907: 
                    908:   Revision 1.94  2003/06/27 13:00:02  brouard
                    909:   Just cleaning
                    910: 
                    911:   Revision 1.93  2003/06/25 16:33:55  brouard
                    912:   (Module): On windows (cygwin) function asctime_r doesn't
                    913:   exist so I changed back to asctime which exists.
                    914:   (Module): Version 0.96b
                    915: 
                    916:   Revision 1.92  2003/06/25 16:30:45  brouard
                    917:   (Module): On windows (cygwin) function asctime_r doesn't
                    918:   exist so I changed back to asctime which exists.
                    919: 
                    920:   Revision 1.91  2003/06/25 15:30:29  brouard
                    921:   * imach.c (Repository): Duplicated warning errors corrected.
                    922:   (Repository): Elapsed time after each iteration is now output. It
                    923:   helps to forecast when convergence will be reached. Elapsed time
                    924:   is stamped in powell.  We created a new html file for the graphs
                    925:   concerning matrix of covariance. It has extension -cov.htm.
                    926: 
                    927:   Revision 1.90  2003/06/24 12:34:15  brouard
                    928:   (Module): Some bugs corrected for windows. Also, when
                    929:   mle=-1 a template is output in file "or"mypar.txt with the design
                    930:   of the covariance matrix to be input.
                    931: 
                    932:   Revision 1.89  2003/06/24 12:30:52  brouard
                    933:   (Module): Some bugs corrected for windows. Also, when
                    934:   mle=-1 a template is output in file "or"mypar.txt with the design
                    935:   of the covariance matrix to be input.
                    936: 
                    937:   Revision 1.88  2003/06/23 17:54:56  brouard
                    938:   * 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.
                    939: 
                    940:   Revision 1.87  2003/06/18 12:26:01  brouard
                    941:   Version 0.96
                    942: 
                    943:   Revision 1.86  2003/06/17 20:04:08  brouard
                    944:   (Module): Change position of html and gnuplot routines and added
                    945:   routine fileappend.
                    946: 
                    947:   Revision 1.85  2003/06/17 13:12:43  brouard
                    948:   * imach.c (Repository): Check when date of death was earlier that
                    949:   current date of interview. It may happen when the death was just
                    950:   prior to the death. In this case, dh was negative and likelihood
                    951:   was wrong (infinity). We still send an "Error" but patch by
                    952:   assuming that the date of death was just one stepm after the
                    953:   interview.
                    954:   (Repository): Because some people have very long ID (first column)
                    955:   we changed int to long in num[] and we added a new lvector for
                    956:   memory allocation. But we also truncated to 8 characters (left
                    957:   truncation)
                    958:   (Repository): No more line truncation errors.
                    959: 
                    960:   Revision 1.84  2003/06/13 21:44:43  brouard
                    961:   * imach.c (Repository): Replace "freqsummary" at a correct
                    962:   place. It differs from routine "prevalence" which may be called
                    963:   many times. Probs is memory consuming and must be used with
                    964:   parcimony.
                    965:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    966: 
                    967:   Revision 1.83  2003/06/10 13:39:11  lievre
                    968:   *** empty log message ***
                    969: 
                    970:   Revision 1.82  2003/06/05 15:57:20  brouard
                    971:   Add log in  imach.c and  fullversion number is now printed.
                    972: 
                    973: */
                    974: /*
                    975:    Interpolated Markov Chain
                    976: 
                    977:   Short summary of the programme:
                    978:   
1.227     brouard   979:   This program computes Healthy Life Expectancies or State-specific
                    980:   (if states aren't health statuses) Expectancies from
                    981:   cross-longitudinal data. Cross-longitudinal data consist in: 
                    982: 
                    983:   -1- a first survey ("cross") where individuals from different ages
                    984:   are interviewed on their health status or degree of disability (in
                    985:   the case of a health survey which is our main interest)
                    986: 
                    987:   -2- at least a second wave of interviews ("longitudinal") which
                    988:   measure each change (if any) in individual health status.  Health
                    989:   expectancies are computed from the time spent in each health state
                    990:   according to a model. More health states you consider, more time is
                    991:   necessary to reach the Maximum Likelihood of the parameters involved
                    992:   in the model.  The simplest model is the multinomial logistic model
                    993:   where pij is the probability to be observed in state j at the second
                    994:   wave conditional to be observed in state i at the first
                    995:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                    996:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                    997:   have a more complex model than "constant and age", you should modify
                    998:   the program where the markup *Covariates have to be included here
                    999:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard  1000:   convergence.
                   1001: 
                   1002:   The advantage of this computer programme, compared to a simple
                   1003:   multinomial logistic model, is clear when the delay between waves is not
                   1004:   identical for each individual. Also, if a individual missed an
                   1005:   intermediate interview, the information is lost, but taken into
                   1006:   account using an interpolation or extrapolation.  
                   1007: 
                   1008:   hPijx is the probability to be observed in state i at age x+h
                   1009:   conditional to the observed state i at age x. The delay 'h' can be
                   1010:   split into an exact number (nh*stepm) of unobserved intermediate
                   1011:   states. This elementary transition (by month, quarter,
                   1012:   semester or year) is modelled as a multinomial logistic.  The hPx
                   1013:   matrix is simply the matrix product of nh*stepm elementary matrices
                   1014:   and the contribution of each individual to the likelihood is simply
                   1015:   hPijx.
                   1016: 
                   1017:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard  1018:   of the life expectancies. It also computes the period (stable) prevalence.
                   1019: 
                   1020: Back prevalence and projections:
1.227     brouard  1021: 
                   1022:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                   1023:    double agemaxpar, double ftolpl, int *ncvyearp, double
                   1024:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                   1025:    mobilavproj)
                   1026: 
                   1027:     Computes the back prevalence limit for any combination of
                   1028:     covariate values k at any age between ageminpar and agemaxpar and
                   1029:     returns it in **bprlim. In the loops,
                   1030: 
                   1031:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                   1032:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                   1033: 
                   1034:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard  1035:    Computes for any combination of covariates k and any age between bage and fage 
                   1036:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1037:                        oldm=oldms;savm=savms;
1.227     brouard  1038: 
1.267     brouard  1039:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard  1040:      Computes the transition matrix starting at age 'age' over
                   1041:      'nhstepm*hstepm*stepm' months (i.e. until
                   1042:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard  1043:      nhstepm*hstepm matrices. 
                   1044: 
                   1045:      Returns p3mat[i][j][h] after calling
                   1046:      p3mat[i][j][h]=matprod2(newm,
                   1047:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                   1048:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                   1049:      oldm);
1.226     brouard  1050: 
                   1051: Important routines
                   1052: 
                   1053: - func (or funcone), computes logit (pij) distinguishing
                   1054:   o fixed variables (single or product dummies or quantitative);
                   1055:   o varying variables by:
                   1056:    (1) wave (single, product dummies, quantitative), 
                   1057:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                   1058:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                   1059:        % varying dummy (not done) or quantitative (not done);
                   1060: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                   1061:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                   1062: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
1.325     brouard  1063:   o There are 2**cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
1.226     brouard  1064:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard  1065: 
1.226     brouard  1066: 
                   1067:   
1.324     brouard  1068:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                   1069:            Institut national d'études démographiques, Paris.
1.126     brouard  1070:   This software have been partly granted by Euro-REVES, a concerted action
                   1071:   from the European Union.
                   1072:   It is copyrighted identically to a GNU software product, ie programme and
                   1073:   software can be distributed freely for non commercial use. Latest version
                   1074:   can be accessed at http://euroreves.ined.fr/imach .
                   1075: 
                   1076:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                   1077:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                   1078:   
                   1079:   **********************************************************************/
                   1080: /*
                   1081:   main
                   1082:   read parameterfile
                   1083:   read datafile
                   1084:   concatwav
                   1085:   freqsummary
                   1086:   if (mle >= 1)
                   1087:     mlikeli
                   1088:   print results files
                   1089:   if mle==1 
                   1090:      computes hessian
                   1091:   read end of parameter file: agemin, agemax, bage, fage, estepm
                   1092:       begin-prev-date,...
                   1093:   open gnuplot file
                   1094:   open html file
1.145     brouard  1095:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1096:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1097:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1098:     freexexit2 possible for memory heap.
                   1099: 
                   1100:   h Pij x                         | pij_nom  ficrestpij
                   1101:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1102:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1103:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1104: 
                   1105:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1106:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1107:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1108:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1109:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1110: 
1.126     brouard  1111:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1112:   health expectancies
                   1113:   Variance-covariance of DFLE
                   1114:   prevalence()
                   1115:    movingaverage()
                   1116:   varevsij() 
                   1117:   if popbased==1 varevsij(,popbased)
                   1118:   total life expectancies
                   1119:   Variance of period (stable) prevalence
                   1120:  end
                   1121: */
                   1122: 
1.187     brouard  1123: /* #define DEBUG */
                   1124: /* #define DEBUGBRENT */
1.203     brouard  1125: /* #define DEBUGLINMIN */
                   1126: /* #define DEBUGHESS */
                   1127: #define DEBUGHESSIJ
1.224     brouard  1128: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1129: #define POWELL /* Instead of NLOPT */
1.224     brouard  1130: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1131: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1132: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.319     brouard  1133: /* #define FLATSUP  *//* Suppresses directions where likelihood is flat */
1.126     brouard  1134: 
                   1135: #include <math.h>
                   1136: #include <stdio.h>
                   1137: #include <stdlib.h>
                   1138: #include <string.h>
1.226     brouard  1139: #include <ctype.h>
1.159     brouard  1140: 
                   1141: #ifdef _WIN32
                   1142: #include <io.h>
1.172     brouard  1143: #include <windows.h>
                   1144: #include <tchar.h>
1.159     brouard  1145: #else
1.126     brouard  1146: #include <unistd.h>
1.159     brouard  1147: #endif
1.126     brouard  1148: 
                   1149: #include <limits.h>
                   1150: #include <sys/types.h>
1.171     brouard  1151: 
                   1152: #if defined(__GNUC__)
                   1153: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1154: #endif
                   1155: 
1.126     brouard  1156: #include <sys/stat.h>
                   1157: #include <errno.h>
1.159     brouard  1158: /* extern int errno; */
1.126     brouard  1159: 
1.157     brouard  1160: /* #ifdef LINUX */
                   1161: /* #include <time.h> */
                   1162: /* #include "timeval.h" */
                   1163: /* #else */
                   1164: /* #include <sys/time.h> */
                   1165: /* #endif */
                   1166: 
1.126     brouard  1167: #include <time.h>
                   1168: 
1.136     brouard  1169: #ifdef GSL
                   1170: #include <gsl/gsl_errno.h>
                   1171: #include <gsl/gsl_multimin.h>
                   1172: #endif
                   1173: 
1.167     brouard  1174: 
1.162     brouard  1175: #ifdef NLOPT
                   1176: #include <nlopt.h>
                   1177: typedef struct {
                   1178:   double (* function)(double [] );
                   1179: } myfunc_data ;
                   1180: #endif
                   1181: 
1.126     brouard  1182: /* #include <libintl.h> */
                   1183: /* #define _(String) gettext (String) */
                   1184: 
1.251     brouard  1185: #define MAXLINE 2048 /* Was 256 and 1024. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1186: 
                   1187: #define GNUPLOTPROGRAM "gnuplot"
                   1188: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                   1189: #define FILENAMELENGTH 132
                   1190: 
                   1191: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1192: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1193: 
1.144     brouard  1194: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                   1195: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1196: 
                   1197: #define NINTERVMAX 8
1.144     brouard  1198: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1199: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.325     brouard  1200: #define NCOVMAX 30  /**< Maximum number of covariates used in the model, including generated covariates V1*V2 or V1*age */
1.197     brouard  1201: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1202: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1203: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1204: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1205: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1206: /* #define AGESUP 130 */
1.288     brouard  1207: /* #define AGESUP 150 */
                   1208: #define AGESUP 200
1.268     brouard  1209: #define AGEINF 0
1.218     brouard  1210: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1211: #define AGEBASE 40
1.194     brouard  1212: #define AGEOVERFLOW 1.e20
1.164     brouard  1213: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1214: #ifdef _WIN32
                   1215: #define DIRSEPARATOR '\\'
                   1216: #define CHARSEPARATOR "\\"
                   1217: #define ODIRSEPARATOR '/'
                   1218: #else
1.126     brouard  1219: #define DIRSEPARATOR '/'
                   1220: #define CHARSEPARATOR "/"
                   1221: #define ODIRSEPARATOR '\\'
                   1222: #endif
                   1223: 
1.327   ! brouard  1224: /* $Id: imach.c,v 1.326 2022/07/26 17:33:55 brouard Exp $ */
1.126     brouard  1225: /* $State: Exp $ */
1.196     brouard  1226: #include "version.h"
                   1227: char version[]=__IMACH_VERSION__;
1.323     brouard  1228: char copyright[]="July 2022,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015-2020, Nihon University 2021-202, INED 2000-2022";
1.327   ! brouard  1229: char fullversion[]="$Revision: 1.326 $ $Date: 2022/07/26 17:33:55 $"; 
1.126     brouard  1230: char strstart[80];
                   1231: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1232: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard  1233: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard  1234: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                   1235: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                   1236: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
1.225     brouard  1237: int cptcovs=0; /**< cptcovs number of simple covariates in the model V2+V1 =2 */
                   1238: int cptcovsnq=0; /**< cptcovsnq number of simple covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1239: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                   1240: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                   1241: int cptcoveff=0; /* Total number of covariates to vary for printing results */
1.233     brouard  1242: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1243: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.232     brouard  1244: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
1.234     brouard  1245: int nsd=0; /**< Total number of single dummy variables (output) */
                   1246: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1247: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1248: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1249: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1250: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1251: int cptcov=0; /* Working variable */
1.290     brouard  1252: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1253: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.302     brouard  1254: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
1.126     brouard  1255: int nlstate=2; /* Number of live states */
                   1256: int ndeath=1; /* Number of dead states */
1.130     brouard  1257: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.223     brouard  1258: int  nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable */ 
1.126     brouard  1259: int popbased=0;
                   1260: 
                   1261: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1262: int maxwav=0; /* Maxim number of waves */
                   1263: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1264: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1265: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard  1266:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1267: int mle=1, weightopt=0;
1.126     brouard  1268: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1269: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1270: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1271:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1272: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1273: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1274: 
1.130     brouard  1275: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1276: double **matprod2(); /* test */
1.126     brouard  1277: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1278: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1279: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1280: 
1.136     brouard  1281: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1282: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1283: FILE *ficlog, *ficrespow;
1.130     brouard  1284: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1285: double fretone; /* Only one call to likelihood */
1.130     brouard  1286: long ipmx=0; /* Number of contributions */
1.126     brouard  1287: double sw; /* Sum of weights */
                   1288: char filerespow[FILENAMELENGTH];
                   1289: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1290: FILE *ficresilk;
                   1291: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1292: FILE *ficresprobmorprev;
                   1293: FILE *fichtm, *fichtmcov; /* Html File */
                   1294: FILE *ficreseij;
                   1295: char filerese[FILENAMELENGTH];
                   1296: FILE *ficresstdeij;
                   1297: char fileresstde[FILENAMELENGTH];
                   1298: FILE *ficrescveij;
                   1299: char filerescve[FILENAMELENGTH];
                   1300: FILE  *ficresvij;
                   1301: char fileresv[FILENAMELENGTH];
1.269     brouard  1302: 
1.126     brouard  1303: char title[MAXLINE];
1.234     brouard  1304: char model[MAXLINE]; /**< The model line */
1.217     brouard  1305: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1306: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1307: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1308: char command[FILENAMELENGTH];
                   1309: int  outcmd=0;
                   1310: 
1.217     brouard  1311: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1312: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1313: char filelog[FILENAMELENGTH]; /* Log file */
                   1314: char filerest[FILENAMELENGTH];
                   1315: char fileregp[FILENAMELENGTH];
                   1316: char popfile[FILENAMELENGTH];
                   1317: 
                   1318: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1319: 
1.157     brouard  1320: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1321: /* struct timezone tzp; */
                   1322: /* extern int gettimeofday(); */
                   1323: struct tm tml, *gmtime(), *localtime();
                   1324: 
                   1325: extern time_t time();
                   1326: 
                   1327: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1328: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                   1329: struct tm tm;
                   1330: 
1.126     brouard  1331: char strcurr[80], strfor[80];
                   1332: 
                   1333: char *endptr;
                   1334: long lval;
                   1335: double dval;
                   1336: 
                   1337: #define NR_END 1
                   1338: #define FREE_ARG char*
                   1339: #define FTOL 1.0e-10
                   1340: 
                   1341: #define NRANSI 
1.240     brouard  1342: #define ITMAX 200
                   1343: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1344: 
                   1345: #define TOL 2.0e-4 
                   1346: 
                   1347: #define CGOLD 0.3819660 
                   1348: #define ZEPS 1.0e-10 
                   1349: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1350: 
                   1351: #define GOLD 1.618034 
                   1352: #define GLIMIT 100.0 
                   1353: #define TINY 1.0e-20 
                   1354: 
                   1355: static double maxarg1,maxarg2;
                   1356: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1357: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1358:   
                   1359: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1360: #define rint(a) floor(a+0.5)
1.166     brouard  1361: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1362: #define mytinydouble 1.0e-16
1.166     brouard  1363: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1364: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1365: /* static double dsqrarg; */
                   1366: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1367: static double sqrarg;
                   1368: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1369: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1370: int agegomp= AGEGOMP;
                   1371: 
                   1372: int imx; 
                   1373: int stepm=1;
                   1374: /* Stepm, step in month: minimum step interpolation*/
                   1375: 
                   1376: int estepm;
                   1377: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1378: 
                   1379: int m,nb;
                   1380: long *num;
1.197     brouard  1381: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1382: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1383:                   covariate for which somebody answered excluding 
                   1384:                   undefined. Usually 2: 0 and 1. */
                   1385: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1386:                             covariate for which somebody answered including 
                   1387:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1388: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1389: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1390: double ***mobaverage, ***mobaverages; /* New global variable */
1.126     brouard  1391: double *ageexmed,*agecens;
                   1392: double dateintmean=0;
1.296     brouard  1393:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1394:   double anprojf, mprojf, jprojf;
1.126     brouard  1395: 
1.296     brouard  1396:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1397:   double anbackf, mbackf, jbackf;
                   1398:   double jintmean,mintmean,aintmean;  
1.126     brouard  1399: double *weight;
                   1400: int **s; /* Status */
1.141     brouard  1401: double *agedc;
1.145     brouard  1402: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1403:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1404:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1405: double **coqvar; /* Fixed quantitative covariate nqv */
                   1406: double ***cotvar; /* Time varying covariate ntv */
1.225     brouard  1407: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1408: double  idx; 
                   1409: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.319     brouard  1410: /* Some documentation */
                   1411:       /*   Design original data
                   1412:        *  V1   V2   V3   V4  V5  V6  V7  V8  Weight ddb ddth d1st s1 V9 V10 V11 V12 s2 V9 V10 V11 V12 
                   1413:        *  <          ncovcol=6   >   nqv=2 (V7 V8)                   dv dv  dv  qtv    dv dv  dvv qtv
                   1414:        *                                                             ntv=3     nqtv=1
                   1415:        *  cptcovn number of covariates (not including constant and age) = # of + plus 1 = 10+1=11
                   1416:        * For time varying covariate, quanti or dummies
                   1417:        *       cotqvar[wav][iv(1 to nqtv)][i]= [1][12][i]=(V12) quanti
                   1418:        *       cotvar[wav][ntv+iv][i]= [3+(1 to nqtv)][i]=(V12) quanti
                   1419:        *       cotvar[wav][iv(1 to ntv)][i]= [1][1][i]=(V9) dummies at wav 1
                   1420:        *       cotvar[wav][iv(1 to ntv)][i]= [1][2][i]=(V10) dummies at wav 1
                   1421:        *       covar[k,i], value of kth fixed covariate dummy or quanti :
                   1422:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   1423:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 + V9 + V9*age + V10
                   1424:        *   k=  1    2      3       4     5       6      7        8   9     10       11 
                   1425:        */
                   1426: /* According to the model, more columns can be added to covar by the product of covariates */
1.318     brouard  1427: /* 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
                   1428:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1429:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1430: */
1.319     brouard  1431: /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1432: /*    k        1  2   3   4     5    6    7     8    9 */
                   1433: /*Typevar[k]=  0  0   0   2     1    0    2     1    0 *//*0 for simple covariate (dummy, quantitative,*/
                   1434:                                                          /* fixed or varying), 1 for age product, 2 for*/
                   1435:                                                          /* product */
                   1436: /*Dummy[k]=    1  0   0   1     3    1    1     2    0 *//*Dummy[k] 0=dummy (0 1), 1 quantitative */
                   1437:                                                          /*(single or product without age), 2 dummy*/
                   1438:                                                          /* with age product, 3 quant with age product*/
                   1439: /*Tvar[k]=     5  4   3   6     5    2    7     1    1 */
                   1440: /*    nsd         1   2                              3 */ /* Counting single dummies covar fixed or tv */
                   1441: /*TvarsD[nsd]     4   3                              1 */ /* ID of single dummy cova fixed or timevary*/
                   1442: /*TvarsDind[k]    2   3                              9 */ /* position K of single dummy cova */
                   1443: /*    nsq      1                     2                 */ /* Counting single quantit tv */
                   1444: /* TvarsQ[k]   5                     2                 */ /* Number of single quantitative cova */
                   1445: /* TvarsQind   1                     6                 */ /* position K of single quantitative cova */
                   1446: /* Tprod[i]=k             1               2            */ /* Position in model of the ith prod without age */
                   1447: /* cptcovage                    1               2      */ /* Counting cov*age in the model equation */
                   1448: /* Tage[cptcovage]=k            5               8      */ /* Position in the model of ith cov*age */
                   1449: /* Tvard[1][1]@4={4,3,1,2}    V4*V3 V1*V2              */ /* Position in model of the ith prod without age */
                   1450: /* 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  1451: /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.234     brouard  1452: /* Type                    */
                   1453: /* V         1  2  3  4  5 */
                   1454: /*           F  F  V  V  V */
                   1455: /*           D  Q  D  D  Q */
                   1456: /*                         */
                   1457: int *TvarsD;
                   1458: int *TvarsDind;
                   1459: int *TvarsQ;
                   1460: int *TvarsQind;
                   1461: 
1.318     brouard  1462: #define MAXRESULTLINESPONE 10+1
1.235     brouard  1463: int nresult=0;
1.258     brouard  1464: int parameterline=0; /* # of the parameter (type) line */
1.318     brouard  1465: int TKresult[MAXRESULTLINESPONE];
                   1466: int Tresult[MAXRESULTLINESPONE][NCOVMAX];/* For dummy variable , value (output) */
                   1467: int Tinvresult[MAXRESULTLINESPONE][NCOVMAX];/* For dummy variable , value (output) */
                   1468: int Tvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For dummy variable , variable # (output) */
                   1469: double Tqresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
                   1470: double Tqinvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
                   1471: int Tvqresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , variable # (output) */
                   1472: 
                   1473: /* 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
                   1474:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1475:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1476: */
1.234     brouard  1477: /* 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  1478: 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 */
                   1479: 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 */
                   1480: 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 */
                   1481: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1482: 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 */
                   1483: 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  1484: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1485: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1486: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1487: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1488: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1489: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1490: 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 */
                   1491: 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 */
                   1492: 
1.230     brouard  1493: int *Tvarsel; /**< Selected covariates for output */
                   1494: double *Tvalsel; /**< Selected modality value of covariate for output */
1.226     brouard  1495: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.227     brouard  1496: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1497: 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  1498: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1499: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1500: int *Tage;
1.227     brouard  1501: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1502: 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  1503: 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*/ 
                   1504: 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  1505: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1506: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1507: int **Tvard;
                   1508: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1509: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1510: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1511:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1512:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1513: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1514: double *lsurv, *lpop, *tpop;
                   1515: 
1.231     brouard  1516: #define FD 1; /* Fixed dummy covariate */
                   1517: #define FQ 2; /* Fixed quantitative covariate */
                   1518: #define FP 3; /* Fixed product covariate */
                   1519: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1520: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1521: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1522: #define VD 10; /* Varying dummy covariate */
                   1523: #define VQ 11; /* Varying quantitative covariate */
                   1524: #define VP 12; /* Varying product covariate */
                   1525: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1526: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1527: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1528: #define APFD 16; /* Age product * fixed dummy covariate */
                   1529: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1530: #define APVD 18; /* Age product * varying dummy covariate */
                   1531: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1532: 
                   1533: #define FTYPE 1; /* Fixed covariate */
                   1534: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1535: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1536: 
                   1537: struct kmodel{
                   1538:        int maintype; /* main type */
                   1539:        int subtype; /* subtype */
                   1540: };
                   1541: struct kmodel modell[NCOVMAX];
                   1542: 
1.143     brouard  1543: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1544: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1545: 
                   1546: /**************** split *************************/
                   1547: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1548: {
                   1549:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1550:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1551:   */ 
                   1552:   char *ss;                            /* pointer */
1.186     brouard  1553:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1554: 
                   1555:   l1 = strlen(path );                  /* length of path */
                   1556:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1557:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1558:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1559:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1560:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1561:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1562:     /* get current working directory */
                   1563:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1564: #ifdef WIN32
                   1565:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1566: #else
                   1567:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1568: #endif
1.126     brouard  1569:       return( GLOCK_ERROR_GETCWD );
                   1570:     }
                   1571:     /* got dirc from getcwd*/
                   1572:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1573:   } else {                             /* strip directory from path */
1.126     brouard  1574:     ss++;                              /* after this, the filename */
                   1575:     l2 = strlen( ss );                 /* length of filename */
                   1576:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1577:     strcpy( name, ss );                /* save file name */
                   1578:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1579:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1580:     printf(" DIRC2 = %s \n",dirc);
                   1581:   }
                   1582:   /* We add a separator at the end of dirc if not exists */
                   1583:   l1 = strlen( dirc );                 /* length of directory */
                   1584:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1585:     dirc[l1] =  DIRSEPARATOR;
                   1586:     dirc[l1+1] = 0; 
                   1587:     printf(" DIRC3 = %s \n",dirc);
                   1588:   }
                   1589:   ss = strrchr( name, '.' );           /* find last / */
                   1590:   if (ss >0){
                   1591:     ss++;
                   1592:     strcpy(ext,ss);                    /* save extension */
                   1593:     l1= strlen( name);
                   1594:     l2= strlen(ss)+1;
                   1595:     strncpy( finame, name, l1-l2);
                   1596:     finame[l1-l2]= 0;
                   1597:   }
                   1598: 
                   1599:   return( 0 );                         /* we're done */
                   1600: }
                   1601: 
                   1602: 
                   1603: /******************************************/
                   1604: 
                   1605: void replace_back_to_slash(char *s, char*t)
                   1606: {
                   1607:   int i;
                   1608:   int lg=0;
                   1609:   i=0;
                   1610:   lg=strlen(t);
                   1611:   for(i=0; i<= lg; i++) {
                   1612:     (s[i] = t[i]);
                   1613:     if (t[i]== '\\') s[i]='/';
                   1614:   }
                   1615: }
                   1616: 
1.132     brouard  1617: char *trimbb(char *out, char *in)
1.137     brouard  1618: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1619:   char *s;
                   1620:   s=out;
                   1621:   while (*in != '\0'){
1.137     brouard  1622:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1623:       in++;
                   1624:     }
                   1625:     *out++ = *in++;
                   1626:   }
                   1627:   *out='\0';
                   1628:   return s;
                   1629: }
                   1630: 
1.187     brouard  1631: /* char *substrchaine(char *out, char *in, char *chain) */
                   1632: /* { */
                   1633: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1634: /*   char *s, *t; */
                   1635: /*   t=in;s=out; */
                   1636: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1637: /*     *out++ = *in++; */
                   1638: /*   } */
                   1639: 
                   1640: /*   /\* *in matches *chain *\/ */
                   1641: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1642: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1643: /*   } */
                   1644: /*   in--; chain--; */
                   1645: /*   while ( (*in != '\0')){ */
                   1646: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1647: /*     *out++ = *in++; */
                   1648: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1649: /*   } */
                   1650: /*   *out='\0'; */
                   1651: /*   out=s; */
                   1652: /*   return out; */
                   1653: /* } */
                   1654: char *substrchaine(char *out, char *in, char *chain)
                   1655: {
                   1656:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1657:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1658: 
                   1659:   char *strloc;
                   1660: 
                   1661:   strcpy (out, in); 
                   1662:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1663:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1664:   if(strloc != NULL){ 
                   1665:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1666:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1667:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1668:   }
                   1669:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1670:   return out;
                   1671: }
                   1672: 
                   1673: 
1.145     brouard  1674: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1675: {
1.187     brouard  1676:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1677:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.310     brouard  1678:      gives alocc="abcdef" and blocc="ghi2j".
1.145     brouard  1679:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1680:   */
1.160     brouard  1681:   char *s, *t;
1.145     brouard  1682:   t=in;s=in;
                   1683:   while ((*in != occ) && (*in != '\0')){
                   1684:     *alocc++ = *in++;
                   1685:   }
                   1686:   if( *in == occ){
                   1687:     *(alocc)='\0';
                   1688:     s=++in;
                   1689:   }
                   1690:  
                   1691:   if (s == t) {/* occ not found */
                   1692:     *(alocc-(in-s))='\0';
                   1693:     in=s;
                   1694:   }
                   1695:   while ( *in != '\0'){
                   1696:     *blocc++ = *in++;
                   1697:   }
                   1698: 
                   1699:   *blocc='\0';
                   1700:   return t;
                   1701: }
1.137     brouard  1702: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1703: {
1.187     brouard  1704:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1705:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1706:      gives blocc="abcdef2ghi" and alocc="j".
                   1707:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1708:   */
                   1709:   char *s, *t;
                   1710:   t=in;s=in;
                   1711:   while (*in != '\0'){
                   1712:     while( *in == occ){
                   1713:       *blocc++ = *in++;
                   1714:       s=in;
                   1715:     }
                   1716:     *blocc++ = *in++;
                   1717:   }
                   1718:   if (s == t) /* occ not found */
                   1719:     *(blocc-(in-s))='\0';
                   1720:   else
                   1721:     *(blocc-(in-s)-1)='\0';
                   1722:   in=s;
                   1723:   while ( *in != '\0'){
                   1724:     *alocc++ = *in++;
                   1725:   }
                   1726: 
                   1727:   *alocc='\0';
                   1728:   return s;
                   1729: }
                   1730: 
1.126     brouard  1731: int nbocc(char *s, char occ)
                   1732: {
                   1733:   int i,j=0;
                   1734:   int lg=20;
                   1735:   i=0;
                   1736:   lg=strlen(s);
                   1737:   for(i=0; i<= lg; i++) {
1.234     brouard  1738:     if  (s[i] == occ ) j++;
1.126     brouard  1739:   }
                   1740:   return j;
                   1741: }
                   1742: 
1.137     brouard  1743: /* void cutv(char *u,char *v, char*t, char occ) */
                   1744: /* { */
                   1745: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1746: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1747: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1748: /*   int i,lg,j,p=0; */
                   1749: /*   i=0; */
                   1750: /*   lg=strlen(t); */
                   1751: /*   for(j=0; j<=lg-1; j++) { */
                   1752: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1753: /*   } */
1.126     brouard  1754: 
1.137     brouard  1755: /*   for(j=0; j<p; j++) { */
                   1756: /*     (u[j] = t[j]); */
                   1757: /*   } */
                   1758: /*      u[p]='\0'; */
1.126     brouard  1759: 
1.137     brouard  1760: /*    for(j=0; j<= lg; j++) { */
                   1761: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1762: /*   } */
                   1763: /* } */
1.126     brouard  1764: 
1.160     brouard  1765: #ifdef _WIN32
                   1766: char * strsep(char **pp, const char *delim)
                   1767: {
                   1768:   char *p, *q;
                   1769:          
                   1770:   if ((p = *pp) == NULL)
                   1771:     return 0;
                   1772:   if ((q = strpbrk (p, delim)) != NULL)
                   1773:   {
                   1774:     *pp = q + 1;
                   1775:     *q = '\0';
                   1776:   }
                   1777:   else
                   1778:     *pp = 0;
                   1779:   return p;
                   1780: }
                   1781: #endif
                   1782: 
1.126     brouard  1783: /********************** nrerror ********************/
                   1784: 
                   1785: void nrerror(char error_text[])
                   1786: {
                   1787:   fprintf(stderr,"ERREUR ...\n");
                   1788:   fprintf(stderr,"%s\n",error_text);
                   1789:   exit(EXIT_FAILURE);
                   1790: }
                   1791: /*********************** vector *******************/
                   1792: double *vector(int nl, int nh)
                   1793: {
                   1794:   double *v;
                   1795:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1796:   if (!v) nrerror("allocation failure in vector");
                   1797:   return v-nl+NR_END;
                   1798: }
                   1799: 
                   1800: /************************ free vector ******************/
                   1801: void free_vector(double*v, int nl, int nh)
                   1802: {
                   1803:   free((FREE_ARG)(v+nl-NR_END));
                   1804: }
                   1805: 
                   1806: /************************ivector *******************************/
                   1807: int *ivector(long nl,long nh)
                   1808: {
                   1809:   int *v;
                   1810:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1811:   if (!v) nrerror("allocation failure in ivector");
                   1812:   return v-nl+NR_END;
                   1813: }
                   1814: 
                   1815: /******************free ivector **************************/
                   1816: void free_ivector(int *v, long nl, long nh)
                   1817: {
                   1818:   free((FREE_ARG)(v+nl-NR_END));
                   1819: }
                   1820: 
                   1821: /************************lvector *******************************/
                   1822: long *lvector(long nl,long nh)
                   1823: {
                   1824:   long *v;
                   1825:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1826:   if (!v) nrerror("allocation failure in ivector");
                   1827:   return v-nl+NR_END;
                   1828: }
                   1829: 
                   1830: /******************free lvector **************************/
                   1831: void free_lvector(long *v, long nl, long nh)
                   1832: {
                   1833:   free((FREE_ARG)(v+nl-NR_END));
                   1834: }
                   1835: 
                   1836: /******************* imatrix *******************************/
                   1837: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1838:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1839: { 
                   1840:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1841:   int **m; 
                   1842:   
                   1843:   /* allocate pointers to rows */ 
                   1844:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1845:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1846:   m += NR_END; 
                   1847:   m -= nrl; 
                   1848:   
                   1849:   
                   1850:   /* allocate rows and set pointers to them */ 
                   1851:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1852:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1853:   m[nrl] += NR_END; 
                   1854:   m[nrl] -= ncl; 
                   1855:   
                   1856:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1857:   
                   1858:   /* return pointer to array of pointers to rows */ 
                   1859:   return m; 
                   1860: } 
                   1861: 
                   1862: /****************** free_imatrix *************************/
                   1863: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1864:       int **m;
                   1865:       long nch,ncl,nrh,nrl; 
                   1866:      /* free an int matrix allocated by imatrix() */ 
                   1867: { 
                   1868:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1869:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1870: } 
                   1871: 
                   1872: /******************* matrix *******************************/
                   1873: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1874: {
                   1875:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1876:   double **m;
                   1877: 
                   1878:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1879:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1880:   m += NR_END;
                   1881:   m -= nrl;
                   1882: 
                   1883:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1884:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1885:   m[nrl] += NR_END;
                   1886:   m[nrl] -= ncl;
                   1887: 
                   1888:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1889:   return m;
1.145     brouard  1890:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1891: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1892: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1893:    */
                   1894: }
                   1895: 
                   1896: /*************************free matrix ************************/
                   1897: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1898: {
                   1899:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1900:   free((FREE_ARG)(m+nrl-NR_END));
                   1901: }
                   1902: 
                   1903: /******************* ma3x *******************************/
                   1904: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1905: {
                   1906:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1907:   double ***m;
                   1908: 
                   1909:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1910:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1911:   m += NR_END;
                   1912:   m -= nrl;
                   1913: 
                   1914:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1915:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1916:   m[nrl] += NR_END;
                   1917:   m[nrl] -= ncl;
                   1918: 
                   1919:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1920: 
                   1921:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1922:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1923:   m[nrl][ncl] += NR_END;
                   1924:   m[nrl][ncl] -= nll;
                   1925:   for (j=ncl+1; j<=nch; j++) 
                   1926:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1927:   
                   1928:   for (i=nrl+1; i<=nrh; i++) {
                   1929:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1930:     for (j=ncl+1; j<=nch; j++) 
                   1931:       m[i][j]=m[i][j-1]+nlay;
                   1932:   }
                   1933:   return m; 
                   1934:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1935:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1936:   */
                   1937: }
                   1938: 
                   1939: /*************************free ma3x ************************/
                   1940: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1941: {
                   1942:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1943:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1944:   free((FREE_ARG)(m+nrl-NR_END));
                   1945: }
                   1946: 
                   1947: /*************** function subdirf ***********/
                   1948: char *subdirf(char fileres[])
                   1949: {
                   1950:   /* Caution optionfilefiname is hidden */
                   1951:   strcpy(tmpout,optionfilefiname);
                   1952:   strcat(tmpout,"/"); /* Add to the right */
                   1953:   strcat(tmpout,fileres);
                   1954:   return tmpout;
                   1955: }
                   1956: 
                   1957: /*************** function subdirf2 ***********/
                   1958: char *subdirf2(char fileres[], char *preop)
                   1959: {
1.314     brouard  1960:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
                   1961:  Errors in subdirf, 2, 3 while printing tmpout is
1.315     brouard  1962:  rewritten within the same printf. Workaround: many printfs */
1.126     brouard  1963:   /* Caution optionfilefiname is hidden */
                   1964:   strcpy(tmpout,optionfilefiname);
                   1965:   strcat(tmpout,"/");
                   1966:   strcat(tmpout,preop);
                   1967:   strcat(tmpout,fileres);
                   1968:   return tmpout;
                   1969: }
                   1970: 
                   1971: /*************** function subdirf3 ***********/
                   1972: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1973: {
                   1974:   
                   1975:   /* Caution optionfilefiname is hidden */
                   1976:   strcpy(tmpout,optionfilefiname);
                   1977:   strcat(tmpout,"/");
                   1978:   strcat(tmpout,preop);
                   1979:   strcat(tmpout,preop2);
                   1980:   strcat(tmpout,fileres);
                   1981:   return tmpout;
                   1982: }
1.213     brouard  1983:  
                   1984: /*************** function subdirfext ***********/
                   1985: char *subdirfext(char fileres[], char *preop, char *postop)
                   1986: {
                   1987:   
                   1988:   strcpy(tmpout,preop);
                   1989:   strcat(tmpout,fileres);
                   1990:   strcat(tmpout,postop);
                   1991:   return tmpout;
                   1992: }
1.126     brouard  1993: 
1.213     brouard  1994: /*************** function subdirfext3 ***********/
                   1995: char *subdirfext3(char fileres[], char *preop, char *postop)
                   1996: {
                   1997:   
                   1998:   /* Caution optionfilefiname is hidden */
                   1999:   strcpy(tmpout,optionfilefiname);
                   2000:   strcat(tmpout,"/");
                   2001:   strcat(tmpout,preop);
                   2002:   strcat(tmpout,fileres);
                   2003:   strcat(tmpout,postop);
                   2004:   return tmpout;
                   2005: }
                   2006:  
1.162     brouard  2007: char *asc_diff_time(long time_sec, char ascdiff[])
                   2008: {
                   2009:   long sec_left, days, hours, minutes;
                   2010:   days = (time_sec) / (60*60*24);
                   2011:   sec_left = (time_sec) % (60*60*24);
                   2012:   hours = (sec_left) / (60*60) ;
                   2013:   sec_left = (sec_left) %(60*60);
                   2014:   minutes = (sec_left) /60;
                   2015:   sec_left = (sec_left) % (60);
                   2016:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   2017:   return ascdiff;
                   2018: }
                   2019: 
1.126     brouard  2020: /***************** f1dim *************************/
                   2021: extern int ncom; 
                   2022: extern double *pcom,*xicom;
                   2023: extern double (*nrfunc)(double []); 
                   2024:  
                   2025: double f1dim(double x) 
                   2026: { 
                   2027:   int j; 
                   2028:   double f;
                   2029:   double *xt; 
                   2030:  
                   2031:   xt=vector(1,ncom); 
                   2032:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   2033:   f=(*nrfunc)(xt); 
                   2034:   free_vector(xt,1,ncom); 
                   2035:   return f; 
                   2036: } 
                   2037: 
                   2038: /*****************brent *************************/
                   2039: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  2040: {
                   2041:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   2042:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   2043:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   2044:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   2045:    * returned function value. 
                   2046:   */
1.126     brouard  2047:   int iter; 
                   2048:   double a,b,d,etemp;
1.159     brouard  2049:   double fu=0,fv,fw,fx;
1.164     brouard  2050:   double ftemp=0.;
1.126     brouard  2051:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   2052:   double e=0.0; 
                   2053:  
                   2054:   a=(ax < cx ? ax : cx); 
                   2055:   b=(ax > cx ? ax : cx); 
                   2056:   x=w=v=bx; 
                   2057:   fw=fv=fx=(*f)(x); 
                   2058:   for (iter=1;iter<=ITMAX;iter++) { 
                   2059:     xm=0.5*(a+b); 
                   2060:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   2061:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   2062:     printf(".");fflush(stdout);
                   2063:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  2064: #ifdef DEBUGBRENT
1.126     brouard  2065:     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);
                   2066:     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);
                   2067:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   2068: #endif
                   2069:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   2070:       *xmin=x; 
                   2071:       return fx; 
                   2072:     } 
                   2073:     ftemp=fu;
                   2074:     if (fabs(e) > tol1) { 
                   2075:       r=(x-w)*(fx-fv); 
                   2076:       q=(x-v)*(fx-fw); 
                   2077:       p=(x-v)*q-(x-w)*r; 
                   2078:       q=2.0*(q-r); 
                   2079:       if (q > 0.0) p = -p; 
                   2080:       q=fabs(q); 
                   2081:       etemp=e; 
                   2082:       e=d; 
                   2083:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  2084:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  2085:       else { 
1.224     brouard  2086:                                d=p/q; 
                   2087:                                u=x+d; 
                   2088:                                if (u-a < tol2 || b-u < tol2) 
                   2089:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  2090:       } 
                   2091:     } else { 
                   2092:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2093:     } 
                   2094:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   2095:     fu=(*f)(u); 
                   2096:     if (fu <= fx) { 
                   2097:       if (u >= x) a=x; else b=x; 
                   2098:       SHFT(v,w,x,u) 
1.183     brouard  2099:       SHFT(fv,fw,fx,fu) 
                   2100:     } else { 
                   2101:       if (u < x) a=u; else b=u; 
                   2102:       if (fu <= fw || w == x) { 
1.224     brouard  2103:                                v=w; 
                   2104:                                w=u; 
                   2105:                                fv=fw; 
                   2106:                                fw=fu; 
1.183     brouard  2107:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  2108:                                v=u; 
                   2109:                                fv=fu; 
1.183     brouard  2110:       } 
                   2111:     } 
1.126     brouard  2112:   } 
                   2113:   nrerror("Too many iterations in brent"); 
                   2114:   *xmin=x; 
                   2115:   return fx; 
                   2116: } 
                   2117: 
                   2118: /****************** mnbrak ***********************/
                   2119: 
                   2120: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2121:            double (*func)(double)) 
1.183     brouard  2122: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2123: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2124: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2125: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2126:    */
1.126     brouard  2127:   double ulim,u,r,q, dum;
                   2128:   double fu; 
1.187     brouard  2129: 
                   2130:   double scale=10.;
                   2131:   int iterscale=0;
                   2132: 
                   2133:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2134:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2135: 
                   2136: 
                   2137:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2138:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2139:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2140:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2141:   /* } */
                   2142: 
1.126     brouard  2143:   if (*fb > *fa) { 
                   2144:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2145:     SHFT(dum,*fb,*fa,dum) 
                   2146:   } 
1.126     brouard  2147:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2148:   *fc=(*func)(*cx); 
1.183     brouard  2149: #ifdef DEBUG
1.224     brouard  2150:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2151:   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  2152: #endif
1.224     brouard  2153:   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  2154:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2155:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2156:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2157:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2158:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2159:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2160:       fu=(*func)(u); 
1.163     brouard  2161: #ifdef DEBUG
                   2162:       /* f(x)=A(x-u)**2+f(u) */
                   2163:       double A, fparabu; 
                   2164:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2165:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2166:       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);
                   2167:       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  2168:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2169:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2170:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2171:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2172: #endif 
1.184     brouard  2173: #ifdef MNBRAKORIGINAL
1.183     brouard  2174: #else
1.191     brouard  2175: /*       if (fu > *fc) { */
                   2176: /* #ifdef DEBUG */
                   2177: /*       printf("mnbrak4  fu > fc \n"); */
                   2178: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2179: /* #endif */
                   2180: /*     /\* 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 *\\/  *\/ */
                   2181: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2182: /*     dum=u; /\* Shifting c and u *\/ */
                   2183: /*     u = *cx; */
                   2184: /*     *cx = dum; */
                   2185: /*     dum = fu; */
                   2186: /*     fu = *fc; */
                   2187: /*     *fc =dum; */
                   2188: /*       } else { /\* end *\/ */
                   2189: /* #ifdef DEBUG */
                   2190: /*       printf("mnbrak3  fu < fc \n"); */
                   2191: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2192: /* #endif */
                   2193: /*     dum=u; /\* Shifting c and u *\/ */
                   2194: /*     u = *cx; */
                   2195: /*     *cx = dum; */
                   2196: /*     dum = fu; */
                   2197: /*     fu = *fc; */
                   2198: /*     *fc =dum; */
                   2199: /*       } */
1.224     brouard  2200: #ifdef DEBUGMNBRAK
                   2201:                 double A, fparabu; 
                   2202:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2203:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2204:      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);
                   2205:      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  2206: #endif
1.191     brouard  2207:       dum=u; /* Shifting c and u */
                   2208:       u = *cx;
                   2209:       *cx = dum;
                   2210:       dum = fu;
                   2211:       fu = *fc;
                   2212:       *fc =dum;
1.183     brouard  2213: #endif
1.162     brouard  2214:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2215: #ifdef DEBUG
1.224     brouard  2216:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2217:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2218: #endif
1.126     brouard  2219:       fu=(*func)(u); 
                   2220:       if (fu < *fc) { 
1.183     brouard  2221: #ifdef DEBUG
1.224     brouard  2222:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2223:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2224: #endif
                   2225:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2226:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2227: #ifdef DEBUG
                   2228:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2229: #endif
                   2230:       } 
1.162     brouard  2231:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2232: #ifdef DEBUG
1.224     brouard  2233:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2234:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2235: #endif
1.126     brouard  2236:       u=ulim; 
                   2237:       fu=(*func)(u); 
1.183     brouard  2238:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2239: #ifdef DEBUG
1.224     brouard  2240:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2241:       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  2242: #endif
1.126     brouard  2243:       u=(*cx)+GOLD*(*cx-*bx); 
                   2244:       fu=(*func)(u); 
1.224     brouard  2245: #ifdef DEBUG
                   2246:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2247:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2248: #endif
1.183     brouard  2249:     } /* end tests */
1.126     brouard  2250:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2251:     SHFT(*fa,*fb,*fc,fu) 
                   2252: #ifdef DEBUG
1.224     brouard  2253:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2254:       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  2255: #endif
                   2256:   } /* 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  2257: } 
                   2258: 
                   2259: /*************** linmin ************************/
1.162     brouard  2260: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2261: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2262: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2263: the value of func at the returned location p . This is actually all accomplished by calling the
                   2264: routines mnbrak and brent .*/
1.126     brouard  2265: int ncom; 
                   2266: double *pcom,*xicom;
                   2267: double (*nrfunc)(double []); 
                   2268:  
1.224     brouard  2269: #ifdef LINMINORIGINAL
1.126     brouard  2270: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2271: #else
                   2272: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2273: #endif
1.126     brouard  2274: { 
                   2275:   double brent(double ax, double bx, double cx, 
                   2276:               double (*f)(double), double tol, double *xmin); 
                   2277:   double f1dim(double x); 
                   2278:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2279:              double *fc, double (*func)(double)); 
                   2280:   int j; 
                   2281:   double xx,xmin,bx,ax; 
                   2282:   double fx,fb,fa;
1.187     brouard  2283: 
1.203     brouard  2284: #ifdef LINMINORIGINAL
                   2285: #else
                   2286:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2287: #endif
                   2288:   
1.126     brouard  2289:   ncom=n; 
                   2290:   pcom=vector(1,n); 
                   2291:   xicom=vector(1,n); 
                   2292:   nrfunc=func; 
                   2293:   for (j=1;j<=n;j++) { 
                   2294:     pcom[j]=p[j]; 
1.202     brouard  2295:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2296:   } 
1.187     brouard  2297: 
1.203     brouard  2298: #ifdef LINMINORIGINAL
                   2299:   xx=1.;
                   2300: #else
                   2301:   axs=0.0;
                   2302:   xxs=1.;
                   2303:   do{
                   2304:     xx= xxs;
                   2305: #endif
1.187     brouard  2306:     ax=0.;
                   2307:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2308:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2309:     /* 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))   */
                   2310:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2311:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2312:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2313:     /* 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  2314: #ifdef LINMINORIGINAL
                   2315: #else
                   2316:     if (fx != fx){
1.224     brouard  2317:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2318:                        printf("|");
                   2319:                        fprintf(ficlog,"|");
1.203     brouard  2320: #ifdef DEBUGLINMIN
1.224     brouard  2321:                        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  2322: #endif
                   2323:     }
1.224     brouard  2324:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2325: #endif
                   2326:   
1.191     brouard  2327: #ifdef DEBUGLINMIN
                   2328:   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  2329:   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  2330: #endif
1.224     brouard  2331: #ifdef LINMINORIGINAL
                   2332: #else
1.317     brouard  2333:   if(fb == fx){ /* Flat function in the direction */
                   2334:     xmin=xx;
1.224     brouard  2335:     *flat=1;
1.317     brouard  2336:   }else{
1.224     brouard  2337:     *flat=0;
                   2338: #endif
                   2339:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2340:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2341:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2342:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2343:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2344:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2345: #ifdef DEBUG
1.224     brouard  2346:   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);
                   2347:   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);
                   2348: #endif
                   2349: #ifdef LINMINORIGINAL
                   2350: #else
                   2351:                        }
1.126     brouard  2352: #endif
1.191     brouard  2353: #ifdef DEBUGLINMIN
                   2354:   printf("linmin end ");
1.202     brouard  2355:   fprintf(ficlog,"linmin end ");
1.191     brouard  2356: #endif
1.126     brouard  2357:   for (j=1;j<=n;j++) { 
1.203     brouard  2358: #ifdef LINMINORIGINAL
                   2359:     xi[j] *= xmin; 
                   2360: #else
                   2361: #ifdef DEBUGLINMIN
                   2362:     if(xxs <1.0)
                   2363:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2364: #endif
                   2365:     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) */
                   2366: #ifdef DEBUGLINMIN
                   2367:     if(xxs <1.0)
                   2368:       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 );
                   2369: #endif
                   2370: #endif
1.187     brouard  2371:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2372:   } 
1.191     brouard  2373: #ifdef DEBUGLINMIN
1.203     brouard  2374:   printf("\n");
1.191     brouard  2375:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2376:   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  2377:   for (j=1;j<=n;j++) { 
1.202     brouard  2378:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2379:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2380:     if(j % ncovmodel == 0){
1.191     brouard  2381:       printf("\n");
1.202     brouard  2382:       fprintf(ficlog,"\n");
                   2383:     }
1.191     brouard  2384:   }
1.203     brouard  2385: #else
1.191     brouard  2386: #endif
1.126     brouard  2387:   free_vector(xicom,1,n); 
                   2388:   free_vector(pcom,1,n); 
                   2389: } 
                   2390: 
                   2391: 
                   2392: /*************** powell ************************/
1.162     brouard  2393: /*
1.317     brouard  2394: Minimization of a function func of n variables. Input consists in an initial starting point
                   2395: p[1..n] ; an initial matrix xi[1..n][1..n]  whose columns contain the initial set of di-
                   2396: rections (usually the n unit vectors); and ftol, the fractional tolerance in the function value
                   2397: such that failure to decrease by more than this amount in one iteration signals doneness. On
1.162     brouard  2398: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2399: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2400:  */
1.224     brouard  2401: #ifdef LINMINORIGINAL
                   2402: #else
                   2403:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2404:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2405: #endif
1.126     brouard  2406: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2407:            double (*func)(double [])) 
                   2408: { 
1.224     brouard  2409: #ifdef LINMINORIGINAL
                   2410:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2411:              double (*func)(double [])); 
1.224     brouard  2412: #else 
1.241     brouard  2413:  void linmin(double p[], double xi[], int n, double *fret,
                   2414:             double (*func)(double []),int *flat); 
1.224     brouard  2415: #endif
1.239     brouard  2416:  int i,ibig,j,jk,k; 
1.126     brouard  2417:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2418:   double directest;
1.126     brouard  2419:   double fp,fptt;
                   2420:   double *xits;
                   2421:   int niterf, itmp;
                   2422: 
                   2423:   pt=vector(1,n); 
                   2424:   ptt=vector(1,n); 
                   2425:   xit=vector(1,n); 
                   2426:   xits=vector(1,n); 
                   2427:   *fret=(*func)(p); 
                   2428:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  2429:   rcurr_time = time(NULL);  
1.126     brouard  2430:   for (*iter=1;;++(*iter)) { 
                   2431:     ibig=0; 
                   2432:     del=0.0; 
1.157     brouard  2433:     rlast_time=rcurr_time;
                   2434:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2435:     rcurr_time = time(NULL);  
                   2436:     curr_time = *localtime(&rcurr_time);
1.324     brouard  2437:     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);
                   2438:     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  2439: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.324     brouard  2440:     fp=(*fret); /* From former iteration or initial value */
1.192     brouard  2441:     for (i=1;i<=n;i++) {
1.126     brouard  2442:       fprintf(ficrespow," %.12lf", p[i]);
                   2443:     }
1.239     brouard  2444:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2445:     printf("\n#model=  1      +     age ");
                   2446:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2447:     if(nagesqr==1){
1.241     brouard  2448:        printf("  + age*age  ");
                   2449:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2450:     }
                   2451:     for(j=1;j <=ncovmodel-2;j++){
                   2452:       if(Typevar[j]==0) {
                   2453:        printf("  +      V%d  ",Tvar[j]);
                   2454:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2455:       }else if(Typevar[j]==1) {
                   2456:        printf("  +    V%d*age ",Tvar[j]);
                   2457:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2458:       }else if(Typevar[j]==2) {
                   2459:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2460:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2461:       }
                   2462:     }
1.126     brouard  2463:     printf("\n");
1.239     brouard  2464: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2465: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2466:     fprintf(ficlog,"\n");
1.239     brouard  2467:     for(i=1,jk=1; i <=nlstate; i++){
                   2468:       for(k=1; k <=(nlstate+ndeath); k++){
                   2469:        if (k != i) {
                   2470:          printf("%d%d ",i,k);
                   2471:          fprintf(ficlog,"%d%d ",i,k);
                   2472:          for(j=1; j <=ncovmodel; j++){
                   2473:            printf("%12.7f ",p[jk]);
                   2474:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2475:            jk++; 
                   2476:          }
                   2477:          printf("\n");
                   2478:          fprintf(ficlog,"\n");
                   2479:        }
                   2480:       }
                   2481:     }
1.241     brouard  2482:     if(*iter <=3 && *iter >1){
1.157     brouard  2483:       tml = *localtime(&rcurr_time);
                   2484:       strcpy(strcurr,asctime(&tml));
                   2485:       rforecast_time=rcurr_time; 
1.126     brouard  2486:       itmp = strlen(strcurr);
                   2487:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2488:        strcurr[itmp-1]='\0';
1.162     brouard  2489:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2490:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  2491:       for(niterf=10;niterf<=30;niterf+=10){
1.241     brouard  2492:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2493:        forecast_time = *localtime(&rforecast_time);
                   2494:        strcpy(strfor,asctime(&forecast_time));
                   2495:        itmp = strlen(strfor);
                   2496:        if(strfor[itmp-1]=='\n')
                   2497:          strfor[itmp-1]='\0';
                   2498:        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);
                   2499:        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  2500:       }
                   2501:     }
1.187     brouard  2502:     for (i=1;i<=n;i++) { /* For each direction i */
                   2503:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2504:       fptt=(*fret); 
                   2505: #ifdef DEBUG
1.203     brouard  2506:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2507:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2508: #endif
1.203     brouard  2509:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2510:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2511: #ifdef LINMINORIGINAL
1.188     brouard  2512:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2513: #else
                   2514:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2515:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2516: #endif
                   2517:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2518:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2519:                                /* because that direction will be replaced unless the gain del is small */
                   2520:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2521:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2522:                                /* with the new direction. */
                   2523:                                del=fabs(fptt-(*fret)); 
                   2524:                                ibig=i; 
1.126     brouard  2525:       } 
                   2526: #ifdef DEBUG
                   2527:       printf("%d %.12e",i,(*fret));
                   2528:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2529:       for (j=1;j<=n;j++) {
1.224     brouard  2530:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2531:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2532:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2533:       }
                   2534:       for(j=1;j<=n;j++) {
1.225     brouard  2535:                                printf(" p(%d)=%.12e",j,p[j]);
                   2536:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2537:       }
                   2538:       printf("\n");
                   2539:       fprintf(ficlog,"\n");
                   2540: #endif
1.187     brouard  2541:     } /* end loop on each direction i */
                   2542:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2543:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2544:     /* New value of last point Pn is not computed, P(n-1) */
1.319     brouard  2545:     for(j=1;j<=n;j++) {
                   2546:       if(flatdir[j] >0){
                   2547:         printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2548:         fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
1.302     brouard  2549:       }
1.319     brouard  2550:       /* printf("\n"); */
                   2551:       /* fprintf(ficlog,"\n"); */
                   2552:     }
1.243     brouard  2553:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2554:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2555:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2556:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2557:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2558:       /* decreased of more than 3.84  */
                   2559:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2560:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2561:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2562:                        
1.188     brouard  2563:       /* Starting the program with initial values given by a former maximization will simply change */
                   2564:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2565:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2566:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2567: #ifdef DEBUG
                   2568:       int k[2],l;
                   2569:       k[0]=1;
                   2570:       k[1]=-1;
                   2571:       printf("Max: %.12e",(*func)(p));
                   2572:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2573:       for (j=1;j<=n;j++) {
                   2574:        printf(" %.12e",p[j]);
                   2575:        fprintf(ficlog," %.12e",p[j]);
                   2576:       }
                   2577:       printf("\n");
                   2578:       fprintf(ficlog,"\n");
                   2579:       for(l=0;l<=1;l++) {
                   2580:        for (j=1;j<=n;j++) {
                   2581:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2582:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2583:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2584:        }
                   2585:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2586:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2587:       }
                   2588: #endif
                   2589: 
                   2590:       free_vector(xit,1,n); 
                   2591:       free_vector(xits,1,n); 
                   2592:       free_vector(ptt,1,n); 
                   2593:       free_vector(pt,1,n); 
                   2594:       return; 
1.192     brouard  2595:     } /* enough precision */ 
1.240     brouard  2596:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2597:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2598:       ptt[j]=2.0*p[j]-pt[j]; 
                   2599:       xit[j]=p[j]-pt[j]; 
                   2600:       pt[j]=p[j]; 
                   2601:     } 
1.181     brouard  2602:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2603: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2604:                if (*iter <=4) {
1.225     brouard  2605: #else
                   2606: #endif
1.224     brouard  2607: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2608: #else
1.161     brouard  2609:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2610: #endif
1.162     brouard  2611:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2612:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2613:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2614:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2615:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2616:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2617:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2618:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2619:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2620:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2621:       /* mu² and del² are equal when f3=f1 */
                   2622:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2623:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2624:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2625:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2626: #ifdef NRCORIGINAL
                   2627:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2628: #else
                   2629:       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  2630:       t= t- del*SQR(fp-fptt);
1.183     brouard  2631: #endif
1.202     brouard  2632:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2633: #ifdef DEBUG
1.181     brouard  2634:       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);
                   2635:       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  2636:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2637:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2638:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2639:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2640:       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);
                   2641:       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);
                   2642: #endif
1.183     brouard  2643: #ifdef POWELLORIGINAL
                   2644:       if (t < 0.0) { /* Then we use it for new direction */
                   2645: #else
1.182     brouard  2646:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2647:                                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  2648:         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  2649:         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  2650:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2651:       } 
1.181     brouard  2652:       if (directest < 0.0) { /* Then we use it for new direction */
                   2653: #endif
1.191     brouard  2654: #ifdef DEBUGLINMIN
1.234     brouard  2655:        printf("Before linmin in direction P%d-P0\n",n);
                   2656:        for (j=1;j<=n;j++) {
                   2657:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2658:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2659:          if(j % ncovmodel == 0){
                   2660:            printf("\n");
                   2661:            fprintf(ficlog,"\n");
                   2662:          }
                   2663:        }
1.224     brouard  2664: #endif
                   2665: #ifdef LINMINORIGINAL
1.234     brouard  2666:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2667: #else
1.234     brouard  2668:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2669:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2670: #endif
1.234     brouard  2671:        
1.191     brouard  2672: #ifdef DEBUGLINMIN
1.234     brouard  2673:        for (j=1;j<=n;j++) { 
                   2674:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2675:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2676:          if(j % ncovmodel == 0){
                   2677:            printf("\n");
                   2678:            fprintf(ficlog,"\n");
                   2679:          }
                   2680:        }
1.224     brouard  2681: #endif
1.234     brouard  2682:        for (j=1;j<=n;j++) { 
                   2683:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2684:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2685:        }
1.224     brouard  2686: #ifdef LINMINORIGINAL
                   2687: #else
1.234     brouard  2688:        for (j=1, flatd=0;j<=n;j++) {
                   2689:          if(flatdir[j]>0)
                   2690:            flatd++;
                   2691:        }
                   2692:        if(flatd >0){
1.255     brouard  2693:          printf("%d flat directions: ",flatd);
                   2694:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  2695:          for (j=1;j<=n;j++) { 
                   2696:            if(flatdir[j]>0){
                   2697:              printf("%d ",j);
                   2698:              fprintf(ficlog,"%d ",j);
                   2699:            }
                   2700:          }
                   2701:          printf("\n");
                   2702:          fprintf(ficlog,"\n");
1.319     brouard  2703: #ifdef FLATSUP
                   2704:           free_vector(xit,1,n); 
                   2705:           free_vector(xits,1,n); 
                   2706:           free_vector(ptt,1,n); 
                   2707:           free_vector(pt,1,n); 
                   2708:           return;
                   2709: #endif
1.234     brouard  2710:        }
1.191     brouard  2711: #endif
1.234     brouard  2712:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2713:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2714:        
1.126     brouard  2715: #ifdef DEBUG
1.234     brouard  2716:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2717:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2718:        for(j=1;j<=n;j++){
                   2719:          printf(" %lf",xit[j]);
                   2720:          fprintf(ficlog," %lf",xit[j]);
                   2721:        }
                   2722:        printf("\n");
                   2723:        fprintf(ficlog,"\n");
1.126     brouard  2724: #endif
1.192     brouard  2725:       } /* end of t or directest negative */
1.224     brouard  2726: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2727: #else
1.234     brouard  2728:       } /* end if (fptt < fp)  */
1.192     brouard  2729: #endif
1.225     brouard  2730: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2731:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2732: #else
1.224     brouard  2733: #endif
1.234     brouard  2734:                } /* loop iteration */ 
1.126     brouard  2735: } 
1.234     brouard  2736:   
1.126     brouard  2737: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2738:   
1.235     brouard  2739:   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  2740:   {
1.279     brouard  2741:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij 
                   2742:      *   (and selected quantitative values in nres)
                   2743:      *  by left multiplying the unit
                   2744:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   2745:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   2746:      * Wx is row vector: population in state 1, population in state 2, population dead
                   2747:      * or prevalence in state 1, prevalence in state 2, 0
                   2748:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   2749:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   2750:      * Output is prlim.
                   2751:      * Initial matrix pimij 
                   2752:      */
1.206     brouard  2753:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2754:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2755:   /*  0,                   0                  , 1} */
                   2756:   /*
                   2757:    * and after some iteration: */
                   2758:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2759:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2760:   /*  0,                   0                  , 1} */
                   2761:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2762:   /* {0.51571254859325999, 0.4842874514067399, */
                   2763:   /*  0.51326036147820708, 0.48673963852179264} */
                   2764:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2765:     
1.126     brouard  2766:   int i, ii,j,k;
1.209     brouard  2767:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2768:   /* double **matprod2(); */ /* test */
1.218     brouard  2769:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2770:   double **newm;
1.209     brouard  2771:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2772:   int ncvloop=0;
1.288     brouard  2773:   int first=0;
1.169     brouard  2774:   
1.209     brouard  2775:   min=vector(1,nlstate);
                   2776:   max=vector(1,nlstate);
                   2777:   meandiff=vector(1,nlstate);
                   2778: 
1.218     brouard  2779:        /* Starting with matrix unity */
1.126     brouard  2780:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2781:     for (j=1;j<=nlstate+ndeath;j++){
                   2782:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2783:     }
1.169     brouard  2784:   
                   2785:   cov[1]=1.;
                   2786:   
                   2787:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2788:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2789:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2790:     ncvloop++;
1.126     brouard  2791:     newm=savm;
                   2792:     /* Covariates have to be included here again */
1.138     brouard  2793:     cov[2]=agefin;
1.319     brouard  2794:      if(nagesqr==1){
                   2795:       cov[3]= agefin*agefin;
                   2796:      }
1.234     brouard  2797:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2798:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2799:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
1.319     brouard  2800:       /* cov[++k1]=nbcode[TvarsD[k]][codtabm(ij,k)]; */
1.235     brouard  2801:       /* printf("prevalim Dummy combi=%d k=%d TvarsD[%d]=V%d TvarsDind[%d]=%d nbcode=%d cov=%lf codtabm(%d,Tvar[%d])=%d \n",ij,k, k, TvarsD[k],k,TvarsDind[k],nbcode[TvarsD[k]][codtabm(ij,k)],cov[2+nagesqr+TvarsDind[k]], ij, k, codtabm(ij,k)); */
1.234     brouard  2802:     }
                   2803:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2804:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
1.319     brouard  2805:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];
                   2806:       /* cov[++k1]=Tqresult[nres][k];  */
1.235     brouard  2807:       /* printf("prevalim Quantitative k=%d  TvarsQind[%d]=%d, TvarsQ[%d]=V%d,Tqresult[%d][%d]=%f\n",k,k,TvarsQind[k],k,TvarsQ[k],nres,k,Tqresult[nres][k]); */
1.138     brouard  2808:     }
1.237     brouard  2809:     for (k=1; k<=cptcovage;k++){  /* For product with age */
1.319     brouard  2810:       if(Dummy[Tage[k]]==2){ /* dummy with age */
1.234     brouard  2811:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
1.319     brouard  2812:        /* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   2813:       } else if(Dummy[Tage[k]]==3){ /* quantitative with age */
                   2814:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];
                   2815:        /* cov[++k1]=Tqresult[nres][k];  */
1.234     brouard  2816:       }
1.235     brouard  2817:       /* printf("prevalim Age combi=%d k=%d  Tage[%d]=V%d Tqresult[%d][%d]=%f\n",ij,k,k,Tage[k],nres,k,Tqresult[nres][k]); */
1.234     brouard  2818:     }
1.237     brouard  2819:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
1.235     brouard  2820:       /* printf("prevalim Prod ij=%d k=%d  Tprod[%d]=%d Tvard[%d][1]=V%d, Tvard[%d][2]=V%d\n",ij,k,k,Tprod[k], k,Tvard[k][1], k,Tvard[k][2]); */
1.237     brouard  2821:       if(Dummy[Tvard[k][1]==0]){
                   2822:        if(Dummy[Tvard[k][2]==0]){
                   2823:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
1.319     brouard  2824:          /* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.237     brouard  2825:        }else{
                   2826:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
1.319     brouard  2827:          /* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; */
1.237     brouard  2828:        }
                   2829:       }else{
                   2830:        if(Dummy[Tvard[k][2]==0]){
                   2831:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
1.319     brouard  2832:          /* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; */
1.237     brouard  2833:        }else{
                   2834:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
1.319     brouard  2835:          /* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
1.237     brouard  2836:        }
                   2837:       }
1.234     brouard  2838:     }
1.138     brouard  2839:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2840:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2841:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2842:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2843:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.319     brouard  2844:     /* age and covariate values of ij are in 'cov' */
1.142     brouard  2845:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2846:     
1.126     brouard  2847:     savm=oldm;
                   2848:     oldm=newm;
1.209     brouard  2849: 
                   2850:     for(j=1; j<=nlstate; j++){
                   2851:       max[j]=0.;
                   2852:       min[j]=1.;
                   2853:     }
                   2854:     for(i=1;i<=nlstate;i++){
                   2855:       sumnew=0;
                   2856:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2857:       for(j=1; j<=nlstate; j++){ 
                   2858:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2859:        max[j]=FMAX(max[j],prlim[i][j]);
                   2860:        min[j]=FMIN(min[j],prlim[i][j]);
                   2861:       }
                   2862:     }
                   2863: 
1.126     brouard  2864:     maxmax=0.;
1.209     brouard  2865:     for(j=1; j<=nlstate; j++){
                   2866:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2867:       maxmax=FMAX(maxmax,meandiff[j]);
                   2868:       /* 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  2869:     } /* j loop */
1.203     brouard  2870:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2871:     /* 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  2872:     if(maxmax < ftolpl){
1.209     brouard  2873:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2874:       free_vector(min,1,nlstate);
                   2875:       free_vector(max,1,nlstate);
                   2876:       free_vector(meandiff,1,nlstate);
1.126     brouard  2877:       return prlim;
                   2878:     }
1.288     brouard  2879:   } /* agefin loop */
1.208     brouard  2880:     /* After some age loop it doesn't converge */
1.288     brouard  2881:   if(!first){
                   2882:     first=1;
                   2883:     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  2884:     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);
                   2885:   }else if (first >=1 && first <10){
                   2886:     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);
                   2887:     first++;
                   2888:   }else if (first ==10){
                   2889:     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);
                   2890:     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");
                   2891:     fprintf(ficlog,"Warning: the stable prevalence no convergence; too many cases, giving up noticing, even in log file\n");
                   2892:     first++;
1.288     brouard  2893:   }
                   2894: 
1.209     brouard  2895:   /* 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); */
                   2896:   free_vector(min,1,nlstate);
                   2897:   free_vector(max,1,nlstate);
                   2898:   free_vector(meandiff,1,nlstate);
1.208     brouard  2899:   
1.169     brouard  2900:   return prlim; /* should not reach here */
1.126     brouard  2901: }
                   2902: 
1.217     brouard  2903: 
                   2904:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   2905: 
1.218     brouard  2906:  /* 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) */
                   2907:  /* 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  2908:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  2909: {
1.264     brouard  2910:   /* 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  2911:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   2912:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2913:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2914:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2915:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2916:   /* Initial matrix pimij */
                   2917:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2918:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2919:   /*  0,                   0                  , 1} */
                   2920:   /*
                   2921:    * and after some iteration: */
                   2922:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2923:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2924:   /*  0,                   0                  , 1} */
                   2925:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2926:   /* {0.51571254859325999, 0.4842874514067399, */
                   2927:   /*  0.51326036147820708, 0.48673963852179264} */
                   2928:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2929: 
                   2930:   int i, ii,j,k;
1.247     brouard  2931:   int first=0;
1.217     brouard  2932:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   2933:   /* double **matprod2(); */ /* test */
                   2934:   double **out, cov[NCOVMAX+1], **bmij();
                   2935:   double **newm;
1.218     brouard  2936:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   2937:   double        **oldm, **savm;  /* for use */
                   2938: 
1.217     brouard  2939:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   2940:   int ncvloop=0;
                   2941:   
                   2942:   min=vector(1,nlstate);
                   2943:   max=vector(1,nlstate);
                   2944:   meandiff=vector(1,nlstate);
                   2945: 
1.266     brouard  2946:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   2947:   oldm=oldms; savm=savms;
                   2948:   
                   2949:   /* Starting with matrix unity */
                   2950:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2951:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  2952:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2953:     }
                   2954:   
                   2955:   cov[1]=1.;
                   2956:   
                   2957:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2958:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  2959:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  2960:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   2961:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  2962:     ncvloop++;
1.218     brouard  2963:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   2964:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  2965:     /* Covariates have to be included here again */
                   2966:     cov[2]=agefin;
1.319     brouard  2967:     if(nagesqr==1){
1.217     brouard  2968:       cov[3]= agefin*agefin;;
1.319     brouard  2969:     }
1.242     brouard  2970:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2971:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2972:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
1.264     brouard  2973:       /* printf("bprevalim Dummy agefin=%.0f combi=%d k=%d TvarsD[%d]=V%d TvarsDind[%d]=%d nbcode=%d cov[%d]=%lf codtabm(%d,Tvar[%d])=%d \n",agefin,ij,k, k, TvarsD[k],k,TvarsDind[k],nbcode[TvarsD[k]][codtabm(ij,k)],2+nagesqr+TvarsDind[k],cov[2+nagesqr+TvarsDind[k]], ij, k, codtabm(ij,k)); */
1.242     brouard  2974:     }
                   2975:     /* for (k=1; k<=cptcovn;k++) { */
                   2976:     /*   /\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\/ */
                   2977:     /*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   2978:     /*   /\* 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])]); *\/ */
                   2979:     /* } */
                   2980:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2981:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   2982:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   2983:       /* 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]); */
                   2984:     }
                   2985:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; */
                   2986:     /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
                   2987:     /*   /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\/ */
                   2988:     /*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; */
                   2989:     for (k=1; k<=cptcovage;k++){  /* For product with age */
1.319     brouard  2990:       /* if(Dummy[Tvar[Tage[k]]]== 2){ /\* dummy with age *\/ ERROR ???*/
                   2991:       if(Dummy[Tage[k]]== 2){ /* dummy with age */
1.242     brouard  2992:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
1.319     brouard  2993:       } else if(Dummy[Tage[k]]== 3){ /* quantitative with age */
                   2994:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];
1.242     brouard  2995:       }
                   2996:       /* 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]); */
                   2997:     }
                   2998:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
                   2999:       /* 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]); */
                   3000:       if(Dummy[Tvard[k][1]==0]){
                   3001:        if(Dummy[Tvard[k][2]==0]){
                   3002:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   3003:        }else{
                   3004:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
                   3005:        }
                   3006:       }else{
                   3007:        if(Dummy[Tvard[k][2]==0]){
                   3008:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
                   3009:        }else{
                   3010:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   3011:        }
                   3012:       }
1.217     brouard  3013:     }
                   3014:     
                   3015:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3016:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3017:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   3018:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3019:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  3020:                /* ij should be linked to the correct index of cov */
                   3021:                /* age and covariate values ij are in 'cov', but we need to pass
                   3022:                 * ij for the observed prevalence at age and status and covariate
                   3023:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   3024:                 */
                   3025:     /* 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 *\/ */
                   3026:     /* 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 *\/ */
                   3027:     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  3028:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  3029:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   3030:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   3031:     /*         printf("%d newm= ",i); */
                   3032:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3033:     /*           printf("%f ",newm[i][j]); */
                   3034:     /*         } */
                   3035:     /*         printf("oldm * "); */
                   3036:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3037:     /*           printf("%f ",oldm[i][j]); */
                   3038:     /*         } */
1.268     brouard  3039:     /*         printf(" bmmij "); */
1.266     brouard  3040:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3041:     /*           printf("%f ",pmmij[i][j]); */
                   3042:     /*         } */
                   3043:     /*         printf("\n"); */
                   3044:     /*   } */
                   3045:     /* } */
1.217     brouard  3046:     savm=oldm;
                   3047:     oldm=newm;
1.266     brouard  3048: 
1.217     brouard  3049:     for(j=1; j<=nlstate; j++){
                   3050:       max[j]=0.;
                   3051:       min[j]=1.;
                   3052:     }
                   3053:     for(j=1; j<=nlstate; j++){ 
                   3054:       for(i=1;i<=nlstate;i++){
1.234     brouard  3055:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   3056:        bprlim[i][j]= newm[i][j];
                   3057:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   3058:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  3059:       }
                   3060:     }
1.218     brouard  3061:                
1.217     brouard  3062:     maxmax=0.;
                   3063:     for(i=1; i<=nlstate; i++){
1.318     brouard  3064:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column, could be nan! */
1.217     brouard  3065:       maxmax=FMAX(maxmax,meandiff[i]);
                   3066:       /* 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  3067:     } /* i loop */
1.217     brouard  3068:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  3069:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3070:     if(maxmax < ftolpl){
1.220     brouard  3071:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3072:       free_vector(min,1,nlstate);
                   3073:       free_vector(max,1,nlstate);
                   3074:       free_vector(meandiff,1,nlstate);
                   3075:       return bprlim;
                   3076:     }
1.288     brouard  3077:   } /* agefin loop */
1.217     brouard  3078:     /* After some age loop it doesn't converge */
1.288     brouard  3079:   if(!first){
1.247     brouard  3080:     first=1;
                   3081:     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\
                   3082: 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);
                   3083:   }
                   3084:   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  3085: 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);
                   3086:   /* 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); */
                   3087:   free_vector(min,1,nlstate);
                   3088:   free_vector(max,1,nlstate);
                   3089:   free_vector(meandiff,1,nlstate);
                   3090:   
                   3091:   return bprlim; /* should not reach here */
                   3092: }
                   3093: 
1.126     brouard  3094: /*************** transition probabilities ***************/ 
                   3095: 
                   3096: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   3097: {
1.138     brouard  3098:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  3099:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  3100:      model to the ncovmodel covariates (including constant and age).
                   3101:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3102:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3103:      ncth covariate in the global vector x is given by the formula:
                   3104:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3105:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3106:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3107:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  3108:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  3109:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  3110:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  3111:   */
                   3112:   double s1, lnpijopii;
1.126     brouard  3113:   /*double t34;*/
1.164     brouard  3114:   int i,j, nc, ii, jj;
1.126     brouard  3115: 
1.223     brouard  3116:   for(i=1; i<= nlstate; i++){
                   3117:     for(j=1; j<i;j++){
                   3118:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3119:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3120:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3121:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3122:       }
                   3123:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3124:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3125:     }
                   3126:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3127:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3128:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3129:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3130:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3131:       }
                   3132:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3133:     }
                   3134:   }
1.218     brouard  3135:   
1.223     brouard  3136:   for(i=1; i<= nlstate; i++){
                   3137:     s1=0;
                   3138:     for(j=1; j<i; j++){
                   3139:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3140:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3141:     }
                   3142:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3143:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3144:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3145:     }
                   3146:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3147:     ps[i][i]=1./(s1+1.);
                   3148:     /* Computing other pijs */
                   3149:     for(j=1; j<i; j++)
1.325     brouard  3150:       ps[i][j]= exp(ps[i][j])*ps[i][i];/* Bug valgrind */
1.223     brouard  3151:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3152:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3153:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3154:   } /* end i */
1.218     brouard  3155:   
1.223     brouard  3156:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3157:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3158:       ps[ii][jj]=0;
                   3159:       ps[ii][ii]=1;
                   3160:     }
                   3161:   }
1.294     brouard  3162: 
                   3163: 
1.223     brouard  3164:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3165:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3166:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3167:   /*   } */
                   3168:   /*   printf("\n "); */
                   3169:   /* } */
                   3170:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3171:   /*
                   3172:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  3173:                goto end;*/
1.266     brouard  3174:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  3175: }
                   3176: 
1.218     brouard  3177: /*************** backward transition probabilities ***************/ 
                   3178: 
                   3179:  /* 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 ) */
                   3180: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   3181:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   3182: {
1.302     brouard  3183:   /* 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  3184:    * 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  3185:    */
1.218     brouard  3186:   int i, ii, j,k;
1.222     brouard  3187:   
                   3188:   double **out, **pmij();
                   3189:   double sumnew=0.;
1.218     brouard  3190:   double agefin;
1.292     brouard  3191:   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  3192:   double **dnewm, **dsavm, **doldm;
                   3193:   double **bbmij;
                   3194:   
1.218     brouard  3195:   doldm=ddoldms; /* global pointers */
1.222     brouard  3196:   dnewm=ddnewms;
                   3197:   dsavm=ddsavms;
1.318     brouard  3198: 
                   3199:   /* Debug */
                   3200:   /* printf("Bmij ij=%d, cov[2}=%f\n", ij, cov[2]); */
1.222     brouard  3201:   agefin=cov[2];
1.268     brouard  3202:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  3203:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  3204:      the observed prevalence (with this covariate ij) at beginning of transition */
                   3205:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  3206: 
                   3207:   /* P_x */
1.325     brouard  3208:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm *//* Bug valgrind */
1.268     brouard  3209:   /* outputs pmmij which is a stochastic matrix in row */
                   3210: 
                   3211:   /* Diag(w_x) */
1.292     brouard  3212:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  3213:   sumnew=0.;
1.269     brouard  3214:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  3215:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  3216:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  3217:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   3218:   }
                   3219:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   3220:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3221:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  3222:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  3223:     }
                   3224:   }else{
                   3225:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3226:       for (j=1;j<=nlstate+ndeath;j++)
                   3227:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   3228:     }
                   3229:     /* if(sumnew <0.9){ */
                   3230:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   3231:     /* } */
                   3232:   }
                   3233:   k3=0.0;  /* We put the last diagonal to 0 */
                   3234:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   3235:       doldm[ii][ii]= k3;
                   3236:   }
                   3237:   /* End doldm, At the end doldm is diag[(w_i)] */
                   3238:   
1.292     brouard  3239:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   3240:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  3241: 
1.292     brouard  3242:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  3243:   /* 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  3244:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  3245:     sumnew=0.;
1.222     brouard  3246:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  3247:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  3248:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  3249:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  3250:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  3251:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  3252:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3253:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  3254:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3255:        /* }else */
1.268     brouard  3256:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   3257:     } /*End ii */
                   3258:   } /* 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 */
                   3259: 
1.292     brouard  3260:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  3261:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  3262:   /* end bmij */
1.266     brouard  3263:   return ps; /*pointer is unchanged */
1.218     brouard  3264: }
1.217     brouard  3265: /*************** transition probabilities ***************/ 
                   3266: 
1.218     brouard  3267: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  3268: {
                   3269:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3270:      computes the probability to be observed in state j being in state i by appying the
                   3271:      model to the ncovmodel covariates (including constant and age).
                   3272:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3273:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3274:      ncth covariate in the global vector x is given by the formula:
                   3275:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3276:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3277:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3278:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3279:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   3280:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3281:   */
                   3282:   double s1, lnpijopii;
                   3283:   /*double t34;*/
                   3284:   int i,j, nc, ii, jj;
                   3285: 
1.234     brouard  3286:   for(i=1; i<= nlstate; i++){
                   3287:     for(j=1; j<i;j++){
                   3288:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3289:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3290:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3291:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3292:       }
                   3293:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3294:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3295:     }
                   3296:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3297:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3298:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3299:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3300:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3301:       }
                   3302:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3303:     }
                   3304:   }
                   3305:   
                   3306:   for(i=1; i<= nlstate; i++){
                   3307:     s1=0;
                   3308:     for(j=1; j<i; j++){
                   3309:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3310:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3311:     }
                   3312:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3313:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3314:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3315:     }
                   3316:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3317:     ps[i][i]=1./(s1+1.);
                   3318:     /* Computing other pijs */
                   3319:     for(j=1; j<i; j++)
                   3320:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3321:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3322:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3323:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3324:   } /* end i */
                   3325:   
                   3326:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3327:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3328:       ps[ii][jj]=0;
                   3329:       ps[ii][ii]=1;
                   3330:     }
                   3331:   }
1.296     brouard  3332:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  3333:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3334:     s1=0.;
                   3335:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   3336:       s1+=ps[ii][jj];
                   3337:     }
                   3338:     for(ii=1; ii<= nlstate; ii++){
                   3339:       ps[ii][jj]=ps[ii][jj]/s1;
                   3340:     }
                   3341:   }
                   3342:   /* Transposition */
                   3343:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3344:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   3345:       s1=ps[ii][jj];
                   3346:       ps[ii][jj]=ps[jj][ii];
                   3347:       ps[jj][ii]=s1;
                   3348:     }
                   3349:   }
                   3350:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3351:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3352:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3353:   /*   } */
                   3354:   /*   printf("\n "); */
                   3355:   /* } */
                   3356:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3357:   /*
                   3358:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3359:     goto end;*/
                   3360:   return ps;
1.217     brouard  3361: }
                   3362: 
                   3363: 
1.126     brouard  3364: /**************** Product of 2 matrices ******************/
                   3365: 
1.145     brouard  3366: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  3367: {
                   3368:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3369:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3370:   /* in, b, out are matrice of pointers which should have been initialized 
                   3371:      before: only the contents of out is modified. The function returns
                   3372:      a pointer to pointers identical to out */
1.145     brouard  3373:   int i, j, k;
1.126     brouard  3374:   for(i=nrl; i<= nrh; i++)
1.145     brouard  3375:     for(k=ncolol; k<=ncoloh; k++){
                   3376:       out[i][k]=0.;
                   3377:       for(j=ncl; j<=nch; j++)
                   3378:        out[i][k] +=in[i][j]*b[j][k];
                   3379:     }
1.126     brouard  3380:   return out;
                   3381: }
                   3382: 
                   3383: 
                   3384: /************* Higher Matrix Product ***************/
                   3385: 
1.235     brouard  3386: 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  3387: {
1.218     brouard  3388:   /* Computes the transition matrix starting at age 'age' and combination of covariate values corresponding to ij over 
1.126     brouard  3389:      'nhstepm*hstepm*stepm' months (i.e. until
                   3390:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3391:      nhstepm*hstepm matrices. 
                   3392:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3393:      (typically every 2 years instead of every month which is too big 
                   3394:      for the memory).
                   3395:      Model is determined by parameters x and covariates have to be 
                   3396:      included manually here. 
                   3397: 
                   3398:      */
                   3399: 
                   3400:   int i, j, d, h, k;
1.131     brouard  3401:   double **out, cov[NCOVMAX+1];
1.126     brouard  3402:   double **newm;
1.187     brouard  3403:   double agexact;
1.214     brouard  3404:   double agebegin, ageend;
1.126     brouard  3405: 
                   3406:   /* Hstepm could be zero and should return the unit matrix */
                   3407:   for (i=1;i<=nlstate+ndeath;i++)
                   3408:     for (j=1;j<=nlstate+ndeath;j++){
                   3409:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3410:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3411:     }
                   3412:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3413:   for(h=1; h <=nhstepm; h++){
                   3414:     for(d=1; d <=hstepm; d++){
                   3415:       newm=savm;
                   3416:       /* Covariates have to be included here again */
                   3417:       cov[1]=1.;
1.214     brouard  3418:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3419:       cov[2]=agexact;
1.319     brouard  3420:       if(nagesqr==1){
1.227     brouard  3421:        cov[3]= agexact*agexact;
1.319     brouard  3422:       }
1.235     brouard  3423:       for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
1.319     brouard  3424: /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   3425:        /* codtabm(ij,k)  (1 & (ij-1) >> (k-1))+1 */
                   3426: /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   3427: /*    k        1  2   3   4     5    6    7     8    9 */
                   3428: /*Tvar[k]=     5  4   3   6     5    2    7     1    1 */
                   3429: /*    nsd         1   2                              3 */ /* Counting single dummies covar fixed or tv */
                   3430: /*TvarsD[nsd]     4   3                              1 */ /* ID of single dummy cova fixed or timevary*/
                   3431: /*TvarsDind[k]    2   3                              9 */ /* position K of single dummy cova */
1.235     brouard  3432:        cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
                   3433:        /* printf("hpxij 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)); */
                   3434:       }
                   3435:       for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   3436:        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
1.319     brouard  3437:        cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];
1.235     brouard  3438:        /* 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]); */
                   3439:       }
1.319     brouard  3440:       for (k=1; k<=cptcovage;k++){ /* For product with age V1+V1*age +V4 +age*V3 */
                   3441:        /* 1+2 Tage[1]=2 TVar[2]=1 Dummy[2]=2, Tage[2]=4 TVar[4]=3 Dummy[4]=3 quant*/
                   3442:        /* */
                   3443:        if(Dummy[Tage[k]]== 2){ /* dummy with age */
                   3444:        /* if(Dummy[Tvar[Tage[k]]]== 2){ /\* dummy with age *\/ */
1.235     brouard  3445:          cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
1.319     brouard  3446:        } else if(Dummy[Tage[k]]== 3){ /* quantitative with age */
                   3447:          cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];
1.235     brouard  3448:        }
                   3449:        /* 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]); */
                   3450:       }
1.319     brouard  3451:       for (k=1; k<=cptcovprod;k++){ /*  For product without age */
1.235     brouard  3452:        /* printf("hPxij Prod ij=%d k=%d  Tprod[%d]=%d Tvard[%d][1]=V%d, Tvard[%d][2]=V%d\n",ij,k,k,Tprod[k], k,Tvard[k][1], k,Tvard[k][2]); */
1.319     brouard  3453:        /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; */
                   3454:        if(Dummy[Tvard[k][1]==0]){
                   3455:          if(Dummy[Tvard[k][2]==0]){
                   3456:            cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   3457:          }else{
                   3458:            cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
                   3459:          }
                   3460:        }else{
                   3461:          if(Dummy[Tvard[k][2]==0]){
                   3462:            cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
                   3463:          }else{
                   3464:            cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   3465:          }
                   3466:        }
1.235     brouard  3467:       }
                   3468:       /* for (k=1; k<=cptcovn;k++)  */
                   3469:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3470:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3471:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3472:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3473:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3474:       
                   3475:       
1.126     brouard  3476:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3477:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.319     brouard  3478:       /* right multiplication of oldm by the current matrix */
1.126     brouard  3479:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3480:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3481:       /* if((int)age == 70){ */
                   3482:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3483:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3484:       /*         printf("%d pmmij ",i); */
                   3485:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3486:       /*           printf("%f ",pmmij[i][j]); */
                   3487:       /*         } */
                   3488:       /*         printf(" oldm "); */
                   3489:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3490:       /*           printf("%f ",oldm[i][j]); */
                   3491:       /*         } */
                   3492:       /*         printf("\n"); */
                   3493:       /*       } */
                   3494:       /* } */
1.126     brouard  3495:       savm=oldm;
                   3496:       oldm=newm;
                   3497:     }
                   3498:     for(i=1; i<=nlstate+ndeath; i++)
                   3499:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  3500:        po[i][j][h]=newm[i][j];
                   3501:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3502:       }
1.128     brouard  3503:     /*printf("h=%d ",h);*/
1.126     brouard  3504:   } /* end h */
1.267     brouard  3505:   /*     printf("\n H=%d \n",h); */
1.126     brouard  3506:   return po;
                   3507: }
                   3508: 
1.217     brouard  3509: /************* Higher Back Matrix Product ***************/
1.218     brouard  3510: /* 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  3511: 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  3512: {
1.266     brouard  3513:   /* For a combination of dummy covariate ij, computes the transition matrix starting at age 'age' over
1.217     brouard  3514:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3515:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3516:      nhstepm*hstepm matrices.
                   3517:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3518:      (typically every 2 years instead of every month which is too big
1.217     brouard  3519:      for the memory).
1.218     brouard  3520:      Model is determined by parameters x and covariates have to be
1.266     brouard  3521:      included manually here. Then we use a call to bmij(x and cov)
                   3522:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  3523:   */
1.217     brouard  3524: 
                   3525:   int i, j, d, h, k;
1.266     brouard  3526:   double **out, cov[NCOVMAX+1], **bmij();
                   3527:   double **newm, ***newmm;
1.217     brouard  3528:   double agexact;
                   3529:   double agebegin, ageend;
1.222     brouard  3530:   double **oldm, **savm;
1.217     brouard  3531: 
1.266     brouard  3532:   newmm=po; /* To be saved */
                   3533:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  3534:   /* Hstepm could be zero and should return the unit matrix */
                   3535:   for (i=1;i<=nlstate+ndeath;i++)
                   3536:     for (j=1;j<=nlstate+ndeath;j++){
                   3537:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3538:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3539:     }
                   3540:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3541:   for(h=1; h <=nhstepm; h++){
                   3542:     for(d=1; d <=hstepm; d++){
                   3543:       newm=savm;
                   3544:       /* Covariates have to be included here again */
                   3545:       cov[1]=1.;
1.271     brouard  3546:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  3547:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
1.318     brouard  3548:         /* Debug */
                   3549:       /* printf("hBxij age=%lf, agexact=%lf\n", age, agexact); */
1.217     brouard  3550:       cov[2]=agexact;
                   3551:       if(nagesqr==1)
1.222     brouard  3552:        cov[3]= agexact*agexact;
1.325     brouard  3553:       for (k=1; k<=nsd;k++){ /* For single dummy covariates only *//* cptcovn error */
1.266     brouard  3554:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3555:       /* /\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\/ */
1.325     brouard  3556:        cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];/* Bug valgrind */
1.266     brouard  3557:         /* 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)); */
                   3558:       }
1.267     brouard  3559:       for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   3560:        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   3561:        cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   3562:        /* 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]); */
                   3563:       }
1.319     brouard  3564:       for (k=1; k<=cptcovage;k++){ /* Should start at cptcovn+1 *//* For product with age */
                   3565:        /* if(Dummy[Tvar[Tage[k]]]== 2){ /\* dummy with age error!!!*\/ */
                   3566:        if(Dummy[Tage[k]]== 2){ /* dummy with age */
1.267     brouard  3567:          cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
1.319     brouard  3568:        } else if(Dummy[Tage[k]]== 3){ /* quantitative with age */
1.267     brouard  3569:          cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   3570:        }
                   3571:        /* 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]); */
                   3572:       }
                   3573:       for (k=1; k<=cptcovprod;k++){ /* Useless because included in cptcovn */
1.222     brouard  3574:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.325     brouard  3575:        if(Dummy[Tvard[k][1]==0]){
                   3576:          if(Dummy[Tvard[k][2]==0]){
                   3577:            cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   3578:          }else{
                   3579:            cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
                   3580:          }
                   3581:        }else{
                   3582:          if(Dummy[Tvard[k][2]==0]){
                   3583:            cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
                   3584:          }else{
                   3585:            cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   3586:          }
                   3587:        }
1.267     brouard  3588:       }                        
1.217     brouard  3589:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3590:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.267     brouard  3591: 
1.218     brouard  3592:       /* Careful transposed matrix */
1.266     brouard  3593:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  3594:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3595:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3596:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.325     brouard  3597:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);/* Bug valgrind */
1.217     brouard  3598:       /* if((int)age == 70){ */
                   3599:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3600:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3601:       /*         printf("%d pmmij ",i); */
                   3602:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3603:       /*           printf("%f ",pmmij[i][j]); */
                   3604:       /*         } */
                   3605:       /*         printf(" oldm "); */
                   3606:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3607:       /*           printf("%f ",oldm[i][j]); */
                   3608:       /*         } */
                   3609:       /*         printf("\n"); */
                   3610:       /*       } */
                   3611:       /* } */
                   3612:       savm=oldm;
                   3613:       oldm=newm;
                   3614:     }
                   3615:     for(i=1; i<=nlstate+ndeath; i++)
                   3616:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3617:        po[i][j][h]=newm[i][j];
1.268     brouard  3618:        /* if(h==nhstepm) */
                   3619:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  3620:       }
1.268     brouard  3621:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  3622:   } /* end h */
1.268     brouard  3623:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  3624:   return po;
                   3625: }
                   3626: 
                   3627: 
1.162     brouard  3628: #ifdef NLOPT
                   3629:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3630:   double fret;
                   3631:   double *xt;
                   3632:   int j;
                   3633:   myfunc_data *d2 = (myfunc_data *) pd;
                   3634: /* xt = (p1-1); */
                   3635:   xt=vector(1,n); 
                   3636:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3637: 
                   3638:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3639:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3640:   printf("Function = %.12lf ",fret);
                   3641:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3642:   printf("\n");
                   3643:  free_vector(xt,1,n);
                   3644:   return fret;
                   3645: }
                   3646: #endif
1.126     brouard  3647: 
                   3648: /*************** log-likelihood *************/
                   3649: double func( double *x)
                   3650: {
1.226     brouard  3651:   int i, ii, j, k, mi, d, kk;
                   3652:   int ioffset=0;
                   3653:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3654:   double **out;
                   3655:   double lli; /* Individual log likelihood */
                   3656:   int s1, s2;
1.228     brouard  3657:   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  3658:   double bbh, survp;
                   3659:   long ipmx;
                   3660:   double agexact;
                   3661:   /*extern weight */
                   3662:   /* We are differentiating ll according to initial status */
                   3663:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3664:   /*for(i=1;i<imx;i++) 
                   3665:     printf(" %d\n",s[4][i]);
                   3666:   */
1.162     brouard  3667: 
1.226     brouard  3668:   ++countcallfunc;
1.162     brouard  3669: 
1.226     brouard  3670:   cov[1]=1.;
1.126     brouard  3671: 
1.226     brouard  3672:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3673:   ioffset=0;
1.226     brouard  3674:   if(mle==1){
                   3675:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3676:       /* Computes the values of the ncovmodel covariates of the model
                   3677:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3678:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   3679:         to be observed in j being in i according to the model.
                   3680:       */
1.243     brouard  3681:       ioffset=2+nagesqr ;
1.233     brouard  3682:    /* Fixed */
1.319     brouard  3683:       for (k=1; k<=ncovf;k++){ /* For each fixed covariate dummu or quant or prod */
                   3684:        /* # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi */
                   3685:         /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   3686:        /*  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  3687:         /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.319     brouard  3688:        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)*/
                   3689:        /* V1*V2 (7)  TvarFind[2]=7, TvarFind[3]=9 */
1.234     brouard  3690:       }
1.226     brouard  3691:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.319     brouard  3692:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
1.226     brouard  3693:         has been calculated etc */
                   3694:       /* For an individual i, wav[i] gives the number of effective waves */
                   3695:       /* We compute the contribution to Likelihood of each effective transition
                   3696:         mw[mi][i] is real wave of the mi th effectve wave */
                   3697:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   3698:         s2=s[mw[mi+1][i]][i];
                   3699:         And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
                   3700:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   3701:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   3702:       */
                   3703:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  3704:        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*/
                   3705:          /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; but where is the crossproduct? */
1.242     brouard  3706:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
1.234     brouard  3707:        }
                   3708:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3709:          for (j=1;j<=nlstate+ndeath;j++){
                   3710:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3711:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3712:          }
                   3713:        for(d=0; d<dh[mi][i]; d++){
                   3714:          newm=savm;
                   3715:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3716:          cov[2]=agexact;
                   3717:          if(nagesqr==1)
                   3718:            cov[3]= agexact*agexact;  /* Should be changed here */
                   3719:          for (kk=1; kk<=cptcovage;kk++) {
1.318     brouard  3720:            if(!FixedV[Tvar[Tage[kk]]])
                   3721:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   3722:            else
                   3723:              cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
1.234     brouard  3724:          }
                   3725:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3726:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3727:          savm=oldm;
                   3728:          oldm=newm;
                   3729:        } /* end mult */
                   3730:        
                   3731:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   3732:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   3733:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   3734:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   3735:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   3736:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   3737:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   3738:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  3739:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   3740:                                 * -stepm/2 to stepm/2 .
                   3741:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   3742:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   3743:                                 */
1.234     brouard  3744:        s1=s[mw[mi][i]][i];
                   3745:        s2=s[mw[mi+1][i]][i];
                   3746:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3747:        /* bias bh is positive if real duration
                   3748:         * is higher than the multiple of stepm and negative otherwise.
                   3749:         */
                   3750:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   3751:        if( s2 > nlstate){ 
                   3752:          /* i.e. if s2 is a death state and if the date of death is known 
                   3753:             then the contribution to the likelihood is the probability to 
                   3754:             die between last step unit time and current  step unit time, 
                   3755:             which is also equal to probability to die before dh 
                   3756:             minus probability to die before dh-stepm . 
                   3757:             In version up to 0.92 likelihood was computed
                   3758:             as if date of death was unknown. Death was treated as any other
                   3759:             health state: the date of the interview describes the actual state
                   3760:             and not the date of a change in health state. The former idea was
                   3761:             to consider that at each interview the state was recorded
                   3762:             (healthy, disable or death) and IMaCh was corrected; but when we
                   3763:             introduced the exact date of death then we should have modified
                   3764:             the contribution of an exact death to the likelihood. This new
                   3765:             contribution is smaller and very dependent of the step unit
                   3766:             stepm. It is no more the probability to die between last interview
                   3767:             and month of death but the probability to survive from last
                   3768:             interview up to one month before death multiplied by the
                   3769:             probability to die within a month. Thanks to Chris
                   3770:             Jackson for correcting this bug.  Former versions increased
                   3771:             mortality artificially. The bad side is that we add another loop
                   3772:             which slows down the processing. The difference can be up to 10%
                   3773:             lower mortality.
                   3774:          */
                   3775:          /* If, at the beginning of the maximization mostly, the
                   3776:             cumulative probability or probability to be dead is
                   3777:             constant (ie = 1) over time d, the difference is equal to
                   3778:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   3779:             s1 at precedent wave, to be dead a month before current
                   3780:             wave is equal to probability, being at state s1 at
                   3781:             precedent wave, to be dead at mont of the current
                   3782:             wave. Then the observed probability (that this person died)
                   3783:             is null according to current estimated parameter. In fact,
                   3784:             it should be very low but not zero otherwise the log go to
                   3785:             infinity.
                   3786:          */
1.183     brouard  3787: /* #ifdef INFINITYORIGINAL */
                   3788: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3789: /* #else */
                   3790: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   3791: /*         lli=log(mytinydouble); */
                   3792: /*       else */
                   3793: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3794: /* #endif */
1.226     brouard  3795:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3796:          
1.226     brouard  3797:        } else if  ( s2==-1 ) { /* alive */
                   3798:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3799:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3800:          /*survp += out[s1][j]; */
                   3801:          lli= log(survp);
                   3802:        }
                   3803:        else if  (s2==-4) { 
                   3804:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   3805:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3806:          lli= log(survp); 
                   3807:        } 
                   3808:        else if  (s2==-5) { 
                   3809:          for (j=1,survp=0. ; j<=2; j++)  
                   3810:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3811:          lli= log(survp); 
                   3812:        } 
                   3813:        else{
                   3814:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3815:          /*  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 */
                   3816:        } 
                   3817:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   3818:        /*if(lli ==000.0)*/
                   3819:        /*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); */
                   3820:        ipmx +=1;
                   3821:        sw += weight[i];
                   3822:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3823:        /* if (lli < log(mytinydouble)){ */
                   3824:        /*   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); */
                   3825:        /*   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]); */
                   3826:        /* } */
                   3827:       } /* end of wave */
                   3828:     } /* end of individual */
                   3829:   }  else if(mle==2){
                   3830:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.319     brouard  3831:       ioffset=2+nagesqr ;
                   3832:       for (k=1; k<=ncovf;k++)
                   3833:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];
1.226     brouard  3834:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  3835:        for(k=1; k <= ncovv ; k++){
                   3836:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
                   3837:        }
1.226     brouard  3838:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3839:          for (j=1;j<=nlstate+ndeath;j++){
                   3840:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3841:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3842:          }
                   3843:        for(d=0; d<=dh[mi][i]; d++){
                   3844:          newm=savm;
                   3845:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3846:          cov[2]=agexact;
                   3847:          if(nagesqr==1)
                   3848:            cov[3]= agexact*agexact;
                   3849:          for (kk=1; kk<=cptcovage;kk++) {
                   3850:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3851:          }
                   3852:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3853:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3854:          savm=oldm;
                   3855:          oldm=newm;
                   3856:        } /* end mult */
                   3857:       
                   3858:        s1=s[mw[mi][i]][i];
                   3859:        s2=s[mw[mi+1][i]][i];
                   3860:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3861:        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 */
                   3862:        ipmx +=1;
                   3863:        sw += weight[i];
                   3864:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3865:       } /* end of wave */
                   3866:     } /* end of individual */
                   3867:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   3868:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3869:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3870:       for(mi=1; mi<= wav[i]-1; mi++){
                   3871:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3872:          for (j=1;j<=nlstate+ndeath;j++){
                   3873:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3874:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3875:          }
                   3876:        for(d=0; d<dh[mi][i]; d++){
                   3877:          newm=savm;
                   3878:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3879:          cov[2]=agexact;
                   3880:          if(nagesqr==1)
                   3881:            cov[3]= agexact*agexact;
                   3882:          for (kk=1; kk<=cptcovage;kk++) {
                   3883:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3884:          }
                   3885:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3886:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3887:          savm=oldm;
                   3888:          oldm=newm;
                   3889:        } /* end mult */
                   3890:       
                   3891:        s1=s[mw[mi][i]][i];
                   3892:        s2=s[mw[mi+1][i]][i];
                   3893:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3894:        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 */
                   3895:        ipmx +=1;
                   3896:        sw += weight[i];
                   3897:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3898:       } /* end of wave */
                   3899:     } /* end of individual */
                   3900:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   3901:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3902:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3903:       for(mi=1; mi<= wav[i]-1; mi++){
                   3904:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3905:          for (j=1;j<=nlstate+ndeath;j++){
                   3906:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3907:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3908:          }
                   3909:        for(d=0; d<dh[mi][i]; d++){
                   3910:          newm=savm;
                   3911:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3912:          cov[2]=agexact;
                   3913:          if(nagesqr==1)
                   3914:            cov[3]= agexact*agexact;
                   3915:          for (kk=1; kk<=cptcovage;kk++) {
                   3916:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3917:          }
1.126     brouard  3918:        
1.226     brouard  3919:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3920:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3921:          savm=oldm;
                   3922:          oldm=newm;
                   3923:        } /* end mult */
                   3924:       
                   3925:        s1=s[mw[mi][i]][i];
                   3926:        s2=s[mw[mi+1][i]][i];
                   3927:        if( s2 > nlstate){ 
                   3928:          lli=log(out[s1][s2] - savm[s1][s2]);
                   3929:        } else if  ( s2==-1 ) { /* alive */
                   3930:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3931:            survp += out[s1][j];
                   3932:          lli= log(survp);
                   3933:        }else{
                   3934:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3935:        }
                   3936:        ipmx +=1;
                   3937:        sw += weight[i];
                   3938:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.126     brouard  3939: /*     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  3940:       } /* end of wave */
                   3941:     } /* end of individual */
                   3942:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   3943:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3944:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3945:       for(mi=1; mi<= wav[i]-1; mi++){
                   3946:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3947:          for (j=1;j<=nlstate+ndeath;j++){
                   3948:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3949:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3950:          }
                   3951:        for(d=0; d<dh[mi][i]; d++){
                   3952:          newm=savm;
                   3953:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3954:          cov[2]=agexact;
                   3955:          if(nagesqr==1)
                   3956:            cov[3]= agexact*agexact;
                   3957:          for (kk=1; kk<=cptcovage;kk++) {
                   3958:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3959:          }
1.126     brouard  3960:        
1.226     brouard  3961:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3962:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3963:          savm=oldm;
                   3964:          oldm=newm;
                   3965:        } /* end mult */
                   3966:       
                   3967:        s1=s[mw[mi][i]][i];
                   3968:        s2=s[mw[mi+1][i]][i];
                   3969:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3970:        ipmx +=1;
                   3971:        sw += weight[i];
                   3972:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3973:        /*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]);*/
                   3974:       } /* end of wave */
                   3975:     } /* end of individual */
                   3976:   } /* End of if */
                   3977:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3978:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3979:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3980:   return -l;
1.126     brouard  3981: }
                   3982: 
                   3983: /*************** log-likelihood *************/
                   3984: double funcone( double *x)
                   3985: {
1.228     brouard  3986:   /* Same as func but slower because of a lot of printf and if */
1.126     brouard  3987:   int i, ii, j, k, mi, d, kk;
1.228     brouard  3988:   int ioffset=0;
1.131     brouard  3989:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  3990:   double **out;
                   3991:   double lli; /* Individual log likelihood */
                   3992:   double llt;
                   3993:   int s1, s2;
1.228     brouard  3994:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   3995: 
1.126     brouard  3996:   double bbh, survp;
1.187     brouard  3997:   double agexact;
1.214     brouard  3998:   double agebegin, ageend;
1.126     brouard  3999:   /*extern weight */
                   4000:   /* We are differentiating ll according to initial status */
                   4001:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   4002:   /*for(i=1;i<imx;i++) 
                   4003:     printf(" %d\n",s[4][i]);
                   4004:   */
                   4005:   cov[1]=1.;
                   4006: 
                   4007:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  4008:   ioffset=0;
                   4009:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.243     brouard  4010:     /* ioffset=2+nagesqr+cptcovage; */
                   4011:     ioffset=2+nagesqr;
1.232     brouard  4012:     /* Fixed */
1.224     brouard  4013:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  4014:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
1.311     brouard  4015:     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  4016:       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)*/
                   4017: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   4018: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   4019: /*    cov[2+6]=covar[2][i]; V2  */
                   4020: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   4021: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   4022: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   4023: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   4024: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   4025: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  4026:     }
1.232     brouard  4027:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   4028:     /*   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?)*\/ */
                   4029:     /* } */
1.231     brouard  4030:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   4031:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   4032:     /* } */
1.225     brouard  4033:     
1.233     brouard  4034: 
                   4035:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.232     brouard  4036:     /* Wave varying (but not age varying) */
                   4037:       for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242     brouard  4038:        /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
                   4039:        cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
                   4040:       }
1.232     brouard  4041:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
1.242     brouard  4042:       /* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4043:       /* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
                   4044:       /* k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
                   4045:       /* cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
                   4046:       /* 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  4047:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  4048:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4049:       /*       /\* 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]); *\/ */
                   4050:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  4051:       /* } */
1.126     brouard  4052:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  4053:        for (j=1;j<=nlstate+ndeath;j++){
                   4054:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4055:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4056:        }
1.214     brouard  4057:       
                   4058:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4059:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   4060:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  4061:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  4062:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4063:          and mw[mi+1][i]. dh depends on stepm.*/
                   4064:        newm=savm;
1.247     brouard  4065:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  4066:        cov[2]=agexact;
                   4067:        if(nagesqr==1)
                   4068:          cov[3]= agexact*agexact;
                   4069:        for (kk=1; kk<=cptcovage;kk++) {
                   4070:          if(!FixedV[Tvar[Tage[kk]]])
                   4071:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4072:          else
                   4073:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
                   4074:        }
                   4075:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   4076:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4077:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4078:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4079:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   4080:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   4081:        savm=oldm;
                   4082:        oldm=newm;
1.126     brouard  4083:       } /* end mult */
                   4084:       
                   4085:       s1=s[mw[mi][i]][i];
                   4086:       s2=s[mw[mi+1][i]][i];
1.217     brouard  4087:       /* if(s2==-1){ */
1.268     brouard  4088:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  4089:       /*       /\* exit(1); *\/ */
                   4090:       /* } */
1.126     brouard  4091:       bbh=(double)bh[mi][i]/(double)stepm; 
                   4092:       /* bias is positive if real duration
                   4093:        * is higher than the multiple of stepm and negative otherwise.
                   4094:        */
                   4095:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  4096:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4097:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  4098:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   4099:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4100:        lli= log(survp);
1.126     brouard  4101:       }else if (mle==1){
1.242     brouard  4102:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  4103:       } else if(mle==2){
1.242     brouard  4104:        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  4105:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  4106:        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  4107:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  4108:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  4109:       } else{  /* mle=0 back to 1 */
1.242     brouard  4110:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4111:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  4112:       } /* End of if */
                   4113:       ipmx +=1;
                   4114:       sw += weight[i];
                   4115:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  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]); */
1.126     brouard  4117:       if(globpr){
1.246     brouard  4118:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  4119:  %11.6f %11.6f %11.6f ", \
1.242     brouard  4120:                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  4121:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.242     brouard  4122:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   4123:          llt +=ll[k]*gipmx/gsw;
                   4124:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   4125:        }
                   4126:        fprintf(ficresilk," %10.6f\n", -llt);
1.126     brouard  4127:       }
1.232     brouard  4128:        } /* end of wave */
                   4129: } /* end of individual */
                   4130: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   4131: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   4132: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4133: if(globpr==0){ /* First time we count the contributions and weights */
                   4134:        gipmx=ipmx;
                   4135:        gsw=sw;
                   4136: }
                   4137: return -l;
1.126     brouard  4138: }
                   4139: 
                   4140: 
                   4141: /*************** function likelione ***********/
1.292     brouard  4142: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  4143: {
                   4144:   /* This routine should help understanding what is done with 
                   4145:      the selection of individuals/waves and
                   4146:      to check the exact contribution to the likelihood.
                   4147:      Plotting could be done.
                   4148:    */
                   4149:   int k;
                   4150: 
                   4151:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  4152:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  4153:     strcat(fileresilk,fileresu);
1.126     brouard  4154:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   4155:       printf("Problem with resultfile: %s\n", fileresilk);
                   4156:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   4157:     }
1.214     brouard  4158:     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");
                   4159:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  4160:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   4161:     for(k=1; k<=nlstate; k++) 
                   4162:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   4163:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   4164:   }
                   4165: 
1.292     brouard  4166:   *fretone=(*func)(p);
1.126     brouard  4167:   if(*globpri !=0){
                   4168:     fclose(ficresilk);
1.205     brouard  4169:     if (mle ==0)
                   4170:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   4171:     else if(mle >=1)
                   4172:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   4173:     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  4174:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  4175:       
                   4176:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  4177:       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  4178: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   4179:     }
1.207     brouard  4180:     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  4181: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4182:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  4183: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4184:     fflush(fichtm);
1.205     brouard  4185:   }
1.126     brouard  4186:   return;
                   4187: }
                   4188: 
                   4189: 
                   4190: /*********** Maximum Likelihood Estimation ***************/
                   4191: 
                   4192: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   4193: {
1.319     brouard  4194:   int i,j,k, jk, jkk=0, iter=0;
1.126     brouard  4195:   double **xi;
                   4196:   double fret;
                   4197:   double fretone; /* Only one call to likelihood */
                   4198:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  4199: 
                   4200: #ifdef NLOPT
                   4201:   int creturn;
                   4202:   nlopt_opt opt;
                   4203:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   4204:   double *lb;
                   4205:   double minf; /* the minimum objective value, upon return */
                   4206:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   4207:   myfunc_data dinst, *d = &dinst;
                   4208: #endif
                   4209: 
                   4210: 
1.126     brouard  4211:   xi=matrix(1,npar,1,npar);
                   4212:   for (i=1;i<=npar;i++)
                   4213:     for (j=1;j<=npar;j++)
                   4214:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   4215:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  4216:   strcpy(filerespow,"POW_"); 
1.126     brouard  4217:   strcat(filerespow,fileres);
                   4218:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   4219:     printf("Problem with resultfile: %s\n", filerespow);
                   4220:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   4221:   }
                   4222:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   4223:   for (i=1;i<=nlstate;i++)
                   4224:     for(j=1;j<=nlstate+ndeath;j++)
                   4225:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   4226:   fprintf(ficrespow,"\n");
1.162     brouard  4227: #ifdef POWELL
1.319     brouard  4228: #ifdef LINMINORIGINAL
                   4229: #else /* LINMINORIGINAL */
                   4230:   
                   4231:   flatdir=ivector(1,npar); 
                   4232:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   4233: #endif /*LINMINORIGINAL */
                   4234: 
                   4235: #ifdef FLATSUP
                   4236:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4237:   /* reorganizing p by suppressing flat directions */
                   4238:   for(i=1, jk=1; i <=nlstate; i++){
                   4239:     for(k=1; k <=(nlstate+ndeath); k++){
                   4240:       if (k != i) {
                   4241:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4242:         if(flatdir[jk]==1){
                   4243:           printf(" To be skipped %d%d flatdir[%d]=%d ",i,k,jk, flatdir[jk]);
                   4244:         }
                   4245:         for(j=1; j <=ncovmodel; j++){
                   4246:           printf("%12.7f ",p[jk]);
                   4247:           jk++; 
                   4248:         }
                   4249:         printf("\n");
                   4250:       }
                   4251:     }
                   4252:   }
                   4253: /* skipping */
                   4254:   /* for(i=1, jk=1, jkk=1;(flatdir[jk]==0)&& (i <=nlstate); i++){ */
                   4255:   for(i=1, jk=1, jkk=1;i <=nlstate; i++){
                   4256:     for(k=1; k <=(nlstate+ndeath); k++){
                   4257:       if (k != i) {
                   4258:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4259:         if(flatdir[jk]==1){
                   4260:           printf(" To be skipped %d%d flatdir[%d]=%d jk=%d p[%d] ",i,k,jk, flatdir[jk],jk, jk);
                   4261:           for(j=1; j <=ncovmodel;  jk++,j++){
                   4262:             printf(" p[%d]=%12.7f",jk, p[jk]);
                   4263:             /*q[jjk]=p[jk];*/
                   4264:           }
                   4265:         }else{
                   4266:           printf(" To be kept %d%d flatdir[%d]=%d jk=%d q[%d]=p[%d] ",i,k,jk, flatdir[jk],jk, jkk, jk);
                   4267:           for(j=1; j <=ncovmodel;  jk++,jkk++,j++){
                   4268:             printf(" p[%d]=%12.7f=q[%d]",jk, p[jk],jkk);
                   4269:             /*q[jjk]=p[jk];*/
                   4270:           }
                   4271:         }
                   4272:         printf("\n");
                   4273:       }
                   4274:       fflush(stdout);
                   4275:     }
                   4276:   }
                   4277:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4278: #else  /* FLATSUP */
1.126     brouard  4279:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.319     brouard  4280: #endif  /* FLATSUP */
                   4281: 
                   4282: #ifdef LINMINORIGINAL
                   4283: #else
                   4284:       free_ivector(flatdir,1,npar); 
                   4285: #endif  /* LINMINORIGINAL*/
                   4286: #endif /* POWELL */
1.126     brouard  4287: 
1.162     brouard  4288: #ifdef NLOPT
                   4289: #ifdef NEWUOA
                   4290:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   4291: #else
                   4292:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   4293: #endif
                   4294:   lb=vector(0,npar-1);
                   4295:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   4296:   nlopt_set_lower_bounds(opt, lb);
                   4297:   nlopt_set_initial_step1(opt, 0.1);
                   4298:   
                   4299:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   4300:   d->function = func;
                   4301:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   4302:   nlopt_set_min_objective(opt, myfunc, d);
                   4303:   nlopt_set_xtol_rel(opt, ftol);
                   4304:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   4305:     printf("nlopt failed! %d\n",creturn); 
                   4306:   }
                   4307:   else {
                   4308:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   4309:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   4310:     iter=1; /* not equal */
                   4311:   }
                   4312:   nlopt_destroy(opt);
                   4313: #endif
1.319     brouard  4314: #ifdef FLATSUP
                   4315:   /* npared = npar -flatd/ncovmodel; */
                   4316:   /* xired= matrix(1,npared,1,npared); */
                   4317:   /* paramred= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */
                   4318:   /* powell(pred,xired,npared,ftol,&iter,&fret,flatdir,func); */
                   4319:   /* free_matrix(xire,1,npared,1,npared); */
                   4320: #else  /* FLATSUP */
                   4321: #endif /* FLATSUP */
1.126     brouard  4322:   free_matrix(xi,1,npar,1,npar);
                   4323:   fclose(ficrespow);
1.203     brouard  4324:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   4325:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  4326:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  4327: 
                   4328: }
                   4329: 
                   4330: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  4331: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  4332: {
                   4333:   double  **a,**y,*x,pd;
1.203     brouard  4334:   /* double **hess; */
1.164     brouard  4335:   int i, j;
1.126     brouard  4336:   int *indx;
                   4337: 
                   4338:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  4339:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  4340:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   4341:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   4342:   double gompertz(double p[]);
1.203     brouard  4343:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  4344: 
                   4345:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   4346:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   4347:   for (i=1;i<=npar;i++){
1.203     brouard  4348:     printf("%d-",i);fflush(stdout);
                   4349:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  4350:    
                   4351:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   4352:     
                   4353:     /*  printf(" %f ",p[i]);
                   4354:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   4355:   }
                   4356:   
                   4357:   for (i=1;i<=npar;i++) {
                   4358:     for (j=1;j<=npar;j++)  {
                   4359:       if (j>i) { 
1.203     brouard  4360:        printf(".%d-%d",i,j);fflush(stdout);
                   4361:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   4362:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  4363:        
                   4364:        hess[j][i]=hess[i][j];    
                   4365:        /*printf(" %lf ",hess[i][j]);*/
                   4366:       }
                   4367:     }
                   4368:   }
                   4369:   printf("\n");
                   4370:   fprintf(ficlog,"\n");
                   4371: 
                   4372:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4373:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4374:   
                   4375:   a=matrix(1,npar,1,npar);
                   4376:   y=matrix(1,npar,1,npar);
                   4377:   x=vector(1,npar);
                   4378:   indx=ivector(1,npar);
                   4379:   for (i=1;i<=npar;i++)
                   4380:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   4381:   ludcmp(a,npar,indx,&pd);
                   4382: 
                   4383:   for (j=1;j<=npar;j++) {
                   4384:     for (i=1;i<=npar;i++) x[i]=0;
                   4385:     x[j]=1;
                   4386:     lubksb(a,npar,indx,x);
                   4387:     for (i=1;i<=npar;i++){ 
                   4388:       matcov[i][j]=x[i];
                   4389:     }
                   4390:   }
                   4391: 
                   4392:   printf("\n#Hessian matrix#\n");
                   4393:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   4394:   for (i=1;i<=npar;i++) { 
                   4395:     for (j=1;j<=npar;j++) { 
1.203     brouard  4396:       printf("%.6e ",hess[i][j]);
                   4397:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  4398:     }
                   4399:     printf("\n");
                   4400:     fprintf(ficlog,"\n");
                   4401:   }
                   4402: 
1.203     brouard  4403:   /* printf("\n#Covariance matrix#\n"); */
                   4404:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   4405:   /* for (i=1;i<=npar;i++) {  */
                   4406:   /*   for (j=1;j<=npar;j++) {  */
                   4407:   /*     printf("%.6e ",matcov[i][j]); */
                   4408:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   4409:   /*   } */
                   4410:   /*   printf("\n"); */
                   4411:   /*   fprintf(ficlog,"\n"); */
                   4412:   /* } */
                   4413: 
1.126     brouard  4414:   /* Recompute Inverse */
1.203     brouard  4415:   /* for (i=1;i<=npar;i++) */
                   4416:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   4417:   /* ludcmp(a,npar,indx,&pd); */
                   4418: 
                   4419:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   4420: 
                   4421:   /* for (j=1;j<=npar;j++) { */
                   4422:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   4423:   /*   x[j]=1; */
                   4424:   /*   lubksb(a,npar,indx,x); */
                   4425:   /*   for (i=1;i<=npar;i++){  */
                   4426:   /*     y[i][j]=x[i]; */
                   4427:   /*     printf("%.3e ",y[i][j]); */
                   4428:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   4429:   /*   } */
                   4430:   /*   printf("\n"); */
                   4431:   /*   fprintf(ficlog,"\n"); */
                   4432:   /* } */
                   4433: 
                   4434:   /* Verifying the inverse matrix */
                   4435: #ifdef DEBUGHESS
                   4436:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  4437: 
1.203     brouard  4438:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   4439:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  4440: 
                   4441:   for (j=1;j<=npar;j++) {
                   4442:     for (i=1;i<=npar;i++){ 
1.203     brouard  4443:       printf("%.2f ",y[i][j]);
                   4444:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  4445:     }
                   4446:     printf("\n");
                   4447:     fprintf(ficlog,"\n");
                   4448:   }
1.203     brouard  4449: #endif
1.126     brouard  4450: 
                   4451:   free_matrix(a,1,npar,1,npar);
                   4452:   free_matrix(y,1,npar,1,npar);
                   4453:   free_vector(x,1,npar);
                   4454:   free_ivector(indx,1,npar);
1.203     brouard  4455:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  4456: 
                   4457: 
                   4458: }
                   4459: 
                   4460: /*************** hessian matrix ****************/
                   4461: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  4462: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  4463:   int i;
                   4464:   int l=1, lmax=20;
1.203     brouard  4465:   double k1,k2, res, fx;
1.132     brouard  4466:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  4467:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   4468:   int k=0,kmax=10;
                   4469:   double l1;
                   4470: 
                   4471:   fx=func(x);
                   4472:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  4473:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  4474:     l1=pow(10,l);
                   4475:     delts=delt;
                   4476:     for(k=1 ; k <kmax; k=k+1){
                   4477:       delt = delta*(l1*k);
                   4478:       p2[theta]=x[theta] +delt;
1.145     brouard  4479:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  4480:       p2[theta]=x[theta]-delt;
                   4481:       k2=func(p2)-fx;
                   4482:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  4483:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  4484:       
1.203     brouard  4485: #ifdef DEBUGHESSII
1.126     brouard  4486:       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);
                   4487:       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);
                   4488: #endif
                   4489:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   4490:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   4491:        k=kmax;
                   4492:       }
                   4493:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  4494:        k=kmax; l=lmax*10;
1.126     brouard  4495:       }
                   4496:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   4497:        delts=delt;
                   4498:       }
1.203     brouard  4499:     } /* End loop k */
1.126     brouard  4500:   }
                   4501:   delti[theta]=delts;
                   4502:   return res; 
                   4503:   
                   4504: }
                   4505: 
1.203     brouard  4506: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  4507: {
                   4508:   int i;
1.164     brouard  4509:   int l=1, lmax=20;
1.126     brouard  4510:   double k1,k2,k3,k4,res,fx;
1.132     brouard  4511:   double p2[MAXPARM+1];
1.203     brouard  4512:   int k, kmax=1;
                   4513:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  4514: 
                   4515:   int firstime=0;
1.203     brouard  4516:   
1.126     brouard  4517:   fx=func(x);
1.203     brouard  4518:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  4519:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  4520:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4521:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4522:     k1=func(p2)-fx;
                   4523:   
1.203     brouard  4524:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4525:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4526:     k2=func(p2)-fx;
                   4527:   
1.203     brouard  4528:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4529:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4530:     k3=func(p2)-fx;
                   4531:   
1.203     brouard  4532:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4533:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4534:     k4=func(p2)-fx;
1.203     brouard  4535:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   4536:     if(k1*k2*k3*k4 <0.){
1.208     brouard  4537:       firstime=1;
1.203     brouard  4538:       kmax=kmax+10;
1.208     brouard  4539:     }
                   4540:     if(kmax >=10 || firstime ==1){
1.246     brouard  4541:       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);
                   4542:       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  4543:       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);
                   4544:       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);
                   4545:     }
                   4546: #ifdef DEBUGHESSIJ
                   4547:     v1=hess[thetai][thetai];
                   4548:     v2=hess[thetaj][thetaj];
                   4549:     cv12=res;
                   4550:     /* Computing eigen value of Hessian matrix */
                   4551:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4552:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4553:     if ((lc2 <0) || (lc1 <0) ){
                   4554:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4555:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4556:       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);
                   4557:       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);
                   4558:     }
1.126     brouard  4559: #endif
                   4560:   }
                   4561:   return res;
                   4562: }
                   4563: 
1.203     brouard  4564:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   4565: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   4566: /* { */
                   4567: /*   int i; */
                   4568: /*   int l=1, lmax=20; */
                   4569: /*   double k1,k2,k3,k4,res,fx; */
                   4570: /*   double p2[MAXPARM+1]; */
                   4571: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   4572: /*   int k=0,kmax=10; */
                   4573: /*   double l1; */
                   4574:   
                   4575: /*   fx=func(x); */
                   4576: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   4577: /*     l1=pow(10,l); */
                   4578: /*     delts=delt; */
                   4579: /*     for(k=1 ; k <kmax; k=k+1){ */
                   4580: /*       delt = delti*(l1*k); */
                   4581: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   4582: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4583: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4584: /*       k1=func(p2)-fx; */
                   4585:       
                   4586: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4587: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4588: /*       k2=func(p2)-fx; */
                   4589:       
                   4590: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4591: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4592: /*       k3=func(p2)-fx; */
                   4593:       
                   4594: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4595: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4596: /*       k4=func(p2)-fx; */
                   4597: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   4598: /* #ifdef DEBUGHESSIJ */
                   4599: /*       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); */
                   4600: /*       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); */
                   4601: /* #endif */
                   4602: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   4603: /*     k=kmax; */
                   4604: /*       } */
                   4605: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   4606: /*     k=kmax; l=lmax*10; */
                   4607: /*       } */
                   4608: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   4609: /*     delts=delt; */
                   4610: /*       } */
                   4611: /*     } /\* End loop k *\/ */
                   4612: /*   } */
                   4613: /*   delti[theta]=delts; */
                   4614: /*   return res;  */
                   4615: /* } */
                   4616: 
                   4617: 
1.126     brouard  4618: /************** Inverse of matrix **************/
                   4619: void ludcmp(double **a, int n, int *indx, double *d) 
                   4620: { 
                   4621:   int i,imax,j,k; 
                   4622:   double big,dum,sum,temp; 
                   4623:   double *vv; 
                   4624:  
                   4625:   vv=vector(1,n); 
                   4626:   *d=1.0; 
                   4627:   for (i=1;i<=n;i++) { 
                   4628:     big=0.0; 
                   4629:     for (j=1;j<=n;j++) 
                   4630:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  4631:     if (big == 0.0){
                   4632:       printf(" Singular Hessian matrix at row %d:\n",i);
                   4633:       for (j=1;j<=n;j++) {
                   4634:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   4635:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   4636:       }
                   4637:       fflush(ficlog);
                   4638:       fclose(ficlog);
                   4639:       nrerror("Singular matrix in routine ludcmp"); 
                   4640:     }
1.126     brouard  4641:     vv[i]=1.0/big; 
                   4642:   } 
                   4643:   for (j=1;j<=n;j++) { 
                   4644:     for (i=1;i<j;i++) { 
                   4645:       sum=a[i][j]; 
                   4646:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   4647:       a[i][j]=sum; 
                   4648:     } 
                   4649:     big=0.0; 
                   4650:     for (i=j;i<=n;i++) { 
                   4651:       sum=a[i][j]; 
                   4652:       for (k=1;k<j;k++) 
                   4653:        sum -= a[i][k]*a[k][j]; 
                   4654:       a[i][j]=sum; 
                   4655:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   4656:        big=dum; 
                   4657:        imax=i; 
                   4658:       } 
                   4659:     } 
                   4660:     if (j != imax) { 
                   4661:       for (k=1;k<=n;k++) { 
                   4662:        dum=a[imax][k]; 
                   4663:        a[imax][k]=a[j][k]; 
                   4664:        a[j][k]=dum; 
                   4665:       } 
                   4666:       *d = -(*d); 
                   4667:       vv[imax]=vv[j]; 
                   4668:     } 
                   4669:     indx[j]=imax; 
                   4670:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   4671:     if (j != n) { 
                   4672:       dum=1.0/(a[j][j]); 
                   4673:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   4674:     } 
                   4675:   } 
                   4676:   free_vector(vv,1,n);  /* Doesn't work */
                   4677: ;
                   4678: } 
                   4679: 
                   4680: void lubksb(double **a, int n, int *indx, double b[]) 
                   4681: { 
                   4682:   int i,ii=0,ip,j; 
                   4683:   double sum; 
                   4684:  
                   4685:   for (i=1;i<=n;i++) { 
                   4686:     ip=indx[i]; 
                   4687:     sum=b[ip]; 
                   4688:     b[ip]=b[i]; 
                   4689:     if (ii) 
                   4690:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   4691:     else if (sum) ii=i; 
                   4692:     b[i]=sum; 
                   4693:   } 
                   4694:   for (i=n;i>=1;i--) { 
                   4695:     sum=b[i]; 
                   4696:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   4697:     b[i]=sum/a[i][i]; 
                   4698:   } 
                   4699: } 
                   4700: 
                   4701: void pstamp(FILE *fichier)
                   4702: {
1.196     brouard  4703:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  4704: }
                   4705: 
1.297     brouard  4706: void date2dmy(double date,double *day, double *month, double *year){
                   4707:   double yp=0., yp1=0., yp2=0.;
                   4708:   
                   4709:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   4710:                        fractional in yp1 */
                   4711:   *year=yp;
                   4712:   yp2=modf((yp1*12),&yp);
                   4713:   *month=yp;
                   4714:   yp1=modf((yp2*30.5),&yp);
                   4715:   *day=yp;
                   4716:   if(*day==0) *day=1;
                   4717:   if(*month==0) *month=1;
                   4718: }
                   4719: 
1.253     brouard  4720: 
                   4721: 
1.126     brouard  4722: /************ Frequencies ********************/
1.251     brouard  4723: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  4724:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   4725:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  4726: {  /* Some frequencies as well as proposing some starting values */
1.226     brouard  4727:   
1.265     brouard  4728:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  4729:   int iind=0, iage=0;
                   4730:   int mi; /* Effective wave */
                   4731:   int first;
                   4732:   double ***freq; /* Frequencies */
1.268     brouard  4733:   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 */
                   4734:   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  4735:   double *meanq, *stdq, *idq;
1.226     brouard  4736:   double **meanqt;
                   4737:   double *pp, **prop, *posprop, *pospropt;
                   4738:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   4739:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   4740:   double agebegin, ageend;
                   4741:     
                   4742:   pp=vector(1,nlstate);
1.251     brouard  4743:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  4744:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   4745:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   4746:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   4747:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  4748:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  4749:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  4750:   meanqt=matrix(1,lastpass,1,nqtveff);
                   4751:   strcpy(fileresp,"P_");
                   4752:   strcat(fileresp,fileresu);
                   4753:   /*strcat(fileresphtm,fileresu);*/
                   4754:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   4755:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   4756:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   4757:     exit(0);
                   4758:   }
1.240     brouard  4759:   
1.226     brouard  4760:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   4761:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   4762:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4763:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4764:     fflush(ficlog);
                   4765:     exit(70); 
                   4766:   }
                   4767:   else{
                   4768:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  4769: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4770: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4771:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4772:   }
1.319     brouard  4773:   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  4774:   
1.226     brouard  4775:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   4776:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   4777:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4778:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4779:     fflush(ficlog);
                   4780:     exit(70); 
1.240     brouard  4781:   } else{
1.226     brouard  4782:     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  4783: ,<hr size=\"2\" color=\"#EC5E5E\"> \n                                  \
1.214     brouard  4784: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4785:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4786:   }
1.319     brouard  4787:   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  4788:   
1.253     brouard  4789:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   4790:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  4791:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  4792:   j1=0;
1.126     brouard  4793:   
1.227     brouard  4794:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
                   4795:   j=cptcoveff;  /* Only dummy covariates of the model */
1.226     brouard  4796:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  4797:   
                   4798:   
1.226     brouard  4799:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   4800:      reference=low_education V1=0,V2=0
                   4801:      med_educ                V1=1 V2=0, 
                   4802:      high_educ               V1=0 V2=1
                   4803:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcoveff 
                   4804:   */
1.249     brouard  4805:   dateintsum=0;
                   4806:   k2cpt=0;
                   4807: 
1.253     brouard  4808:   if(cptcoveff == 0 )
1.265     brouard  4809:     nl=1;  /* Constant and age model only */
1.253     brouard  4810:   else
                   4811:     nl=2;
1.265     brouard  4812: 
                   4813:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   4814:   /* Loop on nj=1 or 2 if dummy covariates j!=0
                   4815:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
                   4816:    *     freq[s1][s2][iage] =0.
                   4817:    *     Loop on iind
                   4818:    *       ++freq[s1][s2][iage] weighted
                   4819:    *     end iind
                   4820:    *     if covariate and j!0
                   4821:    *       headers Variable on one line
                   4822:    *     endif cov j!=0
                   4823:    *     header of frequency table by age
                   4824:    *     Loop on age
                   4825:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   4826:    *       pos+=freq[s1][s2][iage] weighted
                   4827:    *       Loop on s1 initial state
                   4828:    *         fprintf(ficresp
                   4829:    *       end s1
                   4830:    *     end age
                   4831:    *     if j!=0 computes starting values
                   4832:    *     end compute starting values
                   4833:    *   end j1
                   4834:    * end nl 
                   4835:    */
1.253     brouard  4836:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   4837:     if(nj==1)
                   4838:       j=0;  /* First pass for the constant */
1.265     brouard  4839:     else{
1.253     brouard  4840:       j=cptcoveff; /* Other passes for the covariate values */
1.265     brouard  4841:     }
1.251     brouard  4842:     first=1;
1.265     brouard  4843:     for (j1 = 1; j1 <= (int) pow(2,j); j1++){ /* Loop on all covariates combination of the model, excluding quantitatives, V4=0, V3=0 for example, fixed or varying covariates */
1.251     brouard  4844:       posproptt=0.;
                   4845:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   4846:        scanf("%d", i);*/
                   4847:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  4848:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  4849:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  4850:            freq[i][s2][m]=0;
1.251     brouard  4851:       
                   4852:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  4853:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  4854:          prop[i][m]=0;
                   4855:        posprop[i]=0;
                   4856:        pospropt[i]=0;
                   4857:       }
1.283     brouard  4858:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  4859:         idq[z1]=0.;
                   4860:         meanq[z1]=0.;
                   4861:         stdq[z1]=0.;
1.283     brouard  4862:       }
                   4863:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  4864:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  4865:       /*         meanqt[m][z1]=0.; */
                   4866:       /*       } */
                   4867:       /* }       */
1.251     brouard  4868:       /* dateintsum=0; */
                   4869:       /* k2cpt=0; */
                   4870:       
1.265     brouard  4871:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  4872:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   4873:        bool=1;
                   4874:        if(j !=0){
                   4875:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
                   4876:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   4877:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
                   4878:                /* if(Tvaraff[z1] ==-20){ */
                   4879:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   4880:                /* }else  if(Tvaraff[z1] ==-10){ */
                   4881:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
                   4882:                /* }else  */
                   4883:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){ /* for combination j1 of covariates */
1.265     brouard  4884:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  4885:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
                   4886:                  /* 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", 
                   4887:                     bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   4888:                     j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   4889:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   4890:                } /* Onlyf fixed */
                   4891:              } /* end z1 */
                   4892:            } /* cptcovn > 0 */
                   4893:          } /* end any */
                   4894:        }/* end j==0 */
1.265     brouard  4895:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  4896:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  4897:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  4898:            m=mw[mi][iind];
                   4899:            if(j!=0){
                   4900:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
                   4901:                for (z1=1; z1<=cptcoveff; z1++) {
                   4902:                  if( Fixed[Tmodelind[z1]]==1){
                   4903:                    iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   4904:                    if (cotvar[m][iv][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality. If covariate's 
                   4905:                                                                                      value is -1, we don't select. It differs from the 
                   4906:                                                                                      constant and age model which counts them. */
                   4907:                      bool=0; /* not selected */
                   4908:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
                   4909:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   4910:                      bool=0;
                   4911:                    }
                   4912:                  }
                   4913:                }
                   4914:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   4915:            } /* end j==0 */
                   4916:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  4917:            if(bool==1){ /*Selected */
1.251     brouard  4918:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   4919:                 and mw[mi+1][iind]. dh depends on stepm. */
                   4920:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   4921:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   4922:              if(m >=firstpass && m <=lastpass){
                   4923:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   4924:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   4925:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   4926:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   4927:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   4928:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   4929:                if (m<lastpass) {
                   4930:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   4931:                  /*   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]); */
                   4932:                  if(s[m][iind]==-1)
                   4933:                    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.));
                   4934:                  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  4935:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
                   4936:                    if(!isnan(covar[ncovcol+z1][iind])){
                   4937:                        idq[z1]=idq[z1]+weight[iind];
                   4938:                        meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   4939:                        /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
                   4940:                        stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
                   4941:                    }
1.284     brouard  4942:                  }
1.251     brouard  4943:                  /* if((int)agev[m][iind] == 55) */
                   4944:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   4945:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   4946:                  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  4947:                }
1.251     brouard  4948:              } /* end if between passes */  
                   4949:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   4950:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   4951:                k2cpt++;
                   4952:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  4953:              }
1.251     brouard  4954:            }else{
                   4955:              bool=1;
                   4956:            }/* end bool 2 */
                   4957:          } /* end m */
1.284     brouard  4958:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   4959:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   4960:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   4961:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   4962:          /* } */
1.251     brouard  4963:        } /* end bool */
                   4964:       } /* end iind = 1 to imx */
1.319     brouard  4965:       /* prop[s][age] is fed for any initial and valid live state as well as
1.251     brouard  4966:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   4967:       
                   4968:       
                   4969:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.265     brouard  4970:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
                   4971:         pstamp(ficresp);
1.251     brouard  4972:       if  (cptcoveff>0 && j!=0){
1.265     brouard  4973:         pstamp(ficresp);
1.251     brouard  4974:        printf( "\n#********** Variable "); 
                   4975:        fprintf(ficresp, "\n#********** Variable "); 
                   4976:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   4977:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   4978:        fprintf(ficlog, "\n#********** Variable "); 
                   4979:        for (z1=1; z1<=cptcoveff; z1++){
                   4980:          if(!FixedV[Tvaraff[z1]]){
                   4981:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4982:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4983:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4984:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4985:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.250     brouard  4986:          }else{
1.251     brouard  4987:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4988:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4989:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4990:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4991:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4992:          }
                   4993:        }
                   4994:        printf( "**********\n#");
                   4995:        fprintf(ficresp, "**********\n#");
                   4996:        fprintf(ficresphtm, "**********</h3>\n");
                   4997:        fprintf(ficresphtmfr, "**********</h3>\n");
                   4998:        fprintf(ficlog, "**********\n");
                   4999:       }
1.284     brouard  5000:       /*
                   5001:        Printing means of quantitative variables if any
                   5002:       */
                   5003:       for (z1=1; z1<= nqfveff; z1++) {
1.311     brouard  5004:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.312     brouard  5005:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
1.284     brouard  5006:        if(weightopt==1){
                   5007:          printf(" Weighted mean and standard deviation of");
                   5008:          fprintf(ficlog," Weighted mean and standard deviation of");
                   5009:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   5010:        }
1.311     brouard  5011:        /* mu = \frac{w x}{\sum w}
                   5012:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
                   5013:        */
                   5014:        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]));
                   5015:        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]));
                   5016:        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  5017:       }
                   5018:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   5019:       /*       for(m=1;m<=lastpass;m++){ */
                   5020:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   5021:       /*   } */
                   5022:       /* } */
1.283     brouard  5023: 
1.251     brouard  5024:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.265     brouard  5025:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
                   5026:         fprintf(ficresp, " Age");
                   5027:       if(nj==2) for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " V%d=%d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.251     brouard  5028:       for(i=1; i<=nlstate;i++) {
1.265     brouard  5029:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  5030:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   5031:       }
1.265     brouard  5032:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  5033:       fprintf(ficresphtm, "\n");
                   5034:       
                   5035:       /* Header of frequency table by age */
                   5036:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   5037:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  5038:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  5039:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5040:          if(s2!=0 && m!=0)
                   5041:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  5042:        }
1.226     brouard  5043:       }
1.251     brouard  5044:       fprintf(ficresphtmfr, "\n");
                   5045:     
                   5046:       /* For each age */
                   5047:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   5048:        fprintf(ficresphtm,"<tr>");
                   5049:        if(iage==iagemax+1){
                   5050:          fprintf(ficlog,"1");
                   5051:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   5052:        }else if(iage==iagemax+2){
                   5053:          fprintf(ficlog,"0");
                   5054:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   5055:        }else if(iage==iagemax+3){
                   5056:          fprintf(ficlog,"Total");
                   5057:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   5058:        }else{
1.240     brouard  5059:          if(first==1){
1.251     brouard  5060:            first=0;
                   5061:            printf("See log file for details...\n");
                   5062:          }
                   5063:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   5064:          fprintf(ficlog,"Age %d", iage);
                   5065:        }
1.265     brouard  5066:        for(s1=1; s1 <=nlstate ; s1++){
                   5067:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   5068:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  5069:        }
1.265     brouard  5070:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5071:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  5072:            pos += freq[s1][m][iage];
                   5073:          if(pp[s1]>=1.e-10){
1.251     brouard  5074:            if(first==1){
1.265     brouard  5075:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5076:            }
1.265     brouard  5077:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5078:          }else{
                   5079:            if(first==1)
1.265     brouard  5080:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   5081:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  5082:          }
                   5083:        }
                   5084:       
1.265     brouard  5085:        for(s1=1; s1 <=nlstate ; s1++){ 
                   5086:          /* posprop[s1]=0; */
                   5087:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   5088:            pp[s1] += freq[s1][m][iage];
                   5089:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   5090:       
                   5091:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   5092:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   5093:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5094:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5095:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5096:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5097:        }
                   5098:        
                   5099:        /* Writing ficresp */
                   5100:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
                   5101:           if( iage <= iagemax){
                   5102:            fprintf(ficresp," %d",iage);
                   5103:           }
                   5104:         }else if( nj==2){
                   5105:           if( iage <= iagemax){
                   5106:            fprintf(ficresp," %d",iage);
                   5107:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   5108:           }
1.240     brouard  5109:        }
1.265     brouard  5110:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  5111:          if(pos>=1.e-5){
1.251     brouard  5112:            if(first==1)
1.265     brouard  5113:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   5114:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  5115:          }else{
                   5116:            if(first==1)
1.265     brouard  5117:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   5118:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  5119:          }
                   5120:          if( iage <= iagemax){
                   5121:            if(pos>=1.e-5){
1.265     brouard  5122:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
                   5123:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5124:               }else if( nj==2){
                   5125:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5126:               }
                   5127:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5128:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   5129:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   5130:            } else{
                   5131:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
                   5132:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  5133:            }
1.240     brouard  5134:          }
1.265     brouard  5135:          pospropt[s1] +=posprop[s1];
                   5136:        } /* end loop s1 */
1.251     brouard  5137:        /* pospropt=0.; */
1.265     brouard  5138:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  5139:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5140:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  5141:              if(first==1){
1.265     brouard  5142:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5143:              }
1.265     brouard  5144:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   5145:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5146:            }
1.265     brouard  5147:            if(s1!=0 && m!=0)
                   5148:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  5149:          }
1.265     brouard  5150:        } /* end loop s1 */
1.251     brouard  5151:        posproptt=0.; 
1.265     brouard  5152:        for(s1=1; s1 <=nlstate; s1++){
                   5153:          posproptt += pospropt[s1];
1.251     brouard  5154:        }
                   5155:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  5156:        fprintf(ficresphtm,"</tr>\n");
                   5157:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
                   5158:          if(iage <= iagemax)
                   5159:            fprintf(ficresp,"\n");
1.240     brouard  5160:        }
1.251     brouard  5161:        if(first==1)
                   5162:          printf("Others in log...\n");
                   5163:        fprintf(ficlog,"\n");
                   5164:       } /* end loop age iage */
1.265     brouard  5165:       
1.251     brouard  5166:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  5167:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5168:        if(posproptt < 1.e-5){
1.265     brouard  5169:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  5170:        }else{
1.265     brouard  5171:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  5172:        }
1.226     brouard  5173:       }
1.251     brouard  5174:       fprintf(ficresphtm,"</tr>\n");
                   5175:       fprintf(ficresphtm,"</table>\n");
                   5176:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  5177:       if(posproptt < 1.e-5){
1.251     brouard  5178:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   5179:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  5180:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   5181:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  5182:        invalidvarcomb[j1]=1;
1.226     brouard  5183:       }else{
1.251     brouard  5184:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
                   5185:        invalidvarcomb[j1]=0;
1.226     brouard  5186:       }
1.251     brouard  5187:       fprintf(ficresphtmfr,"</table>\n");
                   5188:       fprintf(ficlog,"\n");
                   5189:       if(j!=0){
                   5190:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  5191:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5192:          for(k=1; k <=(nlstate+ndeath); k++){
                   5193:            if (k != i) {
1.265     brouard  5194:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  5195:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  5196:                  if(j1==1){ /* All dummy covariates to zero */
                   5197:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   5198:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  5199:                    printf("%d%d ",i,k);
                   5200:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5201:                    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]));
                   5202:                    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]));
                   5203:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  5204:                  }
1.253     brouard  5205:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   5206:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   5207:                    x[iage]= (double)iage;
                   5208:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  5209:                    /* 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  5210:                  }
1.268     brouard  5211:                  /* Some are not finite, but linreg will ignore these ages */
                   5212:                  no=0;
1.253     brouard  5213:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  5214:                  pstart[s1]=b;
                   5215:                  pstart[s1-1]=a;
1.252     brouard  5216:                }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 */ 
                   5217:                  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]);
                   5218:                  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  5219:                  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  5220:                  printf("%d%d ",i,k);
                   5221:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5222:                  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  5223:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   5224:                  ;
                   5225:                }
                   5226:                /* printf("%12.7f )", param[i][jj][k]); */
                   5227:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5228:                s1++; 
1.251     brouard  5229:              } /* end jj */
                   5230:            } /* end k!= i */
                   5231:          } /* end k */
1.265     brouard  5232:        } /* end i, s1 */
1.251     brouard  5233:       } /* end j !=0 */
                   5234:     } /* end selected combination of covariate j1 */
                   5235:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   5236:       printf("#Freqsummary: Starting values for the constants:\n");
                   5237:       fprintf(ficlog,"\n");
1.265     brouard  5238:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5239:        for(k=1; k <=(nlstate+ndeath); k++){
                   5240:          if (k != i) {
                   5241:            printf("%d%d ",i,k);
                   5242:            fprintf(ficlog,"%d%d ",i,k);
                   5243:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  5244:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  5245:              if(jj==1){ /* Age has to be done */
1.265     brouard  5246:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   5247:                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]));
                   5248:                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  5249:              }
                   5250:              /* printf("%12.7f )", param[i][jj][k]); */
                   5251:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5252:              s1++; 
1.250     brouard  5253:            }
1.251     brouard  5254:            printf("\n");
                   5255:            fprintf(ficlog,"\n");
1.250     brouard  5256:          }
                   5257:        }
1.284     brouard  5258:       } /* end of state i */
1.251     brouard  5259:       printf("#Freqsummary\n");
                   5260:       fprintf(ficlog,"\n");
1.265     brouard  5261:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   5262:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   5263:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   5264:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5265:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5266:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   5267:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   5268:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  5269:          /* } */
                   5270:        }
1.265     brouard  5271:       } /* end loop s1 */
1.251     brouard  5272:       
                   5273:       printf("\n");
                   5274:       fprintf(ficlog,"\n");
                   5275:     } /* end j=0 */
1.249     brouard  5276:   } /* end j */
1.252     brouard  5277: 
1.253     brouard  5278:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  5279:     for(i=1, jk=1; i <=nlstate; i++){
                   5280:       for(j=1; j <=nlstate+ndeath; j++){
                   5281:        if(j!=i){
                   5282:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5283:          printf("%1d%1d",i,j);
                   5284:          fprintf(ficparo,"%1d%1d",i,j);
                   5285:          for(k=1; k<=ncovmodel;k++){
                   5286:            /*    printf(" %lf",param[i][j][k]); */
                   5287:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   5288:            p[jk]=pstart[jk];
                   5289:            printf(" %f ",pstart[jk]);
                   5290:            fprintf(ficparo," %f ",pstart[jk]);
                   5291:            jk++;
                   5292:          }
                   5293:          printf("\n");
                   5294:          fprintf(ficparo,"\n");
                   5295:        }
                   5296:       }
                   5297:     }
                   5298:   } /* end mle=-2 */
1.226     brouard  5299:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  5300:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  5301:   
1.226     brouard  5302:   fclose(ficresp);
                   5303:   fclose(ficresphtm);
                   5304:   fclose(ficresphtmfr);
1.283     brouard  5305:   free_vector(idq,1,nqfveff);
1.226     brouard  5306:   free_vector(meanq,1,nqfveff);
1.284     brouard  5307:   free_vector(stdq,1,nqfveff);
1.226     brouard  5308:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  5309:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   5310:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  5311:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5312:   free_vector(pospropt,1,nlstate);
                   5313:   free_vector(posprop,1,nlstate);
1.251     brouard  5314:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5315:   free_vector(pp,1,nlstate);
                   5316:   /* End of freqsummary */
                   5317: }
1.126     brouard  5318: 
1.268     brouard  5319: /* Simple linear regression */
                   5320: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   5321: 
                   5322:   /* y=a+bx regression */
                   5323:   double   sumx = 0.0;                        /* sum of x                      */
                   5324:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   5325:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   5326:   double   sumy = 0.0;                        /* sum of y                      */
                   5327:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   5328:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   5329:   double yhat;
                   5330:   
                   5331:   double denom=0;
                   5332:   int i;
                   5333:   int ne=*no;
                   5334:   
                   5335:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5336:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5337:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5338:       continue;
                   5339:     }
                   5340:     ne=ne+1;
                   5341:     sumx  += x[i];       
                   5342:     sumx2 += x[i]*x[i];  
                   5343:     sumxy += x[i] * y[i];
                   5344:     sumy  += y[i];      
                   5345:     sumy2 += y[i]*y[i]; 
                   5346:     denom = (ne * sumx2 - sumx*sumx);
                   5347:     /* 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); */
                   5348:   } 
                   5349:   
                   5350:   denom = (ne * sumx2 - sumx*sumx);
                   5351:   if (denom == 0) {
                   5352:     // vertical, slope m is infinity
                   5353:     *b = INFINITY;
                   5354:     *a = 0;
                   5355:     if (r) *r = 0;
                   5356:     return 1;
                   5357:   }
                   5358:   
                   5359:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   5360:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   5361:   if (r!=NULL) {
                   5362:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   5363:       sqrt((sumx2 - sumx*sumx/ne) *
                   5364:           (sumy2 - sumy*sumy/ne));
                   5365:   }
                   5366:   *no=ne;
                   5367:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5368:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5369:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5370:       continue;
                   5371:     }
                   5372:     ne=ne+1;
                   5373:     yhat = y[i] - *a -*b* x[i];
                   5374:     sume2  += yhat * yhat ;       
                   5375:     
                   5376:     denom = (ne * sumx2 - sumx*sumx);
                   5377:     /* 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); */
                   5378:   } 
                   5379:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   5380:   *sa= *sb * sqrt(sumx2/ne);
                   5381:   
                   5382:   return 0; 
                   5383: }
                   5384: 
1.126     brouard  5385: /************ Prevalence ********************/
1.227     brouard  5386: 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)
                   5387: {  
                   5388:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   5389:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   5390:      We still use firstpass and lastpass as another selection.
                   5391:   */
1.126     brouard  5392:  
1.227     brouard  5393:   int i, m, jk, j1, bool, z1,j, iv;
                   5394:   int mi; /* Effective wave */
                   5395:   int iage;
                   5396:   double agebegin, ageend;
                   5397: 
                   5398:   double **prop;
                   5399:   double posprop; 
                   5400:   double  y2; /* in fractional years */
                   5401:   int iagemin, iagemax;
                   5402:   int first; /** to stop verbosity which is redirected to log file */
                   5403: 
                   5404:   iagemin= (int) agemin;
                   5405:   iagemax= (int) agemax;
                   5406:   /*pp=vector(1,nlstate);*/
1.251     brouard  5407:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  5408:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   5409:   j1=0;
1.222     brouard  5410:   
1.227     brouard  5411:   /*j=cptcoveff;*/
                   5412:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  5413:   
1.288     brouard  5414:   first=0;
1.227     brouard  5415:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of covariate */
                   5416:     for (i=1; i<=nlstate; i++)  
1.251     brouard  5417:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  5418:        prop[i][iage]=0.0;
                   5419:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   5420:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   5421:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   5422:     
                   5423:     for (i=1; i<=imx; i++) { /* Each individual */
                   5424:       bool=1;
                   5425:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   5426:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   5427:        m=mw[mi][i];
                   5428:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   5429:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   5430:        for (z1=1; z1<=cptcoveff; z1++){
                   5431:          if( Fixed[Tmodelind[z1]]==1){
                   5432:            iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   5433:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality */
                   5434:              bool=0;
                   5435:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
                   5436:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   5437:              bool=0;
                   5438:            }
                   5439:        }
                   5440:        if(bool==1){ /* Otherwise we skip that wave/person */
                   5441:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   5442:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   5443:          if(m >=firstpass && m <=lastpass){
                   5444:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   5445:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   5446:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   5447:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  5448:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  5449:                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); 
                   5450:                exit(1);
                   5451:              }
                   5452:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   5453:                /*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]]);*/
                   5454:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   5455:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   5456:              } /* end valid statuses */ 
                   5457:            } /* end selection of dates */
                   5458:          } /* end selection of waves */
                   5459:        } /* end bool */
                   5460:       } /* end wave */
                   5461:     } /* end individual */
                   5462:     for(i=iagemin; i <= iagemax+3; i++){  
                   5463:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   5464:        posprop += prop[jk][i]; 
                   5465:       } 
                   5466:       
                   5467:       for(jk=1; jk <=nlstate ; jk++){      
                   5468:        if( i <=  iagemax){ 
                   5469:          if(posprop>=1.e-5){ 
                   5470:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   5471:          } else{
1.288     brouard  5472:            if(!first){
                   5473:              first=1;
1.266     brouard  5474:              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]);
                   5475:            }else{
1.288     brouard  5476:              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  5477:            }
                   5478:          }
                   5479:        } 
                   5480:       }/* end jk */ 
                   5481:     }/* end i */ 
1.222     brouard  5482:      /*} *//* end i1 */
1.227     brouard  5483:   } /* end j1 */
1.222     brouard  5484:   
1.227     brouard  5485:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   5486:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  5487:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  5488: }  /* End of prevalence */
1.126     brouard  5489: 
                   5490: /************* Waves Concatenation ***************/
                   5491: 
                   5492: 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)
                   5493: {
1.298     brouard  5494:   /* 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  5495:      Death is a valid wave (if date is known).
                   5496:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   5497:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  5498:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  5499:   */
1.126     brouard  5500: 
1.224     brouard  5501:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  5502:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   5503:      double sum=0., jmean=0.;*/
1.224     brouard  5504:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  5505:   int j, k=0,jk, ju, jl;
                   5506:   double sum=0.;
                   5507:   first=0;
1.214     brouard  5508:   firstwo=0;
1.217     brouard  5509:   firsthree=0;
1.218     brouard  5510:   firstfour=0;
1.164     brouard  5511:   jmin=100000;
1.126     brouard  5512:   jmax=-1;
                   5513:   jmean=0.;
1.224     brouard  5514: 
                   5515: /* Treating live states */
1.214     brouard  5516:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  5517:     mi=0;  /* First valid wave */
1.227     brouard  5518:     mli=0; /* Last valid wave */
1.309     brouard  5519:     m=firstpass;  /* Loop on waves */
                   5520:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
1.227     brouard  5521:       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 */
                   5522:        mli=m-1;/* mw[++mi][i]=m-1; */
                   5523:       }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  5524:        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  5525:        mli=m;
1.224     brouard  5526:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   5527:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  5528:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  5529:       }
1.309     brouard  5530:       else{ /* m = lastpass, eventual special issue with warning */
1.224     brouard  5531: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  5532:        break;
1.224     brouard  5533: #else
1.317     brouard  5534:        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  5535:          if(firsthree == 0){
1.302     brouard  5536:            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  5537:            firsthree=1;
1.317     brouard  5538:          }else if(firsthree >=1 && firsthree < 10){
                   5539:            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);
                   5540:            firsthree++;
                   5541:          }else if(firsthree == 10){
                   5542:            printf("Information, too many Information flags: no more reported to log either\n");
                   5543:            fprintf(ficlog,"Information, too many Information flags: no more reported to log either\n");
                   5544:            firsthree++;
                   5545:          }else{
                   5546:            firsthree++;
1.227     brouard  5547:          }
1.309     brouard  5548:          mw[++mi][i]=m; /* Valid transition with unknown status */
1.227     brouard  5549:          mli=m;
                   5550:        }
                   5551:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   5552:          nbwarn++;
1.309     brouard  5553:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
1.227     brouard  5554:            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);
                   5555:            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);
                   5556:          }
                   5557:          break;
                   5558:        }
                   5559:        break;
1.224     brouard  5560: #endif
1.227     brouard  5561:       }/* End m >= lastpass */
1.126     brouard  5562:     }/* end while */
1.224     brouard  5563: 
1.227     brouard  5564:     /* 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  5565:     /* After last pass */
1.224     brouard  5566: /* Treating death states */
1.214     brouard  5567:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  5568:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   5569:       /* } */
1.126     brouard  5570:       mi++;    /* Death is another wave */
                   5571:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  5572:       /* Only death is a correct wave */
1.126     brouard  5573:       mw[mi][i]=m;
1.257     brouard  5574:     } /* else not in a death state */
1.224     brouard  5575: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  5576:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  5577:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.309     brouard  5578:        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  5579:          nbwarn++;
                   5580:          if(firstfiv==0){
1.309     brouard  5581:            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  5582:            firstfiv=1;
                   5583:          }else{
1.309     brouard  5584:            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  5585:          }
1.309     brouard  5586:            s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
                   5587:        }else{ /* Month of Death occured afer last wave month, potential bias */
1.227     brouard  5588:          nberr++;
                   5589:          if(firstwo==0){
1.309     brouard  5590:            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  5591:            firstwo=1;
                   5592:          }
1.309     brouard  5593:          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  5594:        }
1.257     brouard  5595:       }else{ /* if date of interview is unknown */
1.227     brouard  5596:        /* death is known but not confirmed by death status at any wave */
                   5597:        if(firstfour==0){
1.309     brouard  5598:          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  5599:          firstfour=1;
                   5600:        }
1.309     brouard  5601:        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  5602:       }
1.224     brouard  5603:     } /* end if date of death is known */
                   5604: #endif
1.309     brouard  5605:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
                   5606:     /* wav[i]=mw[mi][i];   */
1.126     brouard  5607:     if(mi==0){
                   5608:       nbwarn++;
                   5609:       if(first==0){
1.227     brouard  5610:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   5611:        first=1;
1.126     brouard  5612:       }
                   5613:       if(first==1){
1.227     brouard  5614:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  5615:       }
                   5616:     } /* end mi==0 */
                   5617:   } /* End individuals */
1.214     brouard  5618:   /* wav and mw are no more changed */
1.223     brouard  5619:        
1.317     brouard  5620:   printf("Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   5621:   fprintf(ficlog,"Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   5622: 
                   5623: 
1.126     brouard  5624:   for(i=1; i<=imx; i++){
                   5625:     for(mi=1; mi<wav[i];mi++){
                   5626:       if (stepm <=0)
1.227     brouard  5627:        dh[mi][i]=1;
1.126     brouard  5628:       else{
1.260     brouard  5629:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  5630:          if (agedc[i] < 2*AGESUP) {
                   5631:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   5632:            if(j==0) j=1;  /* Survives at least one month after exam */
                   5633:            else if(j<0){
                   5634:              nberr++;
                   5635:              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]);
                   5636:              j=1; /* Temporary Dangerous patch */
                   5637:              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);
                   5638:              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]);
                   5639:              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);
                   5640:            }
                   5641:            k=k+1;
                   5642:            if (j >= jmax){
                   5643:              jmax=j;
                   5644:              ijmax=i;
                   5645:            }
                   5646:            if (j <= jmin){
                   5647:              jmin=j;
                   5648:              ijmin=i;
                   5649:            }
                   5650:            sum=sum+j;
                   5651:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   5652:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   5653:          }
                   5654:        }
                   5655:        else{
                   5656:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  5657: /*       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  5658:                                        
1.227     brouard  5659:          k=k+1;
                   5660:          if (j >= jmax) {
                   5661:            jmax=j;
                   5662:            ijmax=i;
                   5663:          }
                   5664:          else if (j <= jmin){
                   5665:            jmin=j;
                   5666:            ijmin=i;
                   5667:          }
                   5668:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   5669:          /*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]);*/
                   5670:          if(j<0){
                   5671:            nberr++;
                   5672:            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]);
                   5673:            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]);
                   5674:          }
                   5675:          sum=sum+j;
                   5676:        }
                   5677:        jk= j/stepm;
                   5678:        jl= j -jk*stepm;
                   5679:        ju= j -(jk+1)*stepm;
                   5680:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   5681:          if(jl==0){
                   5682:            dh[mi][i]=jk;
                   5683:            bh[mi][i]=0;
                   5684:          }else{ /* We want a negative bias in order to only have interpolation ie
                   5685:                  * to avoid the price of an extra matrix product in likelihood */
                   5686:            dh[mi][i]=jk+1;
                   5687:            bh[mi][i]=ju;
                   5688:          }
                   5689:        }else{
                   5690:          if(jl <= -ju){
                   5691:            dh[mi][i]=jk;
                   5692:            bh[mi][i]=jl;       /* bias is positive if real duration
                   5693:                                 * is higher than the multiple of stepm and negative otherwise.
                   5694:                                 */
                   5695:          }
                   5696:          else{
                   5697:            dh[mi][i]=jk+1;
                   5698:            bh[mi][i]=ju;
                   5699:          }
                   5700:          if(dh[mi][i]==0){
                   5701:            dh[mi][i]=1; /* At least one step */
                   5702:            bh[mi][i]=ju; /* At least one step */
                   5703:            /*  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);*/
                   5704:          }
                   5705:        } /* end if mle */
1.126     brouard  5706:       }
                   5707:     } /* end wave */
                   5708:   }
                   5709:   jmean=sum/k;
                   5710:   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  5711:   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  5712: }
1.126     brouard  5713: 
                   5714: /*********** Tricode ****************************/
1.220     brouard  5715:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  5716:  {
                   5717:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   5718:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   5719:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   5720:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   5721:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   5722:     */
1.130     brouard  5723: 
1.242     brouard  5724:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   5725:    int modmaxcovj=0; /* Modality max of covariates j */
                   5726:    int cptcode=0; /* Modality max of covariates j */
                   5727:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  5728: 
                   5729: 
1.242     brouard  5730:    /* cptcoveff=0;  */
                   5731:    /* *cptcov=0; */
1.126     brouard  5732:  
1.242     brouard  5733:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  5734:    for (k=1; k <= maxncov; k++)
                   5735:      for(j=1; j<=2; j++)
                   5736:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  5737: 
1.242     brouard  5738:    /* Loop on covariates without age and products and no quantitative variable */
                   5739:    for (k=1; k<=cptcovt; k++) { /* From model V1 + V2*age + V3 + V3*V4 keeps V1 + V3 = 2 only */
                   5740:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
                   5741:      if(Dummy[k]==0 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
                   5742:        switch(Fixed[k]) {
                   5743:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.311     brouard  5744:         modmaxcovj=0;
                   5745:         modmincovj=0;
1.242     brouard  5746:         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*/
                   5747:           ij=(int)(covar[Tvar[k]][i]);
                   5748:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   5749:            * If product of Vn*Vm, still boolean *:
                   5750:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   5751:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   5752:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   5753:              modality of the nth covariate of individual i. */
                   5754:           if (ij > modmaxcovj)
                   5755:             modmaxcovj=ij; 
                   5756:           else if (ij < modmincovj) 
                   5757:             modmincovj=ij; 
1.287     brouard  5758:           if (ij <0 || ij >1 ){
1.311     brouard  5759:             printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   5760:             fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   5761:             fflush(ficlog);
                   5762:             exit(1);
1.287     brouard  5763:           }
                   5764:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  5765:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   5766:             exit(1);
                   5767:           }else
                   5768:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   5769:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   5770:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   5771:           /* getting the maximum value of the modality of the covariate
                   5772:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   5773:              female ies 1, then modmaxcovj=1.
                   5774:           */
                   5775:         } /* end for loop on individuals i */
                   5776:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   5777:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   5778:         cptcode=modmaxcovj;
                   5779:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   5780:         /*for (i=0; i<=cptcode; i++) {*/
                   5781:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   5782:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   5783:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   5784:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   5785:             if( j != -1){
                   5786:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   5787:                                  covariate for which somebody answered excluding 
                   5788:                                  undefined. Usually 2: 0 and 1. */
                   5789:             }
                   5790:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   5791:                                     covariate for which somebody answered including 
                   5792:                                     undefined. Usually 3: -1, 0 and 1. */
                   5793:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   5794:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   5795:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  5796:                        
1.242     brouard  5797:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   5798:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   5799:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   5800:         /* modmincovj=3; modmaxcovj = 7; */
                   5801:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   5802:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   5803:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   5804:         /* nbcode[Tvar[j]][ij]=k; */
                   5805:         /* nbcode[Tvar[j]][1]=0; */
                   5806:         /* nbcode[Tvar[j]][2]=1; */
                   5807:         /* nbcode[Tvar[j]][3]=2; */
                   5808:         /* To be continued (not working yet). */
                   5809:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  5810: 
                   5811:         /* 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*/
                   5812:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   5813:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   5814:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   5815:         /*, could be restored in the future */
                   5816:         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  5817:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   5818:             break;
                   5819:           }
                   5820:           ij++;
1.287     brouard  5821:           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  5822:           cptcode = ij; /* New max modality for covar j */
                   5823:         } /* end of loop on modality i=-1 to 1 or more */
                   5824:         break;
                   5825:        case 1: /* Testing on varying covariate, could be simple and
                   5826:                * should look at waves or product of fixed *
                   5827:                * varying. No time to test -1, assuming 0 and 1 only */
                   5828:         ij=0;
                   5829:         for(i=0; i<=1;i++){
                   5830:           nbcode[Tvar[k]][++ij]=i;
                   5831:         }
                   5832:         break;
                   5833:        default:
                   5834:         break;
                   5835:        } /* end switch */
                   5836:      } /* end dummy test */
1.311     brouard  5837:      if(Dummy[k]==1 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
                   5838:        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*/
                   5839:         if(isnan(covar[Tvar[k]][i])){
                   5840:           printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   5841:           fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   5842:           fflush(ficlog);
                   5843:           exit(1);
                   5844:          }
                   5845:        }
                   5846:      }
1.287     brouard  5847:    } /* 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  5848:   
                   5849:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   5850:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   5851:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   5852:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   5853:      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 */ 
                   5854:      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 */
                   5855:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   5856:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   5857:   
                   5858:    ij=0;
                   5859:    /* for (i=0; i<=  maxncov-1; i++) { /\* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) *\/ */
                   5860:    for (k=1; k<=  cptcovt; k++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   5861:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   5862:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
                   5863:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy and non empty in the model */
                   5864:        /* If product not in single variable we don't print results */
                   5865:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   5866:        ++ij;/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, */
                   5867:        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*/
                   5868:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   5869:        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 */
                   5870:        if(Fixed[k]!=0)
                   5871:         anyvaryingduminmodel=1;
                   5872:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   5873:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   5874:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   5875:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   5876:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   5877:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   5878:      } 
                   5879:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   5880:    /* ij--; */
                   5881:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
                   5882:    *cptcov=ij; /*Number of total real effective covariates: effective
                   5883:                * because they can be excluded from the model and real
                   5884:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   5885:    for(j=ij+1; j<= cptcovt; j++){
                   5886:      Tvaraff[j]=0;
                   5887:      Tmodelind[j]=0;
                   5888:    }
                   5889:    for(j=ntveff+1; j<= cptcovt; j++){
                   5890:      TmodelInvind[j]=0;
                   5891:    }
                   5892:    /* To be sorted */
                   5893:    ;
                   5894:  }
1.126     brouard  5895: 
1.145     brouard  5896: 
1.126     brouard  5897: /*********** Health Expectancies ****************/
                   5898: 
1.235     brouard  5899:  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  5900: 
                   5901: {
                   5902:   /* Health expectancies, no variances */
1.164     brouard  5903:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  5904:   int nhstepma, nstepma; /* Decreasing with age */
                   5905:   double age, agelim, hf;
                   5906:   double ***p3mat;
                   5907:   double eip;
                   5908: 
1.238     brouard  5909:   /* pstamp(ficreseij); */
1.126     brouard  5910:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   5911:   fprintf(ficreseij,"# Age");
                   5912:   for(i=1; i<=nlstate;i++){
                   5913:     for(j=1; j<=nlstate;j++){
                   5914:       fprintf(ficreseij," e%1d%1d ",i,j);
                   5915:     }
                   5916:     fprintf(ficreseij," e%1d. ",i);
                   5917:   }
                   5918:   fprintf(ficreseij,"\n");
                   5919: 
                   5920:   
                   5921:   if(estepm < stepm){
                   5922:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5923:   }
                   5924:   else  hstepm=estepm;   
                   5925:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   5926:    * This is mainly to measure the difference between two models: for example
                   5927:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   5928:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   5929:    * progression in between and thus overestimating or underestimating according
                   5930:    * to the curvature of the survival function. If, for the same date, we 
                   5931:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   5932:    * to compare the new estimate of Life expectancy with the same linear 
                   5933:    * hypothesis. A more precise result, taking into account a more precise
                   5934:    * curvature will be obtained if estepm is as small as stepm. */
                   5935: 
                   5936:   /* For example we decided to compute the life expectancy with the smallest unit */
                   5937:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5938:      nhstepm is the number of hstepm from age to agelim 
                   5939:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  5940:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  5941:      and note for a fixed period like estepm months */
                   5942:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   5943:      survival function given by stepm (the optimization length). Unfortunately it
                   5944:      means that if the survival funtion is printed only each two years of age and if
                   5945:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5946:      results. So we changed our mind and took the option of the best precision.
                   5947:   */
                   5948:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5949: 
                   5950:   agelim=AGESUP;
                   5951:   /* If stepm=6 months */
                   5952:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   5953:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   5954:     
                   5955: /* nhstepm age range expressed in number of stepm */
                   5956:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5957:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5958:   /* if (stepm >= YEARM) hstepm=1;*/
                   5959:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5960:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5961: 
                   5962:   for (age=bage; age<=fage; age ++){ 
                   5963:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5964:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5965:     /* if (stepm >= YEARM) hstepm=1;*/
                   5966:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   5967: 
                   5968:     /* If stepm=6 months */
                   5969:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   5970:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   5971:     
1.235     brouard  5972:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  5973:     
                   5974:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   5975:     
                   5976:     printf("%d|",(int)age);fflush(stdout);
                   5977:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   5978:     
                   5979:     /* Computing expectancies */
                   5980:     for(i=1; i<=nlstate;i++)
                   5981:       for(j=1; j<=nlstate;j++)
                   5982:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   5983:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   5984:          
                   5985:          /* 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]);*/
                   5986: 
                   5987:        }
                   5988: 
                   5989:     fprintf(ficreseij,"%3.0f",age );
                   5990:     for(i=1; i<=nlstate;i++){
                   5991:       eip=0;
                   5992:       for(j=1; j<=nlstate;j++){
                   5993:        eip +=eij[i][j][(int)age];
                   5994:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   5995:       }
                   5996:       fprintf(ficreseij,"%9.4f", eip );
                   5997:     }
                   5998:     fprintf(ficreseij,"\n");
                   5999:     
                   6000:   }
                   6001:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6002:   printf("\n");
                   6003:   fprintf(ficlog,"\n");
                   6004:   
                   6005: }
                   6006: 
1.235     brouard  6007:  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  6008: 
                   6009: {
                   6010:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  6011:      to initial status i, ei. .
1.126     brouard  6012:   */
                   6013:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   6014:   int nhstepma, nstepma; /* Decreasing with age */
                   6015:   double age, agelim, hf;
                   6016:   double ***p3matp, ***p3matm, ***varhe;
                   6017:   double **dnewm,**doldm;
                   6018:   double *xp, *xm;
                   6019:   double **gp, **gm;
                   6020:   double ***gradg, ***trgradg;
                   6021:   int theta;
                   6022: 
                   6023:   double eip, vip;
                   6024: 
                   6025:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   6026:   xp=vector(1,npar);
                   6027:   xm=vector(1,npar);
                   6028:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   6029:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   6030:   
                   6031:   pstamp(ficresstdeij);
                   6032:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   6033:   fprintf(ficresstdeij,"# Age");
                   6034:   for(i=1; i<=nlstate;i++){
                   6035:     for(j=1; j<=nlstate;j++)
                   6036:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   6037:     fprintf(ficresstdeij," e%1d. ",i);
                   6038:   }
                   6039:   fprintf(ficresstdeij,"\n");
                   6040: 
                   6041:   pstamp(ficrescveij);
                   6042:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   6043:   fprintf(ficrescveij,"# Age");
                   6044:   for(i=1; i<=nlstate;i++)
                   6045:     for(j=1; j<=nlstate;j++){
                   6046:       cptj= (j-1)*nlstate+i;
                   6047:       for(i2=1; i2<=nlstate;i2++)
                   6048:        for(j2=1; j2<=nlstate;j2++){
                   6049:          cptj2= (j2-1)*nlstate+i2;
                   6050:          if(cptj2 <= cptj)
                   6051:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   6052:        }
                   6053:     }
                   6054:   fprintf(ficrescveij,"\n");
                   6055:   
                   6056:   if(estepm < stepm){
                   6057:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6058:   }
                   6059:   else  hstepm=estepm;   
                   6060:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6061:    * This is mainly to measure the difference between two models: for example
                   6062:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6063:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6064:    * progression in between and thus overestimating or underestimating according
                   6065:    * to the curvature of the survival function. If, for the same date, we 
                   6066:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6067:    * to compare the new estimate of Life expectancy with the same linear 
                   6068:    * hypothesis. A more precise result, taking into account a more precise
                   6069:    * curvature will be obtained if estepm is as small as stepm. */
                   6070: 
                   6071:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6072:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6073:      nhstepm is the number of hstepm from age to agelim 
                   6074:      nstepm is the number of stepm from age to agelin. 
                   6075:      Look at hpijx to understand the reason of that which relies in memory size
                   6076:      and note for a fixed period like estepm months */
                   6077:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6078:      survival function given by stepm (the optimization length). Unfortunately it
                   6079:      means that if the survival funtion is printed only each two years of age and if
                   6080:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6081:      results. So we changed our mind and took the option of the best precision.
                   6082:   */
                   6083:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6084: 
                   6085:   /* If stepm=6 months */
                   6086:   /* nhstepm age range expressed in number of stepm */
                   6087:   agelim=AGESUP;
                   6088:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   6089:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6090:   /* if (stepm >= YEARM) hstepm=1;*/
                   6091:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6092:   
                   6093:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6094:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6095:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   6096:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   6097:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   6098:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   6099: 
                   6100:   for (age=bage; age<=fage; age ++){ 
                   6101:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6102:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6103:     /* if (stepm >= YEARM) hstepm=1;*/
                   6104:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  6105:                
1.126     brouard  6106:     /* If stepm=6 months */
                   6107:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6108:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   6109:     
                   6110:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  6111:                
1.126     brouard  6112:     /* Computing  Variances of health expectancies */
                   6113:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   6114:        decrease memory allocation */
                   6115:     for(theta=1; theta <=npar; theta++){
                   6116:       for(i=1; i<=npar; i++){ 
1.222     brouard  6117:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6118:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  6119:       }
1.235     brouard  6120:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   6121:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  6122:                        
1.126     brouard  6123:       for(j=1; j<= nlstate; j++){
1.222     brouard  6124:        for(i=1; i<=nlstate; i++){
                   6125:          for(h=0; h<=nhstepm-1; h++){
                   6126:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   6127:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   6128:          }
                   6129:        }
1.126     brouard  6130:       }
1.218     brouard  6131:                        
1.126     brouard  6132:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  6133:        for(h=0; h<=nhstepm-1; h++){
                   6134:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   6135:        }
1.126     brouard  6136:     }/* End theta */
                   6137:     
                   6138:     
                   6139:     for(h=0; h<=nhstepm-1; h++)
                   6140:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  6141:        for(theta=1; theta <=npar; theta++)
                   6142:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  6143:     
1.218     brouard  6144:                
1.222     brouard  6145:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  6146:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  6147:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  6148:                
1.222     brouard  6149:     printf("%d|",(int)age);fflush(stdout);
                   6150:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6151:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  6152:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  6153:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   6154:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   6155:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   6156:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   6157:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  6158:       }
                   6159:     }
1.320     brouard  6160:     /* if((int)age ==50){ */
                   6161:     /*   printf(" age=%d cij=%d nres=%d varhe[%d][%d]=%f ",(int)age, cij, nres, 1,2,varhe[1][2]); */
                   6162:     /* } */
1.126     brouard  6163:     /* Computing expectancies */
1.235     brouard  6164:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  6165:     for(i=1; i<=nlstate;i++)
                   6166:       for(j=1; j<=nlstate;j++)
1.222     brouard  6167:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6168:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  6169:                                        
1.222     brouard  6170:          /* 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  6171:                                        
1.222     brouard  6172:        }
1.269     brouard  6173: 
                   6174:     /* Standard deviation of expectancies ij */                
1.126     brouard  6175:     fprintf(ficresstdeij,"%3.0f",age );
                   6176:     for(i=1; i<=nlstate;i++){
                   6177:       eip=0.;
                   6178:       vip=0.;
                   6179:       for(j=1; j<=nlstate;j++){
1.222     brouard  6180:        eip += eij[i][j][(int)age];
                   6181:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   6182:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   6183:        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  6184:       }
                   6185:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   6186:     }
                   6187:     fprintf(ficresstdeij,"\n");
1.218     brouard  6188:                
1.269     brouard  6189:     /* Variance of expectancies ij */          
1.126     brouard  6190:     fprintf(ficrescveij,"%3.0f",age );
                   6191:     for(i=1; i<=nlstate;i++)
                   6192:       for(j=1; j<=nlstate;j++){
1.222     brouard  6193:        cptj= (j-1)*nlstate+i;
                   6194:        for(i2=1; i2<=nlstate;i2++)
                   6195:          for(j2=1; j2<=nlstate;j2++){
                   6196:            cptj2= (j2-1)*nlstate+i2;
                   6197:            if(cptj2 <= cptj)
                   6198:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   6199:          }
1.126     brouard  6200:       }
                   6201:     fprintf(ficrescveij,"\n");
1.218     brouard  6202:                
1.126     brouard  6203:   }
                   6204:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   6205:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   6206:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   6207:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   6208:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6209:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6210:   printf("\n");
                   6211:   fprintf(ficlog,"\n");
1.218     brouard  6212:        
1.126     brouard  6213:   free_vector(xm,1,npar);
                   6214:   free_vector(xp,1,npar);
                   6215:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   6216:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   6217:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   6218: }
1.218     brouard  6219:  
1.126     brouard  6220: /************ Variance ******************/
1.235     brouard  6221:  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  6222:  {
1.279     brouard  6223:    /** Variance of health expectancies 
                   6224:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   6225:     * double **newm;
                   6226:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   6227:     */
1.218     brouard  6228:   
                   6229:    /* int movingaverage(); */
                   6230:    double **dnewm,**doldm;
                   6231:    double **dnewmp,**doldmp;
                   6232:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  6233:    int first=0;
1.218     brouard  6234:    int k;
                   6235:    double *xp;
1.279     brouard  6236:    double **gp, **gm;  /**< for var eij */
                   6237:    double ***gradg, ***trgradg; /**< for var eij */
                   6238:    double **gradgp, **trgradgp; /**< for var p point j */
                   6239:    double *gpp, *gmp; /**< for var p point j */
                   6240:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
1.218     brouard  6241:    double ***p3mat;
                   6242:    double age,agelim, hf;
                   6243:    /* double ***mobaverage; */
                   6244:    int theta;
                   6245:    char digit[4];
                   6246:    char digitp[25];
                   6247: 
                   6248:    char fileresprobmorprev[FILENAMELENGTH];
                   6249: 
                   6250:    if(popbased==1){
                   6251:      if(mobilav!=0)
                   6252:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   6253:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   6254:    }
                   6255:    else 
                   6256:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  6257: 
1.218     brouard  6258:    /* if (mobilav!=0) { */
                   6259:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6260:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   6261:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   6262:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   6263:    /*   } */
                   6264:    /* } */
                   6265: 
                   6266:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   6267:    sprintf(digit,"%-d",ij);
                   6268:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   6269:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   6270:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   6271:    strcat(fileresprobmorprev,fileresu);
                   6272:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   6273:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   6274:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   6275:    }
                   6276:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6277:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6278:    pstamp(ficresprobmorprev);
                   6279:    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  6280:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
                   6281:    for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   6282:      fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   6283:    }
                   6284:    for(j=1;j<=cptcoveff;j++) 
                   6285:      fprintf(ficresprobmorprev,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,j)]);
                   6286:    fprintf(ficresprobmorprev,"\n");
                   6287: 
1.218     brouard  6288:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   6289:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6290:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   6291:      for(i=1; i<=nlstate;i++)
                   6292:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   6293:    }  
                   6294:    fprintf(ficresprobmorprev,"\n");
                   6295:   
                   6296:    fprintf(ficgp,"\n# Routine varevsij");
                   6297:    fprintf(ficgp,"\nunset title \n");
                   6298:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   6299:    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");
                   6300:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  6301: 
1.218     brouard  6302:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6303:    pstamp(ficresvij);
                   6304:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   6305:    if(popbased==1)
                   6306:      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);
                   6307:    else
                   6308:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   6309:    fprintf(ficresvij,"# Age");
                   6310:    for(i=1; i<=nlstate;i++)
                   6311:      for(j=1; j<=nlstate;j++)
                   6312:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   6313:    fprintf(ficresvij,"\n");
                   6314: 
                   6315:    xp=vector(1,npar);
                   6316:    dnewm=matrix(1,nlstate,1,npar);
                   6317:    doldm=matrix(1,nlstate,1,nlstate);
                   6318:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   6319:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6320: 
                   6321:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   6322:    gpp=vector(nlstate+1,nlstate+ndeath);
                   6323:    gmp=vector(nlstate+1,nlstate+ndeath);
                   6324:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  6325:   
1.218     brouard  6326:    if(estepm < stepm){
                   6327:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   6328:    }
                   6329:    else  hstepm=estepm;   
                   6330:    /* For example we decided to compute the life expectancy with the smallest unit */
                   6331:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6332:       nhstepm is the number of hstepm from age to agelim 
                   6333:       nstepm is the number of stepm from age to agelim. 
                   6334:       Look at function hpijx to understand why because of memory size limitations, 
                   6335:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   6336:       survival function given by stepm (the optimization length). Unfortunately it
                   6337:       means that if the survival funtion is printed every two years of age and if
                   6338:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6339:       results. So we changed our mind and took the option of the best precision.
                   6340:    */
                   6341:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6342:    agelim = AGESUP;
                   6343:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6344:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6345:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6346:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6347:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   6348:      gp=matrix(0,nhstepm,1,nlstate);
                   6349:      gm=matrix(0,nhstepm,1,nlstate);
                   6350:                
                   6351:                
                   6352:      for(theta=1; theta <=npar; theta++){
                   6353:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   6354:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6355:        }
1.279     brouard  6356:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   6357:        * returns into prlim .
1.288     brouard  6358:        */
1.242     brouard  6359:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  6360: 
                   6361:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  6362:        if (popbased==1) {
                   6363:         if(mobilav ==0){
                   6364:           for(i=1; i<=nlstate;i++)
                   6365:             prlim[i][i]=probs[(int)age][i][ij];
                   6366:         }else{ /* mobilav */ 
                   6367:           for(i=1; i<=nlstate;i++)
                   6368:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6369:         }
                   6370:        }
1.295     brouard  6371:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  6372:        */                      
                   6373:        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  6374:        /**< 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  6375:        * at horizon h in state j including mortality.
                   6376:        */
1.218     brouard  6377:        for(j=1; j<= nlstate; j++){
                   6378:         for(h=0; h<=nhstepm; h++){
                   6379:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   6380:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6381:         }
                   6382:        }
1.279     brouard  6383:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  6384:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  6385:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  6386:        */
                   6387:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6388:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   6389:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  6390:        }
                   6391:        
                   6392:        /* Again with minus shift */
1.218     brouard  6393:                        
                   6394:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   6395:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6396: 
1.242     brouard  6397:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  6398:                        
                   6399:        if (popbased==1) {
                   6400:         if(mobilav ==0){
                   6401:           for(i=1; i<=nlstate;i++)
                   6402:             prlim[i][i]=probs[(int)age][i][ij];
                   6403:         }else{ /* mobilav */ 
                   6404:           for(i=1; i<=nlstate;i++)
                   6405:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6406:         }
                   6407:        }
                   6408:                        
1.235     brouard  6409:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  6410:                        
                   6411:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   6412:         for(h=0; h<=nhstepm; h++){
                   6413:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   6414:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6415:         }
                   6416:        }
                   6417:        /* This for computing probability of death (h=1 means
                   6418:          computed over hstepm matrices product = hstepm*stepm months) 
                   6419:          as a weighted average of prlim.
                   6420:        */
                   6421:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6422:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   6423:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   6424:        }    
1.279     brouard  6425:        /* end shifting computations */
                   6426: 
                   6427:        /**< Computing gradient matrix at horizon h 
                   6428:        */
1.218     brouard  6429:        for(j=1; j<= nlstate; j++) /* vareij */
                   6430:         for(h=0; h<=nhstepm; h++){
                   6431:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   6432:         }
1.279     brouard  6433:        /**< Gradient of overall mortality p.3 (or p.j) 
                   6434:        */
                   6435:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
1.218     brouard  6436:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   6437:        }
                   6438:                        
                   6439:      } /* End theta */
1.279     brouard  6440:      
                   6441:      /* We got the gradient matrix for each theta and state j */               
1.218     brouard  6442:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   6443:                
                   6444:      for(h=0; h<=nhstepm; h++) /* veij */
                   6445:        for(j=1; j<=nlstate;j++)
                   6446:         for(theta=1; theta <=npar; theta++)
                   6447:           trgradg[h][j][theta]=gradg[h][theta][j];
                   6448:                
                   6449:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   6450:        for(theta=1; theta <=npar; theta++)
                   6451:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  6452:      /**< as well as its transposed matrix 
                   6453:       */               
1.218     brouard  6454:                
                   6455:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6456:      for(i=1;i<=nlstate;i++)
                   6457:        for(j=1;j<=nlstate;j++)
                   6458:         vareij[i][j][(int)age] =0.;
1.279     brouard  6459: 
                   6460:      /* Computing trgradg by matcov by gradg at age and summing over h
                   6461:       * and k (nhstepm) formula 15 of article
                   6462:       * Lievre-Brouard-Heathcote
                   6463:       */
                   6464:      
1.218     brouard  6465:      for(h=0;h<=nhstepm;h++){
                   6466:        for(k=0;k<=nhstepm;k++){
                   6467:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   6468:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   6469:         for(i=1;i<=nlstate;i++)
                   6470:           for(j=1;j<=nlstate;j++)
                   6471:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   6472:        }
                   6473:      }
                   6474:                
1.279     brouard  6475:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
                   6476:       * p.j overall mortality formula 49 but computed directly because
                   6477:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   6478:       * wix is independent of theta.
                   6479:       */
1.218     brouard  6480:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   6481:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   6482:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   6483:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   6484:         varppt[j][i]=doldmp[j][i];
                   6485:      /* end ppptj */
                   6486:      /*  x centered again */
                   6487:                
1.242     brouard  6488:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  6489:                
                   6490:      if (popbased==1) {
                   6491:        if(mobilav ==0){
                   6492:         for(i=1; i<=nlstate;i++)
                   6493:           prlim[i][i]=probs[(int)age][i][ij];
                   6494:        }else{ /* mobilav */ 
                   6495:         for(i=1; i<=nlstate;i++)
                   6496:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   6497:        }
                   6498:      }
                   6499:                
                   6500:      /* This for computing probability of death (h=1 means
                   6501:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   6502:        as a weighted average of prlim.
                   6503:      */
1.235     brouard  6504:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  6505:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6506:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   6507:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   6508:      }    
                   6509:      /* end probability of death */
                   6510:                
                   6511:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   6512:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6513:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   6514:        for(i=1; i<=nlstate;i++){
                   6515:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   6516:        }
                   6517:      } 
                   6518:      fprintf(ficresprobmorprev,"\n");
                   6519:                
                   6520:      fprintf(ficresvij,"%.0f ",age );
                   6521:      for(i=1; i<=nlstate;i++)
                   6522:        for(j=1; j<=nlstate;j++){
                   6523:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   6524:        }
                   6525:      fprintf(ficresvij,"\n");
                   6526:      free_matrix(gp,0,nhstepm,1,nlstate);
                   6527:      free_matrix(gm,0,nhstepm,1,nlstate);
                   6528:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   6529:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   6530:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6531:    } /* End age */
                   6532:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   6533:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   6534:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   6535:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   6536:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   6537:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   6538:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   6539:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   6540:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   6541:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   6542:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6543:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6544:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   6545:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   6546:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   6547:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   6548:    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);
                   6549:    /*  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  6550:     */
1.218     brouard  6551:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   6552:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  6553: 
1.218     brouard  6554:    free_vector(xp,1,npar);
                   6555:    free_matrix(doldm,1,nlstate,1,nlstate);
                   6556:    free_matrix(dnewm,1,nlstate,1,npar);
                   6557:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6558:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   6559:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6560:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6561:    fclose(ficresprobmorprev);
                   6562:    fflush(ficgp);
                   6563:    fflush(fichtm); 
                   6564:  }  /* end varevsij */
1.126     brouard  6565: 
                   6566: /************ Variance of prevlim ******************/
1.269     brouard  6567:  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  6568: {
1.205     brouard  6569:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  6570:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  6571: 
1.268     brouard  6572:   double **dnewmpar,**doldm;
1.126     brouard  6573:   int i, j, nhstepm, hstepm;
                   6574:   double *xp;
                   6575:   double *gp, *gm;
                   6576:   double **gradg, **trgradg;
1.208     brouard  6577:   double **mgm, **mgp;
1.126     brouard  6578:   double age,agelim;
                   6579:   int theta;
                   6580:   
                   6581:   pstamp(ficresvpl);
1.288     brouard  6582:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  6583:   fprintf(ficresvpl,"# Age ");
                   6584:   if(nresult >=1)
                   6585:     fprintf(ficresvpl," Result# ");
1.126     brouard  6586:   for(i=1; i<=nlstate;i++)
                   6587:       fprintf(ficresvpl," %1d-%1d",i,i);
                   6588:   fprintf(ficresvpl,"\n");
                   6589: 
                   6590:   xp=vector(1,npar);
1.268     brouard  6591:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  6592:   doldm=matrix(1,nlstate,1,nlstate);
                   6593:   
                   6594:   hstepm=1*YEARM; /* Every year of age */
                   6595:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   6596:   agelim = AGESUP;
                   6597:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6598:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6599:     if (stepm >= YEARM) hstepm=1;
                   6600:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6601:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  6602:     mgp=matrix(1,npar,1,nlstate);
                   6603:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  6604:     gp=vector(1,nlstate);
                   6605:     gm=vector(1,nlstate);
                   6606: 
                   6607:     for(theta=1; theta <=npar; theta++){
                   6608:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   6609:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6610:       }
1.288     brouard  6611:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6612:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6613:       /* else */
                   6614:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6615:       for(i=1;i<=nlstate;i++){
1.126     brouard  6616:        gp[i] = prlim[i][i];
1.208     brouard  6617:        mgp[theta][i] = prlim[i][i];
                   6618:       }
1.126     brouard  6619:       for(i=1; i<=npar; i++) /* Computes gradient */
                   6620:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6621:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6622:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6623:       /* else */
                   6624:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6625:       for(i=1;i<=nlstate;i++){
1.126     brouard  6626:        gm[i] = prlim[i][i];
1.208     brouard  6627:        mgm[theta][i] = prlim[i][i];
                   6628:       }
1.126     brouard  6629:       for(i=1;i<=nlstate;i++)
                   6630:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  6631:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  6632:     } /* End theta */
                   6633: 
                   6634:     trgradg =matrix(1,nlstate,1,npar);
                   6635: 
                   6636:     for(j=1; j<=nlstate;j++)
                   6637:       for(theta=1; theta <=npar; theta++)
                   6638:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  6639:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6640:     /*   printf("\nmgm mgp %d ",(int)age); */
                   6641:     /*   for(j=1; j<=nlstate;j++){ */
                   6642:     /*         printf(" %d ",j); */
                   6643:     /*         for(theta=1; theta <=npar; theta++) */
                   6644:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   6645:     /*         printf("\n "); */
                   6646:     /*   } */
                   6647:     /* } */
                   6648:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6649:     /*   printf("\n gradg %d ",(int)age); */
                   6650:     /*   for(j=1; j<=nlstate;j++){ */
                   6651:     /*         printf("%d ",j); */
                   6652:     /*         for(theta=1; theta <=npar; theta++) */
                   6653:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   6654:     /*         printf("\n "); */
                   6655:     /*   } */
                   6656:     /* } */
1.126     brouard  6657: 
                   6658:     for(i=1;i<=nlstate;i++)
                   6659:       varpl[i][(int)age] =0.;
1.209     brouard  6660:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  6661:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6662:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6663:     }else{
1.268     brouard  6664:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6665:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6666:     }
1.126     brouard  6667:     for(i=1;i<=nlstate;i++)
                   6668:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   6669: 
                   6670:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  6671:     if(nresult >=1)
                   6672:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  6673:     for(i=1; i<=nlstate;i++){
1.126     brouard  6674:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  6675:       /* for(j=1;j<=nlstate;j++) */
                   6676:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   6677:     }
1.126     brouard  6678:     fprintf(ficresvpl,"\n");
                   6679:     free_vector(gp,1,nlstate);
                   6680:     free_vector(gm,1,nlstate);
1.208     brouard  6681:     free_matrix(mgm,1,npar,1,nlstate);
                   6682:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  6683:     free_matrix(gradg,1,npar,1,nlstate);
                   6684:     free_matrix(trgradg,1,nlstate,1,npar);
                   6685:   } /* End age */
                   6686: 
                   6687:   free_vector(xp,1,npar);
                   6688:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  6689:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   6690: 
                   6691: }
                   6692: 
                   6693: 
                   6694: /************ Variance of backprevalence limit ******************/
1.269     brouard  6695:  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  6696: {
                   6697:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   6698:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   6699: 
                   6700:   double **dnewmpar,**doldm;
                   6701:   int i, j, nhstepm, hstepm;
                   6702:   double *xp;
                   6703:   double *gp, *gm;
                   6704:   double **gradg, **trgradg;
                   6705:   double **mgm, **mgp;
                   6706:   double age,agelim;
                   6707:   int theta;
                   6708:   
                   6709:   pstamp(ficresvbl);
                   6710:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   6711:   fprintf(ficresvbl,"# Age ");
                   6712:   if(nresult >=1)
                   6713:     fprintf(ficresvbl," Result# ");
                   6714:   for(i=1; i<=nlstate;i++)
                   6715:       fprintf(ficresvbl," %1d-%1d",i,i);
                   6716:   fprintf(ficresvbl,"\n");
                   6717: 
                   6718:   xp=vector(1,npar);
                   6719:   dnewmpar=matrix(1,nlstate,1,npar);
                   6720:   doldm=matrix(1,nlstate,1,nlstate);
                   6721:   
                   6722:   hstepm=1*YEARM; /* Every year of age */
                   6723:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   6724:   agelim = AGEINF;
                   6725:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   6726:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6727:     if (stepm >= YEARM) hstepm=1;
                   6728:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6729:     gradg=matrix(1,npar,1,nlstate);
                   6730:     mgp=matrix(1,npar,1,nlstate);
                   6731:     mgm=matrix(1,npar,1,nlstate);
                   6732:     gp=vector(1,nlstate);
                   6733:     gm=vector(1,nlstate);
                   6734: 
                   6735:     for(theta=1; theta <=npar; theta++){
                   6736:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   6737:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6738:       }
                   6739:       if(mobilavproj > 0 )
                   6740:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6741:       else
                   6742:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6743:       for(i=1;i<=nlstate;i++){
                   6744:        gp[i] = bprlim[i][i];
                   6745:        mgp[theta][i] = bprlim[i][i];
                   6746:       }
                   6747:      for(i=1; i<=npar; i++) /* Computes gradient */
                   6748:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   6749:        if(mobilavproj > 0 )
                   6750:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6751:        else
                   6752:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6753:       for(i=1;i<=nlstate;i++){
                   6754:        gm[i] = bprlim[i][i];
                   6755:        mgm[theta][i] = bprlim[i][i];
                   6756:       }
                   6757:       for(i=1;i<=nlstate;i++)
                   6758:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   6759:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   6760:     } /* End theta */
                   6761: 
                   6762:     trgradg =matrix(1,nlstate,1,npar);
                   6763: 
                   6764:     for(j=1; j<=nlstate;j++)
                   6765:       for(theta=1; theta <=npar; theta++)
                   6766:        trgradg[j][theta]=gradg[theta][j];
                   6767:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6768:     /*   printf("\nmgm mgp %d ",(int)age); */
                   6769:     /*   for(j=1; j<=nlstate;j++){ */
                   6770:     /*         printf(" %d ",j); */
                   6771:     /*         for(theta=1; theta <=npar; theta++) */
                   6772:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   6773:     /*         printf("\n "); */
                   6774:     /*   } */
                   6775:     /* } */
                   6776:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6777:     /*   printf("\n gradg %d ",(int)age); */
                   6778:     /*   for(j=1; j<=nlstate;j++){ */
                   6779:     /*         printf("%d ",j); */
                   6780:     /*         for(theta=1; theta <=npar; theta++) */
                   6781:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   6782:     /*         printf("\n "); */
                   6783:     /*   } */
                   6784:     /* } */
                   6785: 
                   6786:     for(i=1;i<=nlstate;i++)
                   6787:       varbpl[i][(int)age] =0.;
                   6788:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   6789:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6790:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   6791:     }else{
                   6792:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6793:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   6794:     }
                   6795:     for(i=1;i<=nlstate;i++)
                   6796:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   6797: 
                   6798:     fprintf(ficresvbl,"%.0f ",age );
                   6799:     if(nresult >=1)
                   6800:       fprintf(ficresvbl,"%d ",nres );
                   6801:     for(i=1; i<=nlstate;i++)
                   6802:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   6803:     fprintf(ficresvbl,"\n");
                   6804:     free_vector(gp,1,nlstate);
                   6805:     free_vector(gm,1,nlstate);
                   6806:     free_matrix(mgm,1,npar,1,nlstate);
                   6807:     free_matrix(mgp,1,npar,1,nlstate);
                   6808:     free_matrix(gradg,1,npar,1,nlstate);
                   6809:     free_matrix(trgradg,1,nlstate,1,npar);
                   6810:   } /* End age */
                   6811: 
                   6812:   free_vector(xp,1,npar);
                   6813:   free_matrix(doldm,1,nlstate,1,npar);
                   6814:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  6815: 
                   6816: }
                   6817: 
                   6818: /************ Variance of one-step probabilities  ******************/
                   6819: 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  6820:  {
                   6821:    int i, j=0,  k1, l1, tj;
                   6822:    int k2, l2, j1,  z1;
                   6823:    int k=0, l;
                   6824:    int first=1, first1, first2;
1.326     brouard  6825:    int nres=0; /* New */
1.222     brouard  6826:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   6827:    double **dnewm,**doldm;
                   6828:    double *xp;
                   6829:    double *gp, *gm;
                   6830:    double **gradg, **trgradg;
                   6831:    double **mu;
                   6832:    double age, cov[NCOVMAX+1];
                   6833:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   6834:    int theta;
                   6835:    char fileresprob[FILENAMELENGTH];
                   6836:    char fileresprobcov[FILENAMELENGTH];
                   6837:    char fileresprobcor[FILENAMELENGTH];
                   6838:    double ***varpij;
                   6839: 
                   6840:    strcpy(fileresprob,"PROB_"); 
                   6841:    strcat(fileresprob,fileres);
                   6842:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   6843:      printf("Problem with resultfile: %s\n", fileresprob);
                   6844:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   6845:    }
                   6846:    strcpy(fileresprobcov,"PROBCOV_"); 
                   6847:    strcat(fileresprobcov,fileresu);
                   6848:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   6849:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   6850:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   6851:    }
                   6852:    strcpy(fileresprobcor,"PROBCOR_"); 
                   6853:    strcat(fileresprobcor,fileresu);
                   6854:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   6855:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   6856:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   6857:    }
                   6858:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   6859:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   6860:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   6861:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   6862:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   6863:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   6864:    pstamp(ficresprob);
                   6865:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   6866:    fprintf(ficresprob,"# Age");
                   6867:    pstamp(ficresprobcov);
                   6868:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   6869:    fprintf(ficresprobcov,"# Age");
                   6870:    pstamp(ficresprobcor);
                   6871:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   6872:    fprintf(ficresprobcor,"# Age");
1.126     brouard  6873: 
                   6874: 
1.222     brouard  6875:    for(i=1; i<=nlstate;i++)
                   6876:      for(j=1; j<=(nlstate+ndeath);j++){
                   6877:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   6878:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   6879:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   6880:      }  
                   6881:    /* fprintf(ficresprob,"\n");
                   6882:       fprintf(ficresprobcov,"\n");
                   6883:       fprintf(ficresprobcor,"\n");
                   6884:    */
                   6885:    xp=vector(1,npar);
                   6886:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   6887:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   6888:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   6889:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   6890:    first=1;
                   6891:    fprintf(ficgp,"\n# Routine varprob");
                   6892:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   6893:    fprintf(fichtm,"\n");
                   6894: 
1.288     brouard  6895:    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  6896:    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);
                   6897:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  6898: and drawn. It helps understanding how is the covariance between two incidences.\
                   6899:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  6900:    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  6901: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   6902: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   6903: standard deviations wide on each axis. <br>\
                   6904:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   6905:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   6906: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   6907: 
1.222     brouard  6908:    cov[1]=1;
                   6909:    /* tj=cptcoveff; */
1.225     brouard  6910:    tj = (int) pow(2,cptcoveff);
1.222     brouard  6911:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   6912:    j1=0;
1.224     brouard  6913:    for(j1=1; j1<=tj;j1++){  /* For each valid combination of covariates or only once*/
1.326     brouard  6914:      for(nres=1;nres <=1; nres++){ /* For each resultline */
                   6915:      /* for(nres=1;nres <=nresult; nres++){ /\* For each resultline *\/ */
1.222     brouard  6916:      if  (cptcovn>0) {
                   6917:        fprintf(ficresprob, "\n#********** Variable "); 
1.225     brouard  6918:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6919:        fprintf(ficresprob, "**********\n#\n");
                   6920:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.225     brouard  6921:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6922:        fprintf(ficresprobcov, "**********\n#\n");
1.220     brouard  6923:                        
1.222     brouard  6924:        fprintf(ficgp, "\n#********** Variable "); 
1.225     brouard  6925:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6926:        fprintf(ficgp, "**********\n#\n");
1.220     brouard  6927:                        
                   6928:                        
1.222     brouard  6929:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.319     brouard  6930:        /* for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]); */
                   6931:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtmcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6932:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  6933:                        
1.222     brouard  6934:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.225     brouard  6935:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6936:        fprintf(ficresprobcor, "**********\n#");    
                   6937:        if(invalidvarcomb[j1]){
                   6938:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   6939:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   6940:         continue;
                   6941:        }
                   6942:      }
                   6943:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   6944:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   6945:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   6946:      gm=vector(1,(nlstate)*(nlstate+ndeath));
                   6947:      for (age=bage; age<=fage; age ++){ 
                   6948:        cov[2]=age;
                   6949:        if(nagesqr==1)
                   6950:         cov[3]= age*age;
1.326     brouard  6951:        /* for (k=1; k<=cptcovn;k++) { */
                   6952:        /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)]; */
                   6953:        for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   6954:         /* Here comes the value of the covariate 'j1' after renumbering k with single dummy covariates */
                   6955:         cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(j1,k)];
1.222     brouard  6956:         /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
                   6957:                                                                    * 1  1 1 1 1
                   6958:                                                                    * 2  2 1 1 1
                   6959:                                                                    * 3  1 2 1 1
                   6960:                                                                    */
                   6961:         /* nbcode[1][1]=0 nbcode[1][2]=1;*/
                   6962:        }
1.319     brouard  6963:        /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   6964:        /* ) p nbcode[Tvar[Tage[k]]][(1 & (ij-1) >> (k-1))+1] */
                   6965:        /*for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.326     brouard  6966:        for (k=1; k<=cptcovage;k++){  /* For product with age */
                   6967:         if(Dummy[Tage[k]]==2){ /* dummy with age */
                   6968:           cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(j1,k)]*cov[2];
                   6969:           /* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   6970:         } else if(Dummy[Tage[k]]==3){ /* quantitative with age */
1.327   ! brouard  6971:           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]);
        !          6972:           exit(1);
        !          6973:             /* cov[2+nagesqr+Tage[k]]=meanq[k]/idq[k]*cov[2];/\* Using the mean of quantitative variable Tvar[Tage[k]] /\* Tqresult[nres][k]; *\/ */
1.326     brouard  6974:           /* cov[++k1]=Tqresult[nres][k];  */
                   6975:         }
                   6976:         /* cov[2+Tage[k]+nagesqr]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   6977:        }
                   6978:        for (k=1; k<=cptcovprod;k++){/* For product without age */
                   6979:         if(Dummy[Tvard[k][1]==0]){
                   6980:           if(Dummy[Tvard[k][2]==0]){
                   6981:             cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,k)] * nbcode[Tvard[k][2]][codtabm(j1,k)];
                   6982:             /* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; */
                   6983:           }else{ /* Should we use the mean of the quantitative variables? */
                   6984:             cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,k)] * Tqresult[nres][k];
                   6985:             /* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; */
                   6986:           }
                   6987:         }else{
                   6988:           if(Dummy[Tvard[k][2]==0]){
                   6989:             cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(j1,k)] * Tqinvresult[nres][Tvard[k][1]];
                   6990:             /* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; */
                   6991:           }else{
                   6992:             cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   6993:             /* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   6994:           }
                   6995:         }
                   6996:         /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
                   6997:        }                       
                   6998: /* For each age and combination of dummy covariates we slightly move the parameters of delti in order to get the gradient*/                    
1.222     brouard  6999:        for(theta=1; theta <=npar; theta++){
                   7000:         for(i=1; i<=npar; i++)
                   7001:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  7002:                                
1.222     brouard  7003:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  7004:                                
1.222     brouard  7005:         k=0;
                   7006:         for(i=1; i<= (nlstate); i++){
                   7007:           for(j=1; j<=(nlstate+ndeath);j++){
                   7008:             k=k+1;
                   7009:             gp[k]=pmmij[i][j];
                   7010:           }
                   7011:         }
1.220     brouard  7012:                                
1.222     brouard  7013:         for(i=1; i<=npar; i++)
                   7014:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  7015:                                
1.222     brouard  7016:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   7017:         k=0;
                   7018:         for(i=1; i<=(nlstate); i++){
                   7019:           for(j=1; j<=(nlstate+ndeath);j++){
                   7020:             k=k+1;
                   7021:             gm[k]=pmmij[i][j];
                   7022:           }
                   7023:         }
1.220     brouard  7024:                                
1.222     brouard  7025:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   7026:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   7027:        }
1.126     brouard  7028: 
1.222     brouard  7029:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   7030:         for(theta=1; theta <=npar; theta++)
                   7031:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  7032:                        
1.222     brouard  7033:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   7034:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  7035:                        
1.222     brouard  7036:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  7037:                        
1.222     brouard  7038:        k=0;
                   7039:        for(i=1; i<=(nlstate); i++){
                   7040:         for(j=1; j<=(nlstate+ndeath);j++){
                   7041:           k=k+1;
                   7042:           mu[k][(int) age]=pmmij[i][j];
                   7043:         }
                   7044:        }
                   7045:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   7046:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   7047:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  7048:                        
1.222     brouard  7049:        /*printf("\n%d ",(int)age);
                   7050:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7051:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7052:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7053:         }*/
1.220     brouard  7054:                        
1.222     brouard  7055:        fprintf(ficresprob,"\n%d ",(int)age);
                   7056:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   7057:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  7058:                        
1.222     brouard  7059:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   7060:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   7061:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7062:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   7063:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   7064:        }
                   7065:        i=0;
                   7066:        for (k=1; k<=(nlstate);k++){
                   7067:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   7068:           i++;
                   7069:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   7070:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   7071:           for (j=1; j<=i;j++){
                   7072:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   7073:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   7074:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   7075:           }
                   7076:         }
                   7077:        }/* end of loop for state */
                   7078:      } /* end of loop for age */
                   7079:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7080:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7081:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7082:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7083:     
                   7084:      /* Confidence intervalle of pij  */
                   7085:      /*
                   7086:        fprintf(ficgp,"\nunset parametric;unset label");
                   7087:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   7088:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   7089:        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);
                   7090:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   7091:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   7092:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   7093:      */
                   7094:                
                   7095:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   7096:      first1=1;first2=2;
                   7097:      for (k2=1; k2<=(nlstate);k2++){
                   7098:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   7099:         if(l2==k2) continue;
                   7100:         j=(k2-1)*(nlstate+ndeath)+l2;
                   7101:         for (k1=1; k1<=(nlstate);k1++){
                   7102:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   7103:             if(l1==k1) continue;
                   7104:             i=(k1-1)*(nlstate+ndeath)+l1;
                   7105:             if(i<=j) continue;
                   7106:             for (age=bage; age<=fage; age ++){ 
                   7107:               if ((int)age %5==0){
                   7108:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   7109:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7110:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7111:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   7112:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   7113:                 c12=cv12/sqrt(v1*v2);
                   7114:                 /* Computing eigen value of matrix of covariance */
                   7115:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7116:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7117:                 if ((lc2 <0) || (lc1 <0) ){
                   7118:                   if(first2==1){
                   7119:                     first1=0;
                   7120:                     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);
                   7121:                   }
                   7122:                   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);
                   7123:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   7124:                   /* lc2=fabs(lc2); */
                   7125:                 }
1.220     brouard  7126:                                                                
1.222     brouard  7127:                 /* Eigen vectors */
1.280     brouard  7128:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   7129:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7130:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7131:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   7132:                 }else
                   7133:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  7134:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   7135:                 v21=(lc1-v1)/cv12*v11;
                   7136:                 v12=-v21;
                   7137:                 v22=v11;
                   7138:                 tnalp=v21/v11;
                   7139:                 if(first1==1){
                   7140:                   first1=0;
                   7141:                   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);
                   7142:                 }
                   7143:                 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);
                   7144:                 /*printf(fignu*/
                   7145:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   7146:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   7147:                 if(first==1){
                   7148:                   first=0;
                   7149:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   7150:                   fprintf(ficgp,"\nset parametric;unset label");
                   7151:                   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);
                   7152:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  7153:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  7154:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  7155: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  7156:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   7157:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7158:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7159:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   7160:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7161:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7162:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7163:                   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  7164:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   7165:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  7166:                 }else{
                   7167:                   first=0;
                   7168:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   7169:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7170:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7171:                   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  7172:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   7173:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  7174:                 }/* if first */
                   7175:               } /* age mod 5 */
                   7176:             } /* end loop age */
                   7177:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7178:             first=1;
                   7179:           } /*l12 */
                   7180:         } /* k12 */
                   7181:        } /*l1 */
                   7182:      }/* k1 */
1.326     brouard  7183:    } /* loop on nres */
1.222     brouard  7184:    }  /* loop on combination of covariates j1 */
                   7185:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   7186:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   7187:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7188:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   7189:    free_vector(xp,1,npar);
                   7190:    fclose(ficresprob);
                   7191:    fclose(ficresprobcov);
                   7192:    fclose(ficresprobcor);
                   7193:    fflush(ficgp);
                   7194:    fflush(fichtmcov);
                   7195:  }
1.126     brouard  7196: 
                   7197: 
                   7198: /******************* Printing html file ***********/
1.201     brouard  7199: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  7200:                  int lastpass, int stepm, int weightopt, char model[],\
                   7201:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  7202:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   7203:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   7204:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.237     brouard  7205:   int jj1, k1, i1, cpt, k4, nres;
1.319     brouard  7206:   /* In fact some results are already printed in fichtm which is open */
1.126     brouard  7207:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   7208:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   7209: </ul>");
1.319     brouard  7210: /*    fprintf(fichtm,"<ul><li> model=1+age+%s\n \ */
                   7211: /* </ul>", model); */
1.214     brouard  7212:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   7213:    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",
                   7214:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
                   7215:    fprintf(fichtm,"<li> - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> (html file) ",
1.213     brouard  7216:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   7217:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  7218:    fprintf(fichtm,"\
                   7219:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  7220:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  7221:    fprintf(fichtm,"\
1.217     brouard  7222:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   7223:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   7224:    fprintf(fichtm,"\
1.288     brouard  7225:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7226:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  7227:    fprintf(fichtm,"\
1.288     brouard  7228:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  7229:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   7230:    fprintf(fichtm,"\
1.211     brouard  7231:  - (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  7232:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7233:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  7234:    if(prevfcast==1){
                   7235:      fprintf(fichtm,"\
                   7236:  - Prevalence projections by age and states:                           \
1.201     brouard  7237:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  7238:    }
1.126     brouard  7239: 
                   7240: 
1.225     brouard  7241:    m=pow(2,cptcoveff);
1.222     brouard  7242:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7243: 
1.317     brouard  7244:    fprintf(fichtm," \n<ul><li><b>Graphs (first order)</b></li><p>");
1.264     brouard  7245: 
                   7246:    jj1=0;
                   7247: 
                   7248:    fprintf(fichtm," \n<ul>");
                   7249:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   7250:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
                   7251:      if(m != 1 && TKresult[nres]!= k1)
                   7252:        continue;
                   7253:      jj1++;
                   7254:      if (cptcovn > 0) {
                   7255:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
                   7256:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7257:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7258:        }
                   7259:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7260:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7261:        }
                   7262:        fprintf(fichtm,"\">");
                   7263:        
                   7264:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   7265:        fprintf(fichtm,"************ Results for covariates");
                   7266:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7267:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7268:        }
                   7269:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7270:         fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7271:        }
                   7272:        if(invalidvarcomb[k1]){
                   7273:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   7274:         continue;
                   7275:        }
                   7276:        fprintf(fichtm,"</a></li>");
                   7277:      } /* cptcovn >0 */
                   7278:    }
1.317     brouard  7279:    fprintf(fichtm," \n</ul>");
1.264     brouard  7280: 
1.222     brouard  7281:    jj1=0;
1.237     brouard  7282: 
                   7283:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.241     brouard  7284:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
1.253     brouard  7285:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7286:        continue;
1.220     brouard  7287: 
1.222     brouard  7288:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7289:      jj1++;
                   7290:      if (cptcovn > 0) {
1.264     brouard  7291:        fprintf(fichtm,"\n<p><a name=\"rescov");
                   7292:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7293:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7294:        }
                   7295:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7296:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7297:        }
                   7298:        fprintf(fichtm,"\"</a>");
                   7299:  
1.222     brouard  7300:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  7301:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.237     brouard  7302:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7303:         printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
                   7304:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   7305:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  7306:        }
1.237     brouard  7307:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7308:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7309:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);fflush(stdout);
                   7310:       }
                   7311:        
1.230     brouard  7312:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.321     brouard  7313:        fprintf(fichtm," (model=%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.222     brouard  7314:        if(invalidvarcomb[k1]){
                   7315:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   7316:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   7317:         continue;
                   7318:        }
                   7319:      }
                   7320:      /* aij, bij */
1.259     brouard  7321:      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  7322: <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  7323:      /* Pij */
1.241     brouard  7324:      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> \
                   7325: <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  7326:      /* Quasi-incidences */
                   7327:      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  7328:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  7329:  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  7330: 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> \
                   7331: <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  7332:      /* Survival functions (period) in state j */
                   7333:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  7334:        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> \
1.241     brouard  7335: <img src=\"%s_%d-%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres,subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres,subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.222     brouard  7336:      }
                   7337:      /* State specific survival functions (period) */
                   7338:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  7339:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
                   7340:  And probability to be observed in various states (up to %d) being in state %d at different ages.      \
1.283     brouard  7341:  <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a><br> <img src=\"%s_%d-%d-%d.svg\">", cpt, nlstate, cpt, subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres,subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres,subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.222     brouard  7342:      }
1.288     brouard  7343:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  7344:      for(cpt=1; cpt<=nlstate;cpt++){
1.264     brouard  7345:        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> \
                   7346: <img src=\"%s_%d-%d-%d.svg\">", cpt, nlstate, cpt, subdirf2(optionfilefiname,"P_"),cpt,k1,nres,subdirf2(optionfilefiname,"P_"),cpt,k1,nres,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.222     brouard  7347:      }
1.296     brouard  7348:      if(prevbcast==1){
1.288     brouard  7349:        /* Backward prevalence in each health state */
1.222     brouard  7350:        for(cpt=1; cpt<=nlstate;cpt++){
1.264     brouard  7351:         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  7352: <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  7353:        }
1.217     brouard  7354:      }
1.222     brouard  7355:      if(prevfcast==1){
1.288     brouard  7356:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  7357:        for(cpt=1; cpt<=nlstate;cpt++){
1.314     brouard  7358:         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);
                   7359:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
                   7360:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
                   7361:                 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  7362:        }
                   7363:      }
1.296     brouard  7364:      if(prevbcast==1){
1.268     brouard  7365:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   7366:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  7367:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
                   7368:  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 \
                   7369:  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  7370: 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);
                   7371:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
                   7372:         fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
1.268     brouard  7373:        }
                   7374:      }
1.220     brouard  7375:         
1.222     brouard  7376:      for(cpt=1; cpt<=nlstate;cpt++) {
1.314     brouard  7377:        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);
                   7378:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
                   7379:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
1.222     brouard  7380:      }
                   7381:      /* } /\* end i1 *\/ */
                   7382:    }/* End k1 */
                   7383:    fprintf(fichtm,"</ul>");
1.126     brouard  7384: 
1.222     brouard  7385:    fprintf(fichtm,"\
1.126     brouard  7386: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  7387:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  7388:  - 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  7389: But because parameters are usually highly correlated (a higher incidence of disability \
                   7390: and a higher incidence of recovery can give very close observed transition) it might \
                   7391: be very useful to look not only at linear confidence intervals estimated from the \
                   7392: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   7393: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   7394: covariance matrix of the one-step probabilities. \
                   7395: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  7396: 
1.222     brouard  7397:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   7398:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   7399:    fprintf(fichtm,"\
1.126     brouard  7400:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7401:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  7402: 
1.222     brouard  7403:    fprintf(fichtm,"\
1.126     brouard  7404:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7405:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   7406:    fprintf(fichtm,"\
1.126     brouard  7407:  - 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): \
                   7408:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7409:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  7410:    fprintf(fichtm,"\
1.126     brouard  7411:  - (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): \
                   7412:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7413:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  7414:    fprintf(fichtm,"\
1.288     brouard  7415:  - 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  7416:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   7417:    fprintf(fichtm,"\
1.128     brouard  7418:  - 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  7419:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   7420:    fprintf(fichtm,"\
1.288     brouard  7421:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  7422:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  7423: 
                   7424: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   7425: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   7426: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   7427: /*     <br>",fileres,fileres,fileres,fileres); */
                   7428: /*  else  */
                   7429: /*    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  7430:    fflush(fichtm);
1.126     brouard  7431: 
1.225     brouard  7432:    m=pow(2,cptcoveff);
1.222     brouard  7433:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7434: 
1.317     brouard  7435:    fprintf(fichtm," <ul><li><b>Graphs (second order)</b></li><p>");
                   7436: 
                   7437:   jj1=0;
                   7438: 
                   7439:    fprintf(fichtm," \n<ul>");
                   7440:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   7441:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
                   7442:      if(m != 1 && TKresult[nres]!= k1)
                   7443:        continue;
                   7444:      jj1++;
                   7445:      if (cptcovn > 0) {
                   7446:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescovsecond");
                   7447:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7448:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7449:        }
                   7450:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7451:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7452:        }
                   7453:        fprintf(fichtm,"\">");
                   7454:        
                   7455:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   7456:        fprintf(fichtm,"************ Results for covariates");
                   7457:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7458:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7459:        }
                   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:        }
                   7463:        if(invalidvarcomb[k1]){
                   7464:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   7465:         continue;
                   7466:        }
                   7467:        fprintf(fichtm,"</a></li>");
                   7468:      } /* cptcovn >0 */
                   7469:    }
                   7470:    fprintf(fichtm," \n</ul>");
                   7471: 
1.222     brouard  7472:    jj1=0;
1.237     brouard  7473: 
1.241     brouard  7474:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.222     brouard  7475:    for(k1=1; k1<=m;k1++){
1.253     brouard  7476:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7477:        continue;
1.222     brouard  7478:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7479:      jj1++;
1.126     brouard  7480:      if (cptcovn > 0) {
1.317     brouard  7481:        fprintf(fichtm,"\n<p><a name=\"rescovsecond");
                   7482:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7483:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7484:        }
                   7485:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7486:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7487:        }
                   7488:        fprintf(fichtm,"\"</a>");
                   7489:        
1.126     brouard  7490:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.317     brouard  7491:        for (cpt=1; cpt<=cptcoveff;cpt++){  /**< cptcoveff number of variables */
1.237     brouard  7492:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);
1.317     brouard  7493:         printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
1.237     brouard  7494:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
1.317     brouard  7495:        }
1.237     brouard  7496:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7497:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7498:       }
                   7499: 
1.321     brouard  7500:        fprintf(fichtm," (model=%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.220     brouard  7501: 
1.222     brouard  7502:        if(invalidvarcomb[k1]){
                   7503:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   7504:         continue;
                   7505:        }
1.126     brouard  7506:      }
                   7507:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  7508:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.314     brouard  7509: 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);
                   7510:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   7511:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
1.126     brouard  7512:      }
                   7513:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.314     brouard  7514: health expectancies in each live states (1 to %d). If popbased=1 the smooth (due to the model) \
1.128     brouard  7515: true period expectancies (those weighted with period prevalences are also\
                   7516:  drawn in addition to the population based expectancies computed using\
1.314     brouard  7517:  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);
                   7518:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
                   7519:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  7520:      /* } /\* end i1 *\/ */
                   7521:    }/* End k1 */
1.241     brouard  7522:   }/* End nres */
1.222     brouard  7523:    fprintf(fichtm,"</ul>");
                   7524:    fflush(fichtm);
1.126     brouard  7525: }
                   7526: 
                   7527: /******************* Gnuplot file **************/
1.296     brouard  7528: 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  7529: 
                   7530:   char dirfileres[132],optfileres[132];
1.264     brouard  7531:   char gplotcondition[132], gplotlabel[132];
1.237     brouard  7532:   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  7533:   int lv=0, vlv=0, kl=0;
1.130     brouard  7534:   int ng=0;
1.201     brouard  7535:   int vpopbased;
1.223     brouard  7536:   int ioffset; /* variable offset for columns */
1.270     brouard  7537:   int iyearc=1; /* variable column for year of projection  */
                   7538:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  7539:   int nres=0; /* Index of resultline */
1.266     brouard  7540:   int istart=1; /* For starting graphs in projections */
1.219     brouard  7541: 
1.126     brouard  7542: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   7543: /*     printf("Problem with file %s",optionfilegnuplot); */
                   7544: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   7545: /*   } */
                   7546: 
                   7547:   /*#ifdef windows */
                   7548:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  7549:   /*#endif */
1.225     brouard  7550:   m=pow(2,cptcoveff);
1.126     brouard  7551: 
1.274     brouard  7552:   /* diagram of the model */
                   7553:   fprintf(ficgp,"\n#Diagram of the model \n");
                   7554:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   7555:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   7556:   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);
                   7557: 
                   7558:   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);
                   7559:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   7560:   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);
                   7561:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   7562:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   7563:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   7564:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   7565: 
1.202     brouard  7566:   /* Contribution to likelihood */
                   7567:   /* Plot the probability implied in the likelihood */
1.223     brouard  7568:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   7569:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   7570:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   7571:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  7572: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  7573:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   7574: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  7575:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   7576:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   7577:   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));
                   7578:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   7579:   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));
                   7580:   for (i=1; i<= nlstate ; i ++) {
                   7581:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   7582:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   7583:     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);
                   7584:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   7585:       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);
                   7586:     }
                   7587:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   7588:   }
                   7589:   /* 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 */               
                   7590:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   7591:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   7592:   fprintf(ficgp,"\nset out;unset log\n");
                   7593:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  7594: 
1.126     brouard  7595:   strcpy(dirfileres,optionfilefiname);
                   7596:   strcpy(optfileres,"vpl");
1.223     brouard  7597:   /* 1eme*/
1.238     brouard  7598:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
                   7599:     for (k1=1; k1<= m ; k1 ++){ /* For each valid combination of covariate */
1.236     brouard  7600:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.238     brouard  7601:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.253     brouard  7602:        if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7603:          continue;
                   7604:        /* We are interested in selected combination by the resultline */
1.246     brouard  7605:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  7606:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  7607:        strcpy(gplotlabel,"(");
1.238     brouard  7608:        for (k=1; k<=cptcoveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   7609:          lv= decodtabm(k1,k,cptcoveff); /* Should be the value of the covariate corresponding to k1 combination */
                   7610:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7611:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7612:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7613:          vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
                   7614:          /* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
1.246     brouard  7615:          /* printf(" V%d=%d ",Tvaraff[k],vlv); */
1.238     brouard  7616:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7617:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7618:        }
                   7619:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.246     brouard  7620:          /* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  7621:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7622:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7623:        }
                   7624:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  7625:        /* printf("\n#\n"); */
1.238     brouard  7626:        fprintf(ficgp,"\n#\n");
                   7627:        if(invalidvarcomb[k1]){
1.260     brouard  7628:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  7629:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7630:          continue;
                   7631:        }
1.235     brouard  7632:       
1.241     brouard  7633:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   7634:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  7635:        /* 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  7636:        fprintf(ficgp,"set title \"Alive state %d %s model=%s\" font \"Helvetica,12\"\n",cpt,gplotlabel,model);
1.260     brouard  7637:        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);
                   7638:        /* 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); */
                   7639:       /* k1-1 error should be nres-1*/
1.238     brouard  7640:        for (i=1; i<= nlstate ; i ++) {
                   7641:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7642:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   7643:        }
1.288     brouard  7644:        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  7645:        for (i=1; i<= nlstate ; i ++) {
                   7646:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7647:          else fprintf(ficgp," %%*lf (%%*lf)");
                   7648:        } 
1.260     brouard  7649:        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  7650:        for (i=1; i<= nlstate ; i ++) {
                   7651:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7652:          else fprintf(ficgp," %%*lf (%%*lf)");
                   7653:        }  
1.265     brouard  7654:        /* 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)); */
                   7655:        
                   7656:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   7657:         if(cptcoveff ==0){
1.271     brouard  7658:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  7659:        }else{
                   7660:          kl=0;
                   7661:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   7662:            lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7663:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7664:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7665:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7666:            vlv= nbcode[Tvaraff[k]][lv];
                   7667:            kl++;
                   7668:            /* 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 *\/ */
                   7669:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7670:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7671:            /* ''  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*/
                   7672:            if(k==cptcoveff){
                   7673:              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], \
                   7674:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   7675:            }else{
                   7676:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   7677:              kl++;
                   7678:            }
                   7679:          } /* end covariate */
                   7680:        } /* end if no covariate */
                   7681: 
1.296     brouard  7682:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  7683:          /* 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  7684:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  7685:          if(cptcoveff ==0){
1.245     brouard  7686:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  7687:          }else{
                   7688:            kl=0;
                   7689:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   7690:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7691:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7692:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7693:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7694:              vlv= nbcode[Tvaraff[k]][lv];
1.223     brouard  7695:              kl++;
1.238     brouard  7696:              /* 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 *\/ */
                   7697:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7698:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7699:              /* ''  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*/
                   7700:              if(k==cptcoveff){
1.245     brouard  7701:                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  7702:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  7703:              }else{
                   7704:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   7705:                kl++;
                   7706:              }
                   7707:            } /* end covariate */
                   7708:          } /* end if no covariate */
1.296     brouard  7709:          if(prevbcast == 1){
1.268     brouard  7710:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   7711:            /* k1-1 error should be nres-1*/
                   7712:            for (i=1; i<= nlstate ; i ++) {
                   7713:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7714:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   7715:            }
1.271     brouard  7716:            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  7717:            for (i=1; i<= nlstate ; i ++) {
                   7718:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7719:              else fprintf(ficgp," %%*lf (%%*lf)");
                   7720:            } 
1.276     brouard  7721:            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  7722:            for (i=1; i<= nlstate ; i ++) {
                   7723:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7724:              else fprintf(ficgp," %%*lf (%%*lf)");
                   7725:            } 
1.274     brouard  7726:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  7727:          } /* end if backprojcast */
1.296     brouard  7728:        } /* end if prevbcast */
1.276     brouard  7729:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   7730:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  7731:       } /* nres */
1.201     brouard  7732:     } /* k1 */
                   7733:   } /* cpt */
1.235     brouard  7734: 
                   7735:   
1.126     brouard  7736:   /*2 eme*/
1.238     brouard  7737:   for (k1=1; k1<= m ; k1 ++){  
                   7738:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7739:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7740:        continue;
                   7741:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  7742:       strcpy(gplotlabel,"(");
1.238     brouard  7743:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.225     brouard  7744:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
1.223     brouard  7745:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7746:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7747:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7748:        vlv= nbcode[Tvaraff[k]][lv];
                   7749:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7750:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  7751:       }
1.237     brouard  7752:       /* for(k=1; k <= ncovds; k++){ */
1.236     brouard  7753:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  7754:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.236     brouard  7755:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7756:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7757:       }
1.264     brouard  7758:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  7759:       fprintf(ficgp,"\n#\n");
1.223     brouard  7760:       if(invalidvarcomb[k1]){
                   7761:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7762:        continue;
                   7763:       }
1.219     brouard  7764:                        
1.241     brouard  7765:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  7766:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  7767:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   7768:        if(vpopbased==0){
1.238     brouard  7769:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  7770:        }else
1.238     brouard  7771:          fprintf(ficgp,"\nreplot ");
                   7772:        for (i=1; i<= nlstate+1 ; i ++) {
                   7773:          k=2*i;
1.261     brouard  7774:          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  7775:          for (j=1; j<= nlstate+1 ; j ++) {
                   7776:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7777:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7778:          }   
                   7779:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   7780:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
1.261     brouard  7781:          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  7782:          for (j=1; j<= nlstate+1 ; j ++) {
                   7783:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7784:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7785:          }   
                   7786:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  7787:          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  7788:          for (j=1; j<= nlstate+1 ; j ++) {
                   7789:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7790:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7791:          }   
                   7792:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   7793:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   7794:        } /* state */
                   7795:       } /* vpopbased */
1.264     brouard  7796:       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  7797:     } /* end nres */
                   7798:   } /* k1 end 2 eme*/
                   7799:        
                   7800:        
                   7801:   /*3eme*/
                   7802:   for (k1=1; k1<= m ; k1 ++){
                   7803:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7804:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7805:        continue;
                   7806: 
                   7807:       for (cpt=1; cpt<= nlstate ; cpt ++) {
1.261     brouard  7808:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  7809:        strcpy(gplotlabel,"(");
1.238     brouard  7810:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7811:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7812:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7813:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7814:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7815:          vlv= nbcode[Tvaraff[k]][lv];
                   7816:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7817:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7818:        }
                   7819:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7820:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7821:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7822:        }       
1.264     brouard  7823:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7824:        fprintf(ficgp,"\n#\n");
                   7825:        if(invalidvarcomb[k1]){
                   7826:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7827:          continue;
                   7828:        }
                   7829:                        
                   7830:        /*       k=2+nlstate*(2*cpt-2); */
                   7831:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  7832:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  7833:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  7834:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  7835: 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  7836:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   7837:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   7838:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   7839:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   7840:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   7841:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  7842:                                
1.238     brouard  7843:        */
                   7844:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  7845:          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  7846:          /*    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  7847:                                
1.238     brouard  7848:        } 
1.261     brouard  7849:        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  7850:       }
1.264     brouard  7851:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  7852:     } /* end nres */
                   7853:   } /* end kl 3eme */
1.126     brouard  7854:   
1.223     brouard  7855:   /* 4eme */
1.201     brouard  7856:   /* Survival functions (period) from state i in state j by initial state i */
1.238     brouard  7857:   for (k1=1; k1<=m; k1++){    /* For each covariate and each value */
                   7858:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7859:       if(m != 1 && TKresult[nres]!= k1)
1.223     brouard  7860:        continue;
1.238     brouard  7861:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  7862:        strcpy(gplotlabel,"(");
1.238     brouard  7863:        fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
                   7864:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7865:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7866:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7867:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7868:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7869:          vlv= nbcode[Tvaraff[k]][lv];
                   7870:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7871:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7872:        }
                   7873:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7874:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7875:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7876:        }       
1.264     brouard  7877:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7878:        fprintf(ficgp,"\n#\n");
                   7879:        if(invalidvarcomb[k1]){
                   7880:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7881:          continue;
1.223     brouard  7882:        }
1.238     brouard  7883:       
1.241     brouard  7884:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  7885:        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  7886:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   7887: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   7888:        k=3;
                   7889:        for (i=1; i<= nlstate ; i ++){
                   7890:          if(i==1){
                   7891:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   7892:          }else{
                   7893:            fprintf(ficgp,", '' ");
                   7894:          }
                   7895:          l=(nlstate+ndeath)*(i-1)+1;
                   7896:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   7897:          for (j=2; j<= nlstate+ndeath ; j ++)
                   7898:            fprintf(ficgp,"+$%d",k+l+j-1);
                   7899:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   7900:        } /* nlstate */
1.264     brouard  7901:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  7902:       } /* end cpt state*/ 
                   7903:     } /* end nres */
                   7904:   } /* end covariate k1 */  
                   7905: 
1.220     brouard  7906: /* 5eme */
1.201     brouard  7907:   /* Survival functions (period) from state i in state j by final state j */
1.238     brouard  7908:   for (k1=1; k1<= m ; k1++){ /* For each covariate combination if any */
                   7909:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7910:       if(m != 1 && TKresult[nres]!= k1)
1.227     brouard  7911:        continue;
1.238     brouard  7912:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  7913:        strcpy(gplotlabel,"(");
1.238     brouard  7914:        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);
                   7915:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7916:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7917:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7918:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7919:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7920:          vlv= nbcode[Tvaraff[k]][lv];
                   7921:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7922:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7923:        }
                   7924:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7925:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7926:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7927:        }       
1.264     brouard  7928:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7929:        fprintf(ficgp,"\n#\n");
                   7930:        if(invalidvarcomb[k1]){
                   7931:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7932:          continue;
                   7933:        }
1.227     brouard  7934:       
1.241     brouard  7935:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  7936:        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  7937:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   7938: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   7939:        k=3;
                   7940:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   7941:          if(j==1)
                   7942:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   7943:          else
                   7944:            fprintf(ficgp,", '' ");
                   7945:          l=(nlstate+ndeath)*(cpt-1) +j;
                   7946:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   7947:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   7948:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   7949:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   7950:        } /* nlstate */
                   7951:        fprintf(ficgp,", '' ");
                   7952:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   7953:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   7954:          l=(nlstate+ndeath)*(cpt-1) +j;
                   7955:          if(j < nlstate)
                   7956:            fprintf(ficgp,"$%d +",k+l);
                   7957:          else
                   7958:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   7959:        }
1.264     brouard  7960:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  7961:       } /* end cpt state*/ 
                   7962:     } /* end covariate */  
                   7963:   } /* end nres */
1.227     brouard  7964:   
1.220     brouard  7965: /* 6eme */
1.202     brouard  7966:   /* CV preval stable (period) for each covariate */
1.237     brouard  7967:   for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7968:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7969:     if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7970:       continue;
1.255     brouard  7971:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  7972:       strcpy(gplotlabel,"(");      
1.288     brouard  7973:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.225     brouard  7974:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.227     brouard  7975:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   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 */
                   7979:        vlv= nbcode[Tvaraff[k]][lv];
                   7980:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7981:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  7982:       }
1.237     brouard  7983:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7984:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7985:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  7986:       }        
1.264     brouard  7987:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  7988:       fprintf(ficgp,"\n#\n");
1.223     brouard  7989:       if(invalidvarcomb[k1]){
1.227     brouard  7990:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7991:        continue;
1.223     brouard  7992:       }
1.227     brouard  7993:       
1.241     brouard  7994:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  7995:       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  7996:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  7997: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  7998:       k=3; /* Offset */
1.255     brouard  7999:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  8000:        if(i==1)
                   8001:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8002:        else
                   8003:          fprintf(ficgp,", '' ");
1.255     brouard  8004:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  8005:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8006:        for (j=2; j<= nlstate ; j ++)
                   8007:          fprintf(ficgp,"+$%d",k+l+j-1);
                   8008:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  8009:       } /* nlstate */
1.264     brouard  8010:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  8011:     } /* end cpt state*/ 
                   8012:   } /* end covariate */  
1.227     brouard  8013:   
                   8014:   
1.220     brouard  8015: /* 7eme */
1.296     brouard  8016:   if(prevbcast == 1){
1.288     brouard  8017:     /* CV backward prevalence  for each covariate */
1.237     brouard  8018:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   8019:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  8020:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  8021:        continue;
1.268     brouard  8022:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  8023:        strcpy(gplotlabel,"(");      
1.288     brouard  8024:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.227     brouard  8025:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   8026:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   8027:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8028:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
1.223     brouard  8029:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.227     brouard  8030:          vlv= nbcode[Tvaraff[k]][lv];
                   8031:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8032:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.227     brouard  8033:        }
1.237     brouard  8034:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   8035:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  8036:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  8037:        }       
1.264     brouard  8038:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8039:        fprintf(ficgp,"\n#\n");
                   8040:        if(invalidvarcomb[k1]){
                   8041:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8042:          continue;
                   8043:        }
                   8044:        
1.241     brouard  8045:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  8046:        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  8047:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8048: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  8049:        k=3; /* Offset */
1.268     brouard  8050:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  8051:          if(i==1)
                   8052:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   8053:          else
                   8054:            fprintf(ficgp,", '' ");
                   8055:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  8056:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.324     brouard  8057:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   8058:          /* 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  8059:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  8060:          /* for (j=2; j<= nlstate ; j ++) */
                   8061:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   8062:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  8063:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  8064:        } /* nlstate */
1.264     brouard  8065:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  8066:       } /* end cpt state*/ 
                   8067:     } /* end covariate */  
1.296     brouard  8068:   } /* End if prevbcast */
1.218     brouard  8069:   
1.223     brouard  8070:   /* 8eme */
1.218     brouard  8071:   if(prevfcast==1){
1.288     brouard  8072:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  8073:     
1.237     brouard  8074:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   8075:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  8076:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  8077:        continue;
1.211     brouard  8078:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  8079:        strcpy(gplotlabel,"(");      
1.288     brouard  8080:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.227     brouard  8081:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   8082:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   8083:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8084:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8085:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8086:          vlv= nbcode[Tvaraff[k]][lv];
                   8087:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8088:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.227     brouard  8089:        }
1.237     brouard  8090:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   8091:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  8092:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  8093:        }       
1.264     brouard  8094:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8095:        fprintf(ficgp,"\n#\n");
                   8096:        if(invalidvarcomb[k1]){
                   8097:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8098:          continue;
                   8099:        }
                   8100:        
                   8101:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  8102:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  8103:        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  8104:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  8105: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  8106: 
                   8107:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   8108:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8109:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8110:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  8111:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8112:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8113:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8114:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  8115:          if(i==istart){
1.227     brouard  8116:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   8117:          }else{
                   8118:            fprintf(ficgp,",\\\n '' ");
                   8119:          }
                   8120:          if(cptcoveff ==0){ /* No covariate */
                   8121:            ioffset=2; /* Age is in 2 */
                   8122:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8123:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8124:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8125:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8126:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  8127:            if(i==nlstate+1){
1.270     brouard  8128:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  8129:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   8130:              fprintf(ficgp,",\\\n '' ");
                   8131:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  8132:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  8133:                     offyear,                           \
1.268     brouard  8134:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  8135:            }else
1.227     brouard  8136:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   8137:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8138:          }else{ /* more than 2 covariates */
1.270     brouard  8139:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   8140:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8141:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   8142:            iyearc=ioffset-1;
                   8143:            iagec=ioffset;
1.227     brouard  8144:            fprintf(ficgp," u %d:(",ioffset); 
                   8145:            kl=0;
                   8146:            strcpy(gplotcondition,"(");
                   8147:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
                   8148:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   8149:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8150:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8151:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8152:              vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   8153:              kl++;
                   8154:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   8155:              kl++;
                   8156:              if(k <cptcoveff && cptcoveff>1)
                   8157:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   8158:            }
                   8159:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   8160:            /* 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 *\/ */
                   8161:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8162:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8163:            /* ''  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*/
                   8164:            if(i==nlstate+1){
1.270     brouard  8165:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   8166:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  8167:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  8168:              fprintf(ficgp," u %d:(",iagec); 
                   8169:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   8170:                      iyearc, iagec, offyear,                           \
                   8171:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  8172: /*  '' 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  8173:            }else{
                   8174:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   8175:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8176:            }
                   8177:          } /* end if covariate */
                   8178:        } /* nlstate */
1.264     brouard  8179:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  8180:       } /* end cpt state*/
                   8181:     } /* end covariate */
                   8182:   } /* End if prevfcast */
1.227     brouard  8183:   
1.296     brouard  8184:   if(prevbcast==1){
1.268     brouard  8185:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   8186:     
                   8187:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   8188:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8189:       if(m != 1 && TKresult[nres]!= k1)
                   8190:        continue;
                   8191:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   8192:        strcpy(gplotlabel,"(");      
                   8193:        fprintf(ficgp,"\n#\n#\n#Back projection of prevalence to stable (mixed) back prevalence: 'BPROJ_' files, covariatecombination#=%d originstate=%d",k1, cpt);
                   8194:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   8195:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   8196:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8197:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8198:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8199:          vlv= nbcode[Tvaraff[k]][lv];
                   8200:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   8201:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
                   8202:        }
                   8203:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   8204:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   8205:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   8206:        }       
                   8207:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   8208:        fprintf(ficgp,"\n#\n");
                   8209:        if(invalidvarcomb[k1]){
                   8210:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8211:          continue;
                   8212:        }
                   8213:        
                   8214:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   8215:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   8216:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   8217:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   8218: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8219: 
                   8220:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   8221:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8222:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8223:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   8224:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8225:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8226:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8227:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8228:          if(i==istart){
                   8229:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   8230:          }else{
                   8231:            fprintf(ficgp,",\\\n '' ");
                   8232:          }
                   8233:          if(cptcoveff ==0){ /* No covariate */
                   8234:            ioffset=2; /* Age is in 2 */
                   8235:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8236:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8237:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8238:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8239:            fprintf(ficgp," u %d:(", ioffset); 
                   8240:            if(i==nlstate+1){
1.270     brouard  8241:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  8242:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   8243:              fprintf(ficgp,",\\\n '' ");
                   8244:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  8245:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  8246:                     offbyear,                          \
                   8247:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   8248:            }else
                   8249:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   8250:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   8251:          }else{ /* more than 2 covariates */
1.270     brouard  8252:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   8253:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8254:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   8255:            iyearc=ioffset-1;
                   8256:            iagec=ioffset;
1.268     brouard  8257:            fprintf(ficgp," u %d:(",ioffset); 
                   8258:            kl=0;
                   8259:            strcpy(gplotcondition,"(");
                   8260:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
                   8261:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   8262:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8263:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8264:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8265:              vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   8266:              kl++;
                   8267:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   8268:              kl++;
                   8269:              if(k <cptcoveff && cptcoveff>1)
                   8270:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   8271:            }
                   8272:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   8273:            /* 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 *\/ */
                   8274:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8275:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8276:            /* ''  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*/
                   8277:            if(i==nlstate+1){
1.270     brouard  8278:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   8279:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  8280:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  8281:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  8282:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  8283:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   8284:                      iyearc,iagec,offbyear,                            \
                   8285:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  8286: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   8287:            }else{
                   8288:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   8289:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   8290:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   8291:            }
                   8292:          } /* end if covariate */
                   8293:        } /* nlstate */
                   8294:        fprintf(ficgp,"\nset out; unset label;\n");
                   8295:       } /* end cpt state*/
                   8296:     } /* end covariate */
1.296     brouard  8297:   } /* End if prevbcast */
1.268     brouard  8298:   
1.227     brouard  8299:   
1.238     brouard  8300:   /* 9eme writing MLE parameters */
                   8301:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  8302:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  8303:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  8304:     for(k=1; k <=(nlstate+ndeath); k++){
                   8305:       if (k != i) {
1.227     brouard  8306:        fprintf(ficgp,"#   current state %d\n",k);
                   8307:        for(j=1; j <=ncovmodel; j++){
                   8308:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   8309:          jk++; 
                   8310:        }
                   8311:        fprintf(ficgp,"\n");
1.126     brouard  8312:       }
                   8313:     }
1.223     brouard  8314:   }
1.187     brouard  8315:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  8316:   
1.145     brouard  8317:   /*goto avoid;*/
1.238     brouard  8318:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   8319:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  8320:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   8321:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   8322:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   8323:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   8324:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8325:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   8326:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8327:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   8328:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   8329:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8330:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   8331:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   8332:   fprintf(ficgp,"#\n");
1.223     brouard  8333:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  8334:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.237     brouard  8335:     fprintf(ficgp,"#model=%s \n",model);
1.238     brouard  8336:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.264     brouard  8337:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
                   8338:     for(k1=1; k1 <=m; k1++)  /* For each combination of covariate */
1.237     brouard  8339:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.264     brouard  8340:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  8341:        continue;
1.264     brouard  8342:       fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1);
                   8343:       strcpy(gplotlabel,"(");
1.276     brouard  8344:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.264     brouard  8345:       for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   8346:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   8347:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8348:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8349:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8350:        vlv= nbcode[Tvaraff[k]][lv];
                   8351:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   8352:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
                   8353:       }
1.237     brouard  8354:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   8355:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  8356:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  8357:       }        
1.264     brouard  8358:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  8359:       fprintf(ficgp,"\n#\n");
1.264     brouard  8360:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  8361:       fprintf(ficgp,"\nset key outside ");
                   8362:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   8363:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  8364:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   8365:       if (ng==1){
                   8366:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   8367:        fprintf(ficgp,"\nunset log y");
                   8368:       }else if (ng==2){
                   8369:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   8370:        fprintf(ficgp,"\nset log y");
                   8371:       }else if (ng==3){
                   8372:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   8373:        fprintf(ficgp,"\nset log y");
                   8374:       }else
                   8375:        fprintf(ficgp,"\nunset title ");
                   8376:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   8377:       i=1;
                   8378:       for(k2=1; k2<=nlstate; k2++) {
                   8379:        k3=i;
                   8380:        for(k=1; k<=(nlstate+ndeath); k++) {
                   8381:          if (k != k2){
                   8382:            switch( ng) {
                   8383:            case 1:
                   8384:              if(nagesqr==0)
                   8385:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   8386:              else /* nagesqr =1 */
                   8387:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   8388:              break;
                   8389:            case 2: /* ng=2 */
                   8390:              if(nagesqr==0)
                   8391:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   8392:              else /* nagesqr =1 */
                   8393:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   8394:              break;
                   8395:            case 3:
                   8396:              if(nagesqr==0)
                   8397:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   8398:              else /* nagesqr =1 */
                   8399:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   8400:              break;
                   8401:            }
                   8402:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  8403:            ijp=1; /* product no age */
                   8404:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   8405:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  8406:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.268     brouard  8407:              if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
1.325     brouard  8408:                if(j==Tage[ij]) { /* Product by age  To be looked at!!*//* Bug valgrind */
1.268     brouard  8409:                  if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
1.325     brouard  8410:                    if(DummyV[j]==0){/* Bug valgrind */
1.268     brouard  8411:                      fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   8412:                    }else{ /* quantitative */
                   8413:                      fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   8414:                      /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8415:                    }
                   8416:                    ij++;
1.237     brouard  8417:                  }
1.268     brouard  8418:                } 
                   8419:              }else if(cptcovprod >0){
                   8420:                if(j==Tprod[ijp]) { /* */ 
                   8421:                  /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   8422:                  if(ijp <=cptcovprod) { /* Product */
                   8423:                    if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   8424:                      if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   8425:                        /* 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)]); */
                   8426:                        fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   8427:                      }else{ /* Vn is dummy and Vm is quanti */
                   8428:                        /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8429:                        fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8430:                      }
                   8431:                    }else{ /* Vn*Vm Vn is quanti */
                   8432:                      if(DummyV[Tvard[ijp][2]]==0){
                   8433:                        fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   8434:                      }else{ /* Both quanti */
                   8435:                        fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8436:                      }
1.237     brouard  8437:                    }
1.268     brouard  8438:                    ijp++;
1.237     brouard  8439:                  }
1.268     brouard  8440:                } /* end Tprod */
1.237     brouard  8441:              } else{  /* simple covariate */
1.264     brouard  8442:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  8443:                if(Dummy[j]==0){
                   8444:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   8445:                }else{ /* quantitative */
                   8446:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  8447:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  8448:                }
1.237     brouard  8449:              } /* end simple */
                   8450:            } /* end j */
1.223     brouard  8451:          }else{
                   8452:            i=i-ncovmodel;
                   8453:            if(ng !=1 ) /* For logit formula of log p11 is more difficult to get */
                   8454:              fprintf(ficgp," (1.");
                   8455:          }
1.227     brouard  8456:          
1.223     brouard  8457:          if(ng != 1){
                   8458:            fprintf(ficgp,")/(1");
1.227     brouard  8459:            
1.264     brouard  8460:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  8461:              if(nagesqr==0)
1.264     brouard  8462:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  8463:              else /* nagesqr =1 */
1.264     brouard  8464:                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  8465:               
1.223     brouard  8466:              ij=1;
                   8467:              for(j=3; j <=ncovmodel-nagesqr; j++){
1.268     brouard  8468:                 if(cptcovage >0){ 
                   8469:                   if((j-2)==Tage[ij]) { /* Bug valgrind */
                   8470:                     if(ij <=cptcovage) { /* Bug valgrind */
                   8471:                       fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);
                   8472:                       /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8473:                       ij++;
                   8474:                     }
                   8475:                   }
                   8476:                 }else
                   8477:                   fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);/* Valgrind bug nbcode */
1.223     brouard  8478:              }
                   8479:              fprintf(ficgp,")");
                   8480:            }
                   8481:            fprintf(ficgp,")");
                   8482:            if(ng ==2)
1.276     brouard  8483:              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  8484:            else /* ng= 3 */
1.276     brouard  8485:              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.223     brouard  8486:          }else{ /* end ng <> 1 */
                   8487:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  8488:              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  8489:          }
                   8490:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   8491:            fprintf(ficgp,",");
                   8492:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   8493:            fprintf(ficgp,",");
                   8494:          i=i+ncovmodel;
                   8495:        } /* end k */
                   8496:       } /* end k2 */
1.276     brouard  8497:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   8498:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.264     brouard  8499:     } /* end k1 */
1.223     brouard  8500:   } /* end ng */
                   8501:   /* avoid: */
                   8502:   fflush(ficgp); 
1.126     brouard  8503: }  /* end gnuplot */
                   8504: 
                   8505: 
                   8506: /*************** Moving average **************/
1.219     brouard  8507: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  8508:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  8509:    
1.222     brouard  8510:    int i, cpt, cptcod;
                   8511:    int modcovmax =1;
                   8512:    int mobilavrange, mob;
                   8513:    int iage=0;
1.288     brouard  8514:    int firstA1=0, firstA2=0;
1.222     brouard  8515: 
1.266     brouard  8516:    double sum=0., sumr=0.;
1.222     brouard  8517:    double age;
1.266     brouard  8518:    double *sumnewp, *sumnewm, *sumnewmr;
                   8519:    double *agemingood, *agemaxgood; 
                   8520:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  8521:   
                   8522:   
1.278     brouard  8523:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   8524:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  8525: 
                   8526:    sumnewp = vector(1,ncovcombmax);
                   8527:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  8528:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  8529:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  8530:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  8531:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  8532:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  8533: 
                   8534:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  8535:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  8536:      sumnewp[cptcod]=0.;
1.266     brouard  8537:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   8538:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  8539:    }
                   8540:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   8541:   
1.266     brouard  8542:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   8543:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  8544:      else mobilavrange=mobilav;
                   8545:      for (age=bage; age<=fage; age++)
                   8546:        for (i=1; i<=nlstate;i++)
                   8547:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   8548:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8549:      /* We keep the original values on the extreme ages bage, fage and for 
                   8550:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   8551:        we use a 5 terms etc. until the borders are no more concerned. 
                   8552:      */ 
                   8553:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   8554:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  8555:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   8556:           sumnewm[cptcod]=0.;
                   8557:           for (i=1; i<=nlstate;i++){
1.222     brouard  8558:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   8559:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   8560:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   8561:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   8562:             }
                   8563:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  8564:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8565:           } /* end i */
                   8566:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   8567:         } /* end cptcod */
1.222     brouard  8568:        }/* end age */
                   8569:      }/* end mob */
1.266     brouard  8570:    }else{
                   8571:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  8572:      return -1;
1.266     brouard  8573:    }
                   8574: 
                   8575:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  8576:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   8577:      if(invalidvarcomb[cptcod]){
                   8578:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   8579:        continue;
                   8580:      }
1.219     brouard  8581: 
1.266     brouard  8582:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   8583:        sumnewm[cptcod]=0.;
                   8584:        sumnewmr[cptcod]=0.;
                   8585:        for (i=1; i<=nlstate;i++){
                   8586:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8587:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8588:        }
                   8589:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8590:         agemingoodr[cptcod]=age;
                   8591:        }
                   8592:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8593:           agemingood[cptcod]=age;
                   8594:        }
                   8595:      } /* age */
                   8596:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  8597:        sumnewm[cptcod]=0.;
1.266     brouard  8598:        sumnewmr[cptcod]=0.;
1.222     brouard  8599:        for (i=1; i<=nlstate;i++){
                   8600:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  8601:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8602:        }
                   8603:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8604:         agemaxgoodr[cptcod]=age;
1.222     brouard  8605:        }
                   8606:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  8607:         agemaxgood[cptcod]=age;
                   8608:        }
                   8609:      } /* age */
                   8610:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   8611:      /* but they will change */
1.288     brouard  8612:      firstA1=0;firstA2=0;
1.266     brouard  8613:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   8614:        sumnewm[cptcod]=0.;
                   8615:        sumnewmr[cptcod]=0.;
                   8616:        for (i=1; i<=nlstate;i++){
                   8617:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8618:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8619:        }
                   8620:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   8621:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8622:           agemaxgoodr[cptcod]=age;  /* age min */
                   8623:           for (i=1; i<=nlstate;i++)
                   8624:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8625:         }else{ /* bad we change the value with the values of good ages */
                   8626:           for (i=1; i<=nlstate;i++){
                   8627:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   8628:           } /* i */
                   8629:         } /* end bad */
                   8630:        }else{
                   8631:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8632:           agemaxgood[cptcod]=age;
                   8633:         }else{ /* bad we change the value with the values of good ages */
                   8634:           for (i=1; i<=nlstate;i++){
                   8635:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   8636:           } /* i */
                   8637:         } /* end bad */
                   8638:        }/* end else */
                   8639:        sum=0.;sumr=0.;
                   8640:        for (i=1; i<=nlstate;i++){
                   8641:         sum+=mobaverage[(int)age][i][cptcod];
                   8642:         sumr+=probs[(int)age][i][cptcod];
                   8643:        }
                   8644:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  8645:         if(!firstA1){
                   8646:           firstA1=1;
                   8647:           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);
                   8648:         }
                   8649:         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  8650:        } /* end bad */
                   8651:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   8652:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  8653:         if(!firstA2){
                   8654:           firstA2=1;
                   8655:           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);
                   8656:         }
                   8657:         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  8658:        } /* end bad */
                   8659:      }/* age */
1.266     brouard  8660: 
                   8661:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  8662:        sumnewm[cptcod]=0.;
1.266     brouard  8663:        sumnewmr[cptcod]=0.;
1.222     brouard  8664:        for (i=1; i<=nlstate;i++){
                   8665:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  8666:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8667:        } 
                   8668:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   8669:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   8670:           agemingoodr[cptcod]=age;
                   8671:           for (i=1; i<=nlstate;i++)
                   8672:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8673:         }else{ /* bad we change the value with the values of good ages */
                   8674:           for (i=1; i<=nlstate;i++){
                   8675:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   8676:           } /* i */
                   8677:         } /* end bad */
                   8678:        }else{
                   8679:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8680:           agemingood[cptcod]=age;
                   8681:         }else{ /* bad */
                   8682:           for (i=1; i<=nlstate;i++){
                   8683:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   8684:           } /* i */
                   8685:         } /* end bad */
                   8686:        }/* end else */
                   8687:        sum=0.;sumr=0.;
                   8688:        for (i=1; i<=nlstate;i++){
                   8689:         sum+=mobaverage[(int)age][i][cptcod];
                   8690:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  8691:        }
1.266     brouard  8692:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  8693:         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  8694:        } /* end bad */
                   8695:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   8696:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  8697:         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  8698:        } /* end bad */
                   8699:      }/* age */
1.266     brouard  8700: 
1.222     brouard  8701:                
                   8702:      for (age=bage; age<=fage; age++){
1.235     brouard  8703:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  8704:        sumnewp[cptcod]=0.;
                   8705:        sumnewm[cptcod]=0.;
                   8706:        for (i=1; i<=nlstate;i++){
                   8707:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   8708:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8709:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   8710:        }
                   8711:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   8712:      }
                   8713:      /* printf("\n"); */
                   8714:      /* } */
1.266     brouard  8715: 
1.222     brouard  8716:      /* brutal averaging */
1.266     brouard  8717:      /* for (i=1; i<=nlstate;i++){ */
                   8718:      /*   for (age=1; age<=bage; age++){ */
                   8719:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   8720:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   8721:      /*   }     */
                   8722:      /*   for (age=fage; age<=AGESUP; age++){ */
                   8723:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   8724:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   8725:      /*   } */
                   8726:      /* } /\* end i status *\/ */
                   8727:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   8728:      /*   for (age=1; age<=AGESUP; age++){ */
                   8729:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   8730:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   8731:      /*   } */
                   8732:      /* } */
1.222     brouard  8733:    }/* end cptcod */
1.266     brouard  8734:    free_vector(agemaxgoodr,1, ncovcombmax);
                   8735:    free_vector(agemaxgood,1, ncovcombmax);
                   8736:    free_vector(agemingood,1, ncovcombmax);
                   8737:    free_vector(agemingoodr,1, ncovcombmax);
                   8738:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  8739:    free_vector(sumnewm,1, ncovcombmax);
                   8740:    free_vector(sumnewp,1, ncovcombmax);
                   8741:    return 0;
                   8742:  }/* End movingaverage */
1.218     brouard  8743:  
1.126     brouard  8744: 
1.296     brouard  8745:  
1.126     brouard  8746: /************** Forecasting ******************/
1.296     brouard  8747: /* 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)*/
                   8748: 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){
                   8749:   /* dateintemean, mean date of interviews
                   8750:      dateprojd, year, month, day of starting projection 
                   8751:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  8752:      agemin, agemax range of age
                   8753:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   8754:   */
1.296     brouard  8755:   /* double anprojd, mprojd, jprojd; */
                   8756:   /* double anprojf, mprojf, jprojf; */
1.267     brouard  8757:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  8758:   double agec; /* generic age */
1.296     brouard  8759:   double agelim, ppij, yp,yp1,yp2;
1.126     brouard  8760:   double *popeffectif,*popcount;
                   8761:   double ***p3mat;
1.218     brouard  8762:   /* double ***mobaverage; */
1.126     brouard  8763:   char fileresf[FILENAMELENGTH];
                   8764: 
                   8765:   agelim=AGESUP;
1.211     brouard  8766:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   8767:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   8768:      We still use firstpass and lastpass as another selection.
                   8769:   */
1.214     brouard  8770:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   8771:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  8772:  
1.201     brouard  8773:   strcpy(fileresf,"F_"); 
                   8774:   strcat(fileresf,fileresu);
1.126     brouard  8775:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   8776:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   8777:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   8778:   }
1.235     brouard  8779:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   8780:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  8781: 
1.225     brouard  8782:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  8783: 
                   8784: 
                   8785:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   8786:   if (stepm<=12) stepsize=1;
                   8787:   if(estepm < stepm){
                   8788:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   8789:   }
1.270     brouard  8790:   else{
                   8791:     hstepm=estepm;   
                   8792:   }
                   8793:   if(estepm > stepm){ /* Yes every two year */
                   8794:     stepsize=2;
                   8795:   }
1.296     brouard  8796:   hstepm=hstepm/stepm;
1.126     brouard  8797: 
1.296     brouard  8798:   
                   8799:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   8800:   /*                              fractional in yp1 *\/ */
                   8801:   /* aintmean=yp; */
                   8802:   /* yp2=modf((yp1*12),&yp); */
                   8803:   /* mintmean=yp; */
                   8804:   /* yp1=modf((yp2*30.5),&yp); */
                   8805:   /* jintmean=yp; */
                   8806:   /* if(jintmean==0) jintmean=1; */
                   8807:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  8808: 
1.296     brouard  8809: 
                   8810:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   8811:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   8812:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.227     brouard  8813:   i1=pow(2,cptcoveff);
1.126     brouard  8814:   if (cptcovn < 1){i1=1;}
                   8815:   
1.296     brouard  8816:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  8817:   
                   8818:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  8819:   
1.126     brouard  8820: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  8821:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8822:   for(k=1; k<=i1;k++){
1.253     brouard  8823:     if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  8824:       continue;
1.227     brouard  8825:     if(invalidvarcomb[k]){
                   8826:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   8827:       continue;
                   8828:     }
                   8829:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   8830:     for(j=1;j<=cptcoveff;j++) {
                   8831:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8832:     }
1.235     brouard  8833:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  8834:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.235     brouard  8835:     }
1.227     brouard  8836:     fprintf(ficresf," yearproj age");
                   8837:     for(j=1; j<=nlstate+ndeath;j++){ 
                   8838:       for(i=1; i<=nlstate;i++)               
                   8839:        fprintf(ficresf," p%d%d",i,j);
                   8840:       fprintf(ficresf," wp.%d",j);
                   8841:     }
1.296     brouard  8842:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  8843:       fprintf(ficresf,"\n");
1.296     brouard  8844:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  8845:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   8846:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  8847:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   8848:        nhstepm = nhstepm/hstepm; 
                   8849:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8850:        oldm=oldms;savm=savms;
1.268     brouard  8851:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  8852:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  8853:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  8854:        for (h=0; h<=nhstepm; h++){
                   8855:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  8856:            break;
                   8857:          }
                   8858:        }
                   8859:        fprintf(ficresf,"\n");
                   8860:        for(j=1;j<=cptcoveff;j++) 
                   8861:          fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.296     brouard  8862:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  8863:        
                   8864:        for(j=1; j<=nlstate+ndeath;j++) {
                   8865:          ppij=0.;
                   8866:          for(i=1; i<=nlstate;i++) {
1.278     brouard  8867:            if (mobilav>=1)
                   8868:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   8869:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   8870:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   8871:            }
1.268     brouard  8872:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   8873:          } /* end i */
                   8874:          fprintf(ficresf," %.3f", ppij);
                   8875:        }/* end j */
1.227     brouard  8876:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8877:       } /* end agec */
1.266     brouard  8878:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   8879:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  8880:     } /* end yearp */
                   8881:   } /* end  k */
1.219     brouard  8882:        
1.126     brouard  8883:   fclose(ficresf);
1.215     brouard  8884:   printf("End of Computing forecasting \n");
                   8885:   fprintf(ficlog,"End of Computing forecasting\n");
                   8886: 
1.126     brouard  8887: }
                   8888: 
1.269     brouard  8889: /************** Back Forecasting ******************/
1.296     brouard  8890:  /* 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){ */
                   8891:  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){
                   8892:   /* back1, year, month, day of starting backprojection
1.267     brouard  8893:      agemin, agemax range of age
                   8894:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  8895:      anback2 year of end of backprojection (same day and month as back1).
                   8896:      prevacurrent and prev are prevalences.
1.267     brouard  8897:   */
                   8898:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   8899:   double agec; /* generic age */
1.302     brouard  8900:   double agelim, ppij, ppi, yp,yp1,yp2; /* ,jintmean,mintmean,aintmean;*/
1.267     brouard  8901:   double *popeffectif,*popcount;
                   8902:   double ***p3mat;
                   8903:   /* double ***mobaverage; */
                   8904:   char fileresfb[FILENAMELENGTH];
                   8905:  
1.268     brouard  8906:   agelim=AGEINF;
1.267     brouard  8907:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   8908:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   8909:      We still use firstpass and lastpass as another selection.
                   8910:   */
                   8911:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   8912:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   8913: 
                   8914:   /*Do we need to compute prevalence again?*/
                   8915: 
                   8916:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   8917:   
                   8918:   strcpy(fileresfb,"FB_");
                   8919:   strcat(fileresfb,fileresu);
                   8920:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   8921:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   8922:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   8923:   }
                   8924:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   8925:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   8926:   
                   8927:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   8928:   
                   8929:    
                   8930:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   8931:   if (stepm<=12) stepsize=1;
                   8932:   if(estepm < stepm){
                   8933:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   8934:   }
1.270     brouard  8935:   else{
                   8936:     hstepm=estepm;   
                   8937:   }
                   8938:   if(estepm >= stepm){ /* Yes every two year */
                   8939:     stepsize=2;
                   8940:   }
1.267     brouard  8941:   
                   8942:   hstepm=hstepm/stepm;
1.296     brouard  8943:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   8944:   /*                              fractional in yp1 *\/ */
                   8945:   /* aintmean=yp; */
                   8946:   /* yp2=modf((yp1*12),&yp); */
                   8947:   /* mintmean=yp; */
                   8948:   /* yp1=modf((yp2*30.5),&yp); */
                   8949:   /* jintmean=yp; */
                   8950:   /* if(jintmean==0) jintmean=1; */
                   8951:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  8952:   
                   8953:   i1=pow(2,cptcoveff);
                   8954:   if (cptcovn < 1){i1=1;}
                   8955:   
1.296     brouard  8956:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   8957:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  8958:   
                   8959:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   8960:   
                   8961:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8962:   for(k=1; k<=i1;k++){
                   8963:     if(i1 != 1 && TKresult[nres]!= k)
                   8964:       continue;
                   8965:     if(invalidvarcomb[k]){
                   8966:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   8967:       continue;
                   8968:     }
1.268     brouard  8969:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.267     brouard  8970:     for(j=1;j<=cptcoveff;j++) {
                   8971:       fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8972:     }
                   8973:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   8974:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   8975:     }
                   8976:     fprintf(ficresfb," yearbproj age");
                   8977:     for(j=1; j<=nlstate+ndeath;j++){
                   8978:       for(i=1; i<=nlstate;i++)
1.268     brouard  8979:        fprintf(ficresfb," b%d%d",i,j);
                   8980:       fprintf(ficresfb," b.%d",j);
1.267     brouard  8981:     }
1.296     brouard  8982:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  8983:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   8984:       fprintf(ficresfb,"\n");
1.296     brouard  8985:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  8986:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  8987:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   8988:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  8989:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  8990:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  8991:        nhstepm = nhstepm/hstepm;
                   8992:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8993:        oldm=oldms;savm=savms;
1.268     brouard  8994:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  8995:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  8996:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  8997:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   8998:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   8999:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  9000:        for (h=0; h<=nhstepm; h++){
1.268     brouard  9001:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   9002:            break;
                   9003:          }
                   9004:        }
                   9005:        fprintf(ficresfb,"\n");
                   9006:        for(j=1;j<=cptcoveff;j++)
                   9007:          fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.296     brouard  9008:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  9009:        for(i=1; i<=nlstate+ndeath;i++) {
                   9010:          ppij=0.;ppi=0.;
                   9011:          for(j=1; j<=nlstate;j++) {
                   9012:            /* if (mobilav==1) */
1.269     brouard  9013:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   9014:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   9015:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   9016:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  9017:              /* else { */
                   9018:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   9019:              /* } */
1.268     brouard  9020:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   9021:          } /* end j */
                   9022:          if(ppi <0.99){
                   9023:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   9024:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   9025:          }
                   9026:          fprintf(ficresfb," %.3f", ppij);
                   9027:        }/* end j */
1.267     brouard  9028:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9029:       } /* end agec */
                   9030:     } /* end yearp */
                   9031:   } /* end k */
1.217     brouard  9032:   
1.267     brouard  9033:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  9034:   
1.267     brouard  9035:   fclose(ficresfb);
                   9036:   printf("End of Computing Back forecasting \n");
                   9037:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  9038:        
1.267     brouard  9039: }
1.217     brouard  9040: 
1.269     brouard  9041: /* Variance of prevalence limit: varprlim */
                   9042:  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  9043:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  9044:  
                   9045:    char fileresvpl[FILENAMELENGTH];  
                   9046:    FILE *ficresvpl;
                   9047:    double **oldm, **savm;
                   9048:    double **varpl; /* Variances of prevalence limits by age */   
                   9049:    int i1, k, nres, j ;
                   9050:    
                   9051:     strcpy(fileresvpl,"VPL_");
                   9052:     strcat(fileresvpl,fileresu);
                   9053:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  9054:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  9055:       exit(0);
                   9056:     }
1.288     brouard  9057:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   9058:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  9059:     
                   9060:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   9061:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   9062:     
                   9063:     i1=pow(2,cptcoveff);
                   9064:     if (cptcovn < 1){i1=1;}
                   9065: 
                   9066:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9067:     for(k=1; k<=i1;k++){
                   9068:       if(i1 != 1 && TKresult[nres]!= k)
                   9069:        continue;
                   9070:       fprintf(ficresvpl,"\n#****** ");
                   9071:       printf("\n#****** ");
                   9072:       fprintf(ficlog,"\n#****** ");
                   9073:       for(j=1;j<=cptcoveff;j++) {
                   9074:        fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9075:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9076:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9077:       }
                   9078:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   9079:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9080:        fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9081:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9082:       }        
                   9083:       fprintf(ficresvpl,"******\n");
                   9084:       printf("******\n");
                   9085:       fprintf(ficlog,"******\n");
                   9086:       
                   9087:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9088:       oldm=oldms;savm=savms;
                   9089:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   9090:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   9091:       /*}*/
                   9092:     }
                   9093:     
                   9094:     fclose(ficresvpl);
1.288     brouard  9095:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   9096:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  9097: 
                   9098:  }
                   9099: /* Variance of back prevalence: varbprlim */
                   9100:  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){
                   9101:       /*------- Variance of back (stable) prevalence------*/
                   9102: 
                   9103:    char fileresvbl[FILENAMELENGTH];  
                   9104:    FILE  *ficresvbl;
                   9105: 
                   9106:    double **oldm, **savm;
                   9107:    double **varbpl; /* Variances of back prevalence limits by age */   
                   9108:    int i1, k, nres, j ;
                   9109: 
                   9110:    strcpy(fileresvbl,"VBL_");
                   9111:    strcat(fileresvbl,fileresu);
                   9112:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   9113:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   9114:      exit(0);
                   9115:    }
                   9116:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   9117:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   9118:    
                   9119:    
                   9120:    i1=pow(2,cptcoveff);
                   9121:    if (cptcovn < 1){i1=1;}
                   9122:    
                   9123:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9124:      for(k=1; k<=i1;k++){
                   9125:        if(i1 != 1 && TKresult[nres]!= k)
                   9126:         continue;
                   9127:        fprintf(ficresvbl,"\n#****** ");
                   9128:        printf("\n#****** ");
                   9129:        fprintf(ficlog,"\n#****** ");
                   9130:        for(j=1;j<=cptcoveff;j++) {
                   9131:         fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9132:         fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9133:         printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9134:        }
                   9135:        for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   9136:         printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9137:         fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9138:         fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9139:        }
                   9140:        fprintf(ficresvbl,"******\n");
                   9141:        printf("******\n");
                   9142:        fprintf(ficlog,"******\n");
                   9143:        
                   9144:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9145:        oldm=oldms;savm=savms;
                   9146:        
                   9147:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   9148:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   9149:        /*}*/
                   9150:      }
                   9151:    
                   9152:    fclose(ficresvbl);
                   9153:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   9154:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   9155: 
                   9156:  } /* End of varbprlim */
                   9157: 
1.126     brouard  9158: /************** Forecasting *****not tested NB*************/
1.227     brouard  9159: /* 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  9160:   
1.227     brouard  9161: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   9162: /*   int *popage; */
                   9163: /*   double calagedatem, agelim, kk1, kk2; */
                   9164: /*   double *popeffectif,*popcount; */
                   9165: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   9166: /*   /\* double ***mobaverage; *\/ */
                   9167: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  9168: 
1.227     brouard  9169: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9170: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9171: /*   agelim=AGESUP; */
                   9172: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  9173:   
1.227     brouard  9174: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  9175:   
                   9176:   
1.227     brouard  9177: /*   strcpy(filerespop,"POP_");  */
                   9178: /*   strcat(filerespop,fileresu); */
                   9179: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   9180: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   9181: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   9182: /*   } */
                   9183: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   9184: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  9185: 
1.227     brouard  9186: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  9187: 
1.227     brouard  9188: /*   /\* if (mobilav!=0) { *\/ */
                   9189: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   9190: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   9191: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   9192: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   9193: /*   /\*   } *\/ */
                   9194: /*   /\* } *\/ */
1.126     brouard  9195: 
1.227     brouard  9196: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   9197: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  9198:   
1.227     brouard  9199: /*   agelim=AGESUP; */
1.126     brouard  9200:   
1.227     brouard  9201: /*   hstepm=1; */
                   9202: /*   hstepm=hstepm/stepm;  */
1.218     brouard  9203:        
1.227     brouard  9204: /*   if (popforecast==1) { */
                   9205: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   9206: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   9207: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   9208: /*     }  */
                   9209: /*     popage=ivector(0,AGESUP); */
                   9210: /*     popeffectif=vector(0,AGESUP); */
                   9211: /*     popcount=vector(0,AGESUP); */
1.126     brouard  9212:     
1.227     brouard  9213: /*     i=1;    */
                   9214: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  9215:     
1.227     brouard  9216: /*     imx=i; */
                   9217: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   9218: /*   } */
1.218     brouard  9219:   
1.227     brouard  9220: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   9221: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   9222: /*       k=k+1; */
                   9223: /*       fprintf(ficrespop,"\n#******"); */
                   9224: /*       for(j=1;j<=cptcoveff;j++) { */
                   9225: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   9226: /*       } */
                   9227: /*       fprintf(ficrespop,"******\n"); */
                   9228: /*       fprintf(ficrespop,"# Age"); */
                   9229: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   9230: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  9231:       
1.227     brouard  9232: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   9233: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  9234:        
1.227     brouard  9235: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   9236: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   9237: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  9238:          
1.227     brouard  9239: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9240: /*       oldm=oldms;savm=savms; */
                   9241: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  9242:          
1.227     brouard  9243: /*       for (h=0; h<=nhstepm; h++){ */
                   9244: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   9245: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   9246: /*         }  */
                   9247: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   9248: /*           kk1=0.;kk2=0; */
                   9249: /*           for(i=1; i<=nlstate;i++) {               */
                   9250: /*             if (mobilav==1)  */
                   9251: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   9252: /*             else { */
                   9253: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   9254: /*             } */
                   9255: /*           } */
                   9256: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   9257: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   9258: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   9259: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   9260: /*           } */
                   9261: /*         } */
                   9262: /*         for(i=1; i<=nlstate;i++){ */
                   9263: /*           kk1=0.; */
                   9264: /*           for(j=1; j<=nlstate;j++){ */
                   9265: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   9266: /*           } */
                   9267: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   9268: /*         } */
1.218     brouard  9269:            
1.227     brouard  9270: /*         if (h==(int)(calagedatem+12*cpt)) */
                   9271: /*           for(j=1; j<=nlstate;j++)  */
                   9272: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   9273: /*       } */
                   9274: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9275: /*     } */
                   9276: /*       } */
1.218     brouard  9277:       
1.227     brouard  9278: /*       /\******\/ */
1.218     brouard  9279:       
1.227     brouard  9280: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   9281: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   9282: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   9283: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   9284: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  9285:          
1.227     brouard  9286: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9287: /*       oldm=oldms;savm=savms; */
                   9288: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   9289: /*       for (h=0; h<=nhstepm; h++){ */
                   9290: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   9291: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   9292: /*         }  */
                   9293: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   9294: /*           kk1=0.;kk2=0; */
                   9295: /*           for(i=1; i<=nlstate;i++) {               */
                   9296: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   9297: /*           } */
                   9298: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   9299: /*         } */
                   9300: /*       } */
                   9301: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9302: /*     } */
                   9303: /*       } */
                   9304: /*     }  */
                   9305: /*   } */
1.218     brouard  9306:   
1.227     brouard  9307: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  9308:   
1.227     brouard  9309: /*   if (popforecast==1) { */
                   9310: /*     free_ivector(popage,0,AGESUP); */
                   9311: /*     free_vector(popeffectif,0,AGESUP); */
                   9312: /*     free_vector(popcount,0,AGESUP); */
                   9313: /*   } */
                   9314: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9315: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9316: /*   fclose(ficrespop); */
                   9317: /* } /\* End of popforecast *\/ */
1.218     brouard  9318:  
1.126     brouard  9319: int fileappend(FILE *fichier, char *optionfich)
                   9320: {
                   9321:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   9322:     printf("Problem with file: %s\n", optionfich);
                   9323:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   9324:     return (0);
                   9325:   }
                   9326:   fflush(fichier);
                   9327:   return (1);
                   9328: }
                   9329: 
                   9330: 
                   9331: /**************** function prwizard **********************/
                   9332: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   9333: {
                   9334: 
                   9335:   /* Wizard to print covariance matrix template */
                   9336: 
1.164     brouard  9337:   char ca[32], cb[32];
                   9338:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  9339:   int numlinepar;
                   9340: 
                   9341:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9342:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9343:   for(i=1; i <=nlstate; i++){
                   9344:     jj=0;
                   9345:     for(j=1; j <=nlstate+ndeath; j++){
                   9346:       if(j==i) continue;
                   9347:       jj++;
                   9348:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   9349:       printf("%1d%1d",i,j);
                   9350:       fprintf(ficparo,"%1d%1d",i,j);
                   9351:       for(k=1; k<=ncovmodel;k++){
                   9352:        /*        printf(" %lf",param[i][j][k]); */
                   9353:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   9354:        printf(" 0.");
                   9355:        fprintf(ficparo," 0.");
                   9356:       }
                   9357:       printf("\n");
                   9358:       fprintf(ficparo,"\n");
                   9359:     }
                   9360:   }
                   9361:   printf("# Scales (for hessian or gradient estimation)\n");
                   9362:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   9363:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   9364:   for(i=1; i <=nlstate; i++){
                   9365:     jj=0;
                   9366:     for(j=1; j <=nlstate+ndeath; j++){
                   9367:       if(j==i) continue;
                   9368:       jj++;
                   9369:       fprintf(ficparo,"%1d%1d",i,j);
                   9370:       printf("%1d%1d",i,j);
                   9371:       fflush(stdout);
                   9372:       for(k=1; k<=ncovmodel;k++){
                   9373:        /*      printf(" %le",delti3[i][j][k]); */
                   9374:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   9375:        printf(" 0.");
                   9376:        fprintf(ficparo," 0.");
                   9377:       }
                   9378:       numlinepar++;
                   9379:       printf("\n");
                   9380:       fprintf(ficparo,"\n");
                   9381:     }
                   9382:   }
                   9383:   printf("# Covariance matrix\n");
                   9384: /* # 121 Var(a12)\n\ */
                   9385: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   9386: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   9387: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   9388: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   9389: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   9390: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   9391: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   9392:   fflush(stdout);
                   9393:   fprintf(ficparo,"# Covariance matrix\n");
                   9394:   /* # 121 Var(a12)\n\ */
                   9395:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   9396:   /* #   ...\n\ */
                   9397:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   9398:   
                   9399:   for(itimes=1;itimes<=2;itimes++){
                   9400:     jj=0;
                   9401:     for(i=1; i <=nlstate; i++){
                   9402:       for(j=1; j <=nlstate+ndeath; j++){
                   9403:        if(j==i) continue;
                   9404:        for(k=1; k<=ncovmodel;k++){
                   9405:          jj++;
                   9406:          ca[0]= k+'a'-1;ca[1]='\0';
                   9407:          if(itimes==1){
                   9408:            printf("#%1d%1d%d",i,j,k);
                   9409:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   9410:          }else{
                   9411:            printf("%1d%1d%d",i,j,k);
                   9412:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   9413:            /*  printf(" %.5le",matcov[i][j]); */
                   9414:          }
                   9415:          ll=0;
                   9416:          for(li=1;li <=nlstate; li++){
                   9417:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   9418:              if(lj==li) continue;
                   9419:              for(lk=1;lk<=ncovmodel;lk++){
                   9420:                ll++;
                   9421:                if(ll<=jj){
                   9422:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   9423:                  if(ll<jj){
                   9424:                    if(itimes==1){
                   9425:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9426:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9427:                    }else{
                   9428:                      printf(" 0.");
                   9429:                      fprintf(ficparo," 0.");
                   9430:                    }
                   9431:                  }else{
                   9432:                    if(itimes==1){
                   9433:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   9434:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   9435:                    }else{
                   9436:                      printf(" 0.");
                   9437:                      fprintf(ficparo," 0.");
                   9438:                    }
                   9439:                  }
                   9440:                }
                   9441:              } /* end lk */
                   9442:            } /* end lj */
                   9443:          } /* end li */
                   9444:          printf("\n");
                   9445:          fprintf(ficparo,"\n");
                   9446:          numlinepar++;
                   9447:        } /* end k*/
                   9448:       } /*end j */
                   9449:     } /* end i */
                   9450:   } /* end itimes */
                   9451: 
                   9452: } /* end of prwizard */
                   9453: /******************* Gompertz Likelihood ******************************/
                   9454: double gompertz(double x[])
                   9455: { 
1.302     brouard  9456:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
1.126     brouard  9457:   int i,n=0; /* n is the size of the sample */
                   9458: 
1.220     brouard  9459:   for (i=1;i<=imx ; i++) {
1.126     brouard  9460:     sump=sump+weight[i];
                   9461:     /*    sump=sump+1;*/
                   9462:     num=num+1;
                   9463:   }
1.302     brouard  9464:   L=0.0;
                   9465:   /* agegomp=AGEGOMP; */
1.126     brouard  9466:   /* for (i=0; i<=imx; i++) 
                   9467:      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]);*/
                   9468: 
1.302     brouard  9469:   for (i=1;i<=imx ; i++) {
                   9470:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   9471:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   9472:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   9473:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   9474:      * +
                   9475:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   9476:      */
                   9477:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   9478:        if (cens[i] == 1){
                   9479:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   9480:        } else if (cens[i] == 0){
1.126     brouard  9481:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
1.302     brouard  9482:          +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   9483:       } else
                   9484:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
1.126     brouard  9485:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
1.302     brouard  9486:        L=L+A*weight[i];
1.126     brouard  9487:        /*      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  9488:      }
                   9489:   }
1.126     brouard  9490: 
1.302     brouard  9491:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
1.126     brouard  9492:  
                   9493:   return -2*L*num/sump;
                   9494: }
                   9495: 
1.136     brouard  9496: #ifdef GSL
                   9497: /******************* Gompertz_f Likelihood ******************************/
                   9498: double gompertz_f(const gsl_vector *v, void *params)
                   9499: { 
1.302     brouard  9500:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
1.136     brouard  9501:   double *x= (double *) v->data;
                   9502:   int i,n=0; /* n is the size of the sample */
                   9503: 
                   9504:   for (i=0;i<=imx-1 ; i++) {
                   9505:     sump=sump+weight[i];
                   9506:     /*    sump=sump+1;*/
                   9507:     num=num+1;
                   9508:   }
                   9509:  
                   9510:  
                   9511:   /* for (i=0; i<=imx; i++) 
                   9512:      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]);*/
                   9513:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   9514:   for (i=1;i<=imx ; i++)
                   9515:     {
                   9516:       if (cens[i] == 1 && wav[i]>1)
                   9517:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   9518:       
                   9519:       if (cens[i] == 0 && wav[i]>1)
                   9520:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   9521:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   9522:       
                   9523:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   9524:       if (wav[i] > 1 ) { /* ??? */
                   9525:        LL=LL+A*weight[i];
                   9526:        /*      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]);*/
                   9527:       }
                   9528:     }
                   9529: 
                   9530:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   9531:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   9532:  
                   9533:   return -2*LL*num/sump;
                   9534: }
                   9535: #endif
                   9536: 
1.126     brouard  9537: /******************* Printing html file ***********/
1.201     brouard  9538: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  9539:                  int lastpass, int stepm, int weightopt, char model[],\
                   9540:                  int imx,  double p[],double **matcov,double agemortsup){
                   9541:   int i,k;
                   9542: 
                   9543:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   9544:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   9545:   for (i=1;i<=2;i++) 
                   9546:     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  9547:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  9548:   fprintf(fichtm,"</ul>");
                   9549: 
                   9550: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   9551: 
                   9552:  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>");
                   9553: 
                   9554:  for (k=agegomp;k<(agemortsup-2);k++) 
                   9555:    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]);
                   9556: 
                   9557:  
                   9558:   fflush(fichtm);
                   9559: }
                   9560: 
                   9561: /******************* Gnuplot file **************/
1.201     brouard  9562: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  9563: 
                   9564:   char dirfileres[132],optfileres[132];
1.164     brouard  9565: 
1.126     brouard  9566:   int ng;
                   9567: 
                   9568: 
                   9569:   /*#ifdef windows */
                   9570:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   9571:     /*#endif */
                   9572: 
                   9573: 
                   9574:   strcpy(dirfileres,optionfilefiname);
                   9575:   strcpy(optfileres,"vpl");
1.199     brouard  9576:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  9577:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  9578:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  9579:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  9580:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   9581: 
                   9582: } 
                   9583: 
1.136     brouard  9584: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   9585: {
1.126     brouard  9586: 
1.136     brouard  9587:   /*-------- data file ----------*/
                   9588:   FILE *fic;
                   9589:   char dummy[]="                         ";
1.240     brouard  9590:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  9591:   int lstra;
1.136     brouard  9592:   int linei, month, year,iout;
1.302     brouard  9593:   int noffset=0; /* This is the offset if BOM data file */
1.136     brouard  9594:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  9595:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  9596:   char *stratrunc;
1.223     brouard  9597: 
1.240     brouard  9598:   DummyV=ivector(1,NCOVMAX); /* 1 to 3 */
                   9599:   FixedV=ivector(1,NCOVMAX); /* 1 to 3 */
1.126     brouard  9600: 
1.240     brouard  9601:   for(v=1; v <=ncovcol;v++){
                   9602:     DummyV[v]=0;
                   9603:     FixedV[v]=0;
                   9604:   }
                   9605:   for(v=ncovcol+1; v <=ncovcol+nqv;v++){
                   9606:     DummyV[v]=1;
                   9607:     FixedV[v]=0;
                   9608:   }
                   9609:   for(v=ncovcol+nqv+1; v <=ncovcol+nqv+ntv;v++){
                   9610:     DummyV[v]=0;
                   9611:     FixedV[v]=1;
                   9612:   }
                   9613:   for(v=ncovcol+nqv+ntv+1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   9614:     DummyV[v]=1;
                   9615:     FixedV[v]=1;
                   9616:   }
                   9617:   for(v=1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   9618:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   9619:     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]);
                   9620:   }
1.126     brouard  9621: 
1.136     brouard  9622:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  9623:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   9624:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  9625:   }
1.126     brouard  9626: 
1.302     brouard  9627:     /* Is it a BOM UTF-8 Windows file? */
                   9628:   /* First data line */
                   9629:   linei=0;
                   9630:   while(fgets(line, MAXLINE, fic)) {
                   9631:     noffset=0;
                   9632:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   9633:     {
                   9634:       noffset=noffset+3;
                   9635:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   9636:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   9637:       fflush(ficlog); return 1;
                   9638:     }
                   9639:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   9640:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   9641:     {
                   9642:       noffset=noffset+2;
1.304     brouard  9643:       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);
                   9644:       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  9645:       fflush(ficlog); return 1;
                   9646:     }
                   9647:     else if( line[0] == 0 && line[1] == 0)
                   9648:     {
                   9649:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   9650:        noffset=noffset+4;
1.304     brouard  9651:        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);
                   9652:        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  9653:        fflush(ficlog); return 1;
                   9654:       }
                   9655:     } else{
                   9656:       ;/*printf(" Not a BOM file\n");*/
                   9657:     }
                   9658:         /* If line starts with a # it is a comment */
                   9659:     if (line[noffset] == '#') {
                   9660:       linei=linei+1;
                   9661:       break;
                   9662:     }else{
                   9663:       break;
                   9664:     }
                   9665:   }
                   9666:   fclose(fic);
                   9667:   if((fic=fopen(datafile,"r"))==NULL)    {
                   9668:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   9669:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   9670:   }
                   9671:   /* Not a Bom file */
                   9672:   
1.136     brouard  9673:   i=1;
                   9674:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   9675:     linei=linei+1;
                   9676:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   9677:       if(line[j] == '\t')
                   9678:        line[j] = ' ';
                   9679:     }
                   9680:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   9681:       ;
                   9682:     };
                   9683:     line[j+1]=0;  /* Trims blanks at end of line */
                   9684:     if(line[0]=='#'){
                   9685:       fprintf(ficlog,"Comment line\n%s\n",line);
                   9686:       printf("Comment line\n%s\n",line);
                   9687:       continue;
                   9688:     }
                   9689:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  9690:     strcpy(line, linetmp);
1.223     brouard  9691:     
                   9692:     /* Loops on waves */
                   9693:     for (j=maxwav;j>=1;j--){
                   9694:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  9695:        cutv(stra, strb, line, ' '); 
                   9696:        if(strb[0]=='.') { /* Missing value */
                   9697:          lval=-1;
                   9698:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
                   9699:          cotvar[j][ntv+iv][i]=-1; /* For performance reasons */
                   9700:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   9701:            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);
                   9702:            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);
                   9703:            return 1;
                   9704:          }
                   9705:        }else{
                   9706:          errno=0;
                   9707:          /* what_kind_of_number(strb); */
                   9708:          dval=strtod(strb,&endptr); 
                   9709:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   9710:          /* if(strb != endptr && *endptr == '\0') */
                   9711:          /*    dval=dlval; */
                   9712:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   9713:          if( strb[0]=='\0' || (*endptr != '\0')){
                   9714:            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);
                   9715:            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);
                   9716:            return 1;
                   9717:          }
                   9718:          cotqvar[j][iv][i]=dval; 
                   9719:          cotvar[j][ntv+iv][i]=dval; 
                   9720:        }
                   9721:        strcpy(line,stra);
1.223     brouard  9722:       }/* end loop ntqv */
1.225     brouard  9723:       
1.223     brouard  9724:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  9725:        cutv(stra, strb, line, ' '); 
                   9726:        if(strb[0]=='.') { /* Missing value */
                   9727:          lval=-1;
                   9728:        }else{
                   9729:          errno=0;
                   9730:          lval=strtol(strb,&endptr,10); 
                   9731:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   9732:          if( strb[0]=='\0' || (*endptr != '\0')){
                   9733:            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);
                   9734:            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);
                   9735:            return 1;
                   9736:          }
                   9737:        }
                   9738:        if(lval <-1 || lval >1){
                   9739:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  9740:  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  9741:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  9742:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9743:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9744:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  9745:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  9746:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  9747:  Exiting.\n",lval,linei, i,line,iv,j);
1.238     brouard  9748:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  9749:  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  9750:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  9751:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9752:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9753:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  9754:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  9755:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  9756:  Exiting.\n",lval,linei, i,line,iv,j);fflush(ficlog);
1.238     brouard  9757:          return 1;
                   9758:        }
                   9759:        cotvar[j][iv][i]=(double)(lval);
                   9760:        strcpy(line,stra);
1.223     brouard  9761:       }/* end loop ntv */
1.225     brouard  9762:       
1.223     brouard  9763:       /* Statuses  at wave */
1.137     brouard  9764:       cutv(stra, strb, line, ' '); 
1.223     brouard  9765:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  9766:        lval=-1;
1.136     brouard  9767:       }else{
1.238     brouard  9768:        errno=0;
                   9769:        lval=strtol(strb,&endptr,10); 
                   9770:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   9771:        if( strb[0]=='\0' || (*endptr != '\0')){
                   9772:          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);
                   9773:          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);
                   9774:          return 1;
                   9775:        }
1.136     brouard  9776:       }
1.225     brouard  9777:       
1.136     brouard  9778:       s[j][i]=lval;
1.225     brouard  9779:       
1.223     brouard  9780:       /* Date of Interview */
1.136     brouard  9781:       strcpy(line,stra);
                   9782:       cutv(stra, strb,line,' ');
1.169     brouard  9783:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9784:       }
1.169     brouard  9785:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  9786:        month=99;
                   9787:        year=9999;
1.136     brouard  9788:       }else{
1.225     brouard  9789:        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);
                   9790:        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);
                   9791:        return 1;
1.136     brouard  9792:       }
                   9793:       anint[j][i]= (double) year; 
1.302     brouard  9794:       mint[j][i]= (double)month;
                   9795:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   9796:       /*       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]); */
                   9797:       /*       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]); */
                   9798:       /* } */
1.136     brouard  9799:       strcpy(line,stra);
1.223     brouard  9800:     } /* End loop on waves */
1.225     brouard  9801:     
1.223     brouard  9802:     /* Date of death */
1.136     brouard  9803:     cutv(stra, strb,line,' '); 
1.169     brouard  9804:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9805:     }
1.169     brouard  9806:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  9807:       month=99;
                   9808:       year=9999;
                   9809:     }else{
1.141     brouard  9810:       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  9811:       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);
                   9812:       return 1;
1.136     brouard  9813:     }
                   9814:     andc[i]=(double) year; 
                   9815:     moisdc[i]=(double) month; 
                   9816:     strcpy(line,stra);
                   9817:     
1.223     brouard  9818:     /* Date of birth */
1.136     brouard  9819:     cutv(stra, strb,line,' '); 
1.169     brouard  9820:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9821:     }
1.169     brouard  9822:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  9823:       month=99;
                   9824:       year=9999;
                   9825:     }else{
1.141     brouard  9826:       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);
                   9827:       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  9828:       return 1;
1.136     brouard  9829:     }
                   9830:     if (year==9999) {
1.141     brouard  9831:       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);
                   9832:       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  9833:       return 1;
                   9834:       
1.136     brouard  9835:     }
                   9836:     annais[i]=(double)(year);
1.302     brouard  9837:     moisnais[i]=(double)(month);
                   9838:     for (j=1;j<=maxwav;j++){
                   9839:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   9840:        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]);
                   9841:        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]);
                   9842:       }
                   9843:     }
                   9844: 
1.136     brouard  9845:     strcpy(line,stra);
1.225     brouard  9846:     
1.223     brouard  9847:     /* Sample weight */
1.136     brouard  9848:     cutv(stra, strb,line,' '); 
                   9849:     errno=0;
                   9850:     dval=strtod(strb,&endptr); 
                   9851:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  9852:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   9853:       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  9854:       fflush(ficlog);
                   9855:       return 1;
                   9856:     }
                   9857:     weight[i]=dval; 
                   9858:     strcpy(line,stra);
1.225     brouard  9859:     
1.223     brouard  9860:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   9861:       cutv(stra, strb, line, ' '); 
                   9862:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  9863:        lval=-1;
1.311     brouard  9864:        coqvar[iv][i]=NAN; 
                   9865:        covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  9866:       }else{
1.225     brouard  9867:        errno=0;
                   9868:        /* what_kind_of_number(strb); */
                   9869:        dval=strtod(strb,&endptr);
                   9870:        /* if(strb != endptr && *endptr == '\0') */
                   9871:        /*   dval=dlval; */
                   9872:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   9873:        if( strb[0]=='\0' || (*endptr != '\0')){
                   9874:          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);
                   9875:          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);
                   9876:          return 1;
                   9877:        }
                   9878:        coqvar[iv][i]=dval; 
1.226     brouard  9879:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  9880:       }
                   9881:       strcpy(line,stra);
                   9882:     }/* end loop nqv */
1.136     brouard  9883:     
1.223     brouard  9884:     /* Covariate values */
1.136     brouard  9885:     for (j=ncovcol;j>=1;j--){
                   9886:       cutv(stra, strb,line,' '); 
1.223     brouard  9887:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  9888:        lval=-1;
1.136     brouard  9889:       }else{
1.225     brouard  9890:        errno=0;
                   9891:        lval=strtol(strb,&endptr,10); 
                   9892:        if( strb[0]=='\0' || (*endptr != '\0')){
                   9893:          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);
                   9894:          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);
                   9895:          return 1;
                   9896:        }
1.136     brouard  9897:       }
                   9898:       if(lval <-1 || lval >1){
1.225     brouard  9899:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  9900:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9901:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  9902:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9903:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9904:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  9905:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  9906:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  9907:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  9908:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  9909:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9910:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  9911:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9912:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9913:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  9914:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  9915:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  9916:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  9917:        return 1;
1.136     brouard  9918:       }
                   9919:       covar[j][i]=(double)(lval);
                   9920:       strcpy(line,stra);
                   9921:     }  
                   9922:     lstra=strlen(stra);
1.225     brouard  9923:     
1.136     brouard  9924:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   9925:       stratrunc = &(stra[lstra-9]);
                   9926:       num[i]=atol(stratrunc);
                   9927:     }
                   9928:     else
                   9929:       num[i]=atol(stra);
                   9930:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   9931:       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;}*/
                   9932:     
                   9933:     i=i+1;
                   9934:   } /* End loop reading  data */
1.225     brouard  9935:   
1.136     brouard  9936:   *imax=i-1; /* Number of individuals */
                   9937:   fclose(fic);
1.225     brouard  9938:   
1.136     brouard  9939:   return (0);
1.164     brouard  9940:   /* endread: */
1.225     brouard  9941:   printf("Exiting readdata: ");
                   9942:   fclose(fic);
                   9943:   return (1);
1.223     brouard  9944: }
1.126     brouard  9945: 
1.234     brouard  9946: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  9947:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  9948:   while (*p2 == ' ')
1.234     brouard  9949:     p2++; 
                   9950:   /* while ((*p1++ = *p2++) !=0) */
                   9951:   /*   ; */
                   9952:   /* do */
                   9953:   /*   while (*p2 == ' ') */
                   9954:   /*     p2++; */
                   9955:   /* while (*p1++ == *p2++); */
                   9956:   *stri=p2; 
1.145     brouard  9957: }
                   9958: 
1.235     brouard  9959: int decoderesult ( char resultline[], int nres)
1.230     brouard  9960: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   9961: {
1.235     brouard  9962:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  9963:   char resultsav[MAXLINE];
1.234     brouard  9964:   int resultmodel[MAXLINE];
                   9965:   int modelresult[MAXLINE];
1.230     brouard  9966:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   9967: 
1.234     brouard  9968:   removefirstspace(&resultline);
1.230     brouard  9969: 
                   9970:   if (strstr(resultline,"v") !=0){
                   9971:     printf("Error. 'v' must be in upper case 'V' result: %s ",resultline);
                   9972:     fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultline);fflush(ficlog);
                   9973:     return 1;
                   9974:   }
                   9975:   trimbb(resultsav, resultline);
                   9976:   if (strlen(resultsav) >1){
                   9977:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' */
                   9978:   }
1.253     brouard  9979:   if(j == 0){ /* Resultline but no = */
                   9980:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   9981:     return (0);
                   9982:   }
1.234     brouard  9983:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
1.318     brouard  9984:     printf("ERROR: the number of variables in this result line, %d, differs from the number of variables used in the model line, %d.\n",j, cptcovs);
1.310     brouard  9985:     fprintf(ficlog,"ERROR: the number of variables in the resultline, %d, differs from the number of variables used in the model line, %d.\n",j, cptcovs);
1.234     brouard  9986:   }
                   9987:   for(k=1; k<=j;k++){ /* Loop on any covariate of the result line */
                   9988:     if(nbocc(resultsav,'=') >1){
1.318     brouard  9989:       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" */
                   9990:       cutl(strc,strd,strb,'=');  /* strb:"V4=1" strc="1" strd="V4" */
1.234     brouard  9991:     }else
                   9992:       cutl(strc,strd,resultsav,'=');
1.318     brouard  9993:     Tvalsel[k]=atof(strc); /* 1 */ /* Tvalsel of k is the float value of the kth covariate appearing in this result line */
1.234     brouard  9994:     
1.230     brouard  9995:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
1.318     brouard  9996:     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  9997:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   9998:     /* cptcovsel++;     */
                   9999:     if (nbocc(stra,'=') >0)
                   10000:       strcpy(resultsav,stra); /* and analyzes it */
                   10001:   }
1.235     brouard  10002:   /* Checking for missing or useless values in comparison of current model needs */
1.318     brouard  10003:   for(k1=1; k1<= cptcovt ;k1++){ /* Loop on model. model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   10004:     if(Typevar[k1]==0){ /* Single covariate in model *//*0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.234     brouard  10005:       match=0;
1.318     brouard  10006:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10007:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.236     brouard  10008:          modelresult[k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.318     brouard  10009:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
1.234     brouard  10010:          break;
                   10011:        }
                   10012:       }
                   10013:       if(match == 0){
1.310     brouard  10014:        printf("Error in result line: V%d is missing in result: %s according to model=%s\n",k1, resultline, model);
                   10015:        fprintf(ficlog,"Error in result line: V%d is missing in result: %s according to model=%s\n",k1, resultline, model);
                   10016:        return 1;
1.234     brouard  10017:       }
                   10018:     }
                   10019:   }
1.235     brouard  10020:   /* Checking for missing or useless values in comparison of current model needs */
1.318     brouard  10021:   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  10022:     match=0;
1.318     brouard  10023:     for(k1=1; k1<= cptcovt ;k1++){ /* loop on model: model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.235     brouard  10024:       if(Typevar[k1]==0){ /* Single */
1.237     brouard  10025:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4   */
1.318     brouard  10026:          resultmodel[k1]=k2;  /* k2th variable of the model corresponds to k1 variable of the model. resultmodel[2]=1 resultmodel[1]=2  resultmodel[3]=3  resultmodel[6]=4 resultmodel[9]=5 */
1.234     brouard  10027:          ++match;
                   10028:        }
                   10029:       }
                   10030:     }
                   10031:     if(match == 0){
                   10032:       printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
1.310     brouard  10033:       fprintf(ficlog,"Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
                   10034:       return 1;
1.234     brouard  10035:     }else if(match > 1){
                   10036:       printf("Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
1.310     brouard  10037:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
                   10038:       return 1;
1.234     brouard  10039:     }
                   10040:   }
1.235     brouard  10041:       
1.234     brouard  10042:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  10043:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   10044:   /* result line V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   10045:   /* should give a combination of dummy V4=1, V3=0, V1=1 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 5 + (1offset) = 6*/
                   10046:   /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10047:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   10048:   /*    1 0 0 0 */
                   10049:   /*    2 1 0 0 */
                   10050:   /*    3 0 1 0 */ 
                   10051:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 */
                   10052:   /*    5 0 0 1 */
                   10053:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 */
                   10054:   /*    7 0 1 1 */
                   10055:   /*    8 1 1 1 */
1.237     brouard  10056:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   10057:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   10058:   /* V5*age V5 known which value for nres?  */
                   10059:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.318     brouard  10060:   for(k1=1, k=0, k4=0, k4q=0; k1 <=cptcovt;k1++){ /* loop on model line */
1.235     brouard  10061:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Single dummy */
1.237     brouard  10062:       k3= resultmodel[k1]; /* resultmodel[2(V4)] = 1=k3 */
1.235     brouard  10063:       k2=(int)Tvarsel[k3]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
                   10064:       k+=Tvalsel[k3]*pow(2,k4);  /*  Tvalsel[1]=1  */
1.237     brouard  10065:       Tresult[nres][k4+1]=Tvalsel[k3];/* Tresult[nres][1]=1(V4=1)  Tresult[nres][2]=0(V3=0) */
                   10066:       Tvresult[nres][k4+1]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   10067:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.235     brouard  10068:       printf("Decoderesult Dummy k=%d, V(k2=V%d)= Tvalsel[%d]=%d, 2**(%d)\n",k, k2, k3, (int)Tvalsel[k3], k4);
                   10069:       k4++;;
                   10070:     }  else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Single quantitative */
1.318     brouard  10071:       k3q= resultmodel[k1]; /* resultmodel[1(V5)] = 25.1=k3q */
                   10072:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.237     brouard  10073:       Tqresult[nres][k4q+1]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   10074:       Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
                   10075:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.235     brouard  10076:       printf("Decoderesult Quantitative nres=%d, V(k2q=V%d)= Tvalsel[%d]=%d, Tvarsel[%d]=%f\n",nres, k2q, k3q, Tvarsel[k3q], k3q, Tvalsel[k3q]);
                   10077:       k4q++;;
                   10078:     }
                   10079:   }
1.234     brouard  10080:   
1.235     brouard  10081:   TKresult[nres]=++k; /* Combination for the nresult and the model */
1.230     brouard  10082:   return (0);
                   10083: }
1.235     brouard  10084: 
1.230     brouard  10085: int decodemodel( char model[], int lastobs)
                   10086:  /**< This routine decodes the model and returns:
1.224     brouard  10087:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   10088:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   10089:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   10090:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   10091:        * - cptcovage number of covariates with age*products =2
                   10092:        * - cptcovs number of simple covariates
                   10093:        * - 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
                   10094:        *     which is a new column after the 9 (ncovcol) variables. 
1.319     brouard  10095:        * - if k is a product Vn*Vm, covar[k][i] is filled with correct values for each individual
1.224     brouard  10096:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   10097:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   10098:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   10099:        */
1.319     brouard  10100: /* 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  10101: {
1.238     brouard  10102:   int i, j, k, ks, v;
1.227     brouard  10103:   int  j1, k1, k2, k3, k4;
1.136     brouard  10104:   char modelsav[80];
1.145     brouard  10105:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  10106:   char *strpt;
1.136     brouard  10107: 
1.145     brouard  10108:   /*removespace(model);*/
1.136     brouard  10109:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  10110:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  10111:     if (strstr(model,"AGE") !=0){
1.192     brouard  10112:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   10113:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  10114:       return 1;
                   10115:     }
1.141     brouard  10116:     if (strstr(model,"v") !=0){
                   10117:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   10118:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   10119:       return 1;
                   10120:     }
1.187     brouard  10121:     strcpy(modelsav,model); 
                   10122:     if ((strpt=strstr(model,"age*age")) !=0){
                   10123:       printf(" strpt=%s, model=%s\n",strpt, model);
                   10124:       if(strpt != model){
1.234     brouard  10125:        printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  10126:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  10127:  corresponding column of parameters.\n",model);
1.234     brouard  10128:        fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  10129:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  10130:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  10131:        return 1;
1.225     brouard  10132:       }
1.187     brouard  10133:       nagesqr=1;
                   10134:       if (strstr(model,"+age*age") !=0)
1.234     brouard  10135:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  10136:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  10137:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  10138:       else 
1.234     brouard  10139:        substrchaine(modelsav, model, "age*age");
1.187     brouard  10140:     }else
                   10141:       nagesqr=0;
                   10142:     if (strlen(modelsav) >1){
                   10143:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   10144:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224     brouard  10145:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  10146:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  10147:                     * cst, age and age*age 
                   10148:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   10149:       /* including age products which are counted in cptcovage.
                   10150:        * but the covariates which are products must be treated 
                   10151:        * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  10152:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   10153:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.225     brouard  10154:       
                   10155:       
1.187     brouard  10156:       /*   Design
                   10157:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   10158:        *  <          ncovcol=8                >
                   10159:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   10160:        *   k=  1    2      3       4     5       6      7        8
                   10161:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   10162:        *  covar[k,i], value of kth covariate if not including age for individual i:
1.224     brouard  10163:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   10164:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  10165:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   10166:        *  Tage[++cptcovage]=k
                   10167:        *       if products, new covar are created after ncovcol with k1
                   10168:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   10169:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   10170:        *  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
                   10171:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   10172:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   10173:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   10174:        *  <          ncovcol=8                >
                   10175:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   10176:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   10177:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
1.319     brouard  10178:        * p Tvar[1]@12={2,   1,     3,      3,  11,     10,     8,       8,   7,   8,   5,  6}
1.187     brouard  10179:        * p Tprod[1]@2={                         6, 5}
                   10180:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   10181:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   10182:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1.319     brouard  10183:        *How to reorganize? Tvars(orted)
1.187     brouard  10184:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   10185:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   10186:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   10187:        * Struct []
                   10188:        */
1.225     brouard  10189:       
1.187     brouard  10190:       /* This loop fills the array Tvar from the string 'model'.*/
                   10191:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   10192:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   10193:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   10194:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   10195:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   10196:       /*       k=1 Tvar[1]=2 (from V2) */
                   10197:       /*       k=5 Tvar[5] */
                   10198:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  10199:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  10200:       /*       } */
1.198     brouard  10201:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  10202:       /*
                   10203:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  10204:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   10205:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   10206:       }
1.187     brouard  10207:       cptcovage=0;
1.319     brouard  10208:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model line */
                   10209:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' cutl from left to right
                   10210:                                         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" */
                   10211:        if (nbocc(modelsav,'+')==0)
                   10212:          strcpy(strb,modelsav); /* and analyzes it */
1.234     brouard  10213:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   10214:        /*scanf("%d",i);*/
1.319     brouard  10215:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V5*age+ V4+V3*age strb=V3*age */
                   10216:          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  10217:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   10218:            /* covar is not filled and then is empty */
                   10219:            cptcovprod--;
                   10220:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
1.319     brouard  10221:            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  10222:            Typevar[k]=1;  /* 1 for age product */
1.319     brouard  10223:            cptcovage++; /* Counts the number of covariates which include age as a product */
                   10224:            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  10225:            /*printf("stre=%s ", stre);*/
                   10226:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   10227:            cptcovprod--;
                   10228:            cutl(stre,strb,strc,'V');
                   10229:            Tvar[k]=atoi(stre);
                   10230:            Typevar[k]=1;  /* 1 for age product */
                   10231:            cptcovage++;
                   10232:            Tage[cptcovage]=k;
                   10233:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   10234:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   10235:            cptcovn++;
                   10236:            cptcovprodnoage++;k1++;
                   10237:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   10238:            Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* For model-covariate k tells which data-covariate to use but
                   10239:                                                because this model-covariate is a construction we invent a new column
                   10240:                                                which is after existing variables ncovcol+nqv+ntv+nqtv + k1
1.319     brouard  10241:                                                If already ncovcol=4 and model=V2 + V1 +V1*V4 +age*V3 +V3*V2
                   10242:                                                thus after V4 we invent V5 and V6 because age*V3 will be computed in 4
                   10243:                                                Tvar[3=V1*V4]=4+1=5 Tvar[5=V3*V2]=4 + 2= 6, Tvar[4=age*V3]=4 etc */
1.234     brouard  10244:            Typevar[k]=2;  /* 2 for double fixed dummy covariates */
                   10245:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   10246:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
1.319     brouard  10247:            Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 */
1.234     brouard  10248:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   10249:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   10250:            k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   10251:            /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   10252:            /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
1.225     brouard  10253:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
1.234     brouard  10254:            /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   10255:            for (i=1; i<=lastobs;i++){
                   10256:              /* Computes the new covariate which is a product of
                   10257:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   10258:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   10259:            }
                   10260:          } /* End age is not in the model */
                   10261:        } /* End if model includes a product */
1.319     brouard  10262:        else { /* not a product */
1.234     brouard  10263:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   10264:          /*  scanf("%d",i);*/
                   10265:          cutl(strd,strc,strb,'V');
                   10266:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   10267:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   10268:          Tvar[k]=atoi(strd);
                   10269:          Typevar[k]=0;  /* 0 for simple covariates */
                   10270:        }
                   10271:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  10272:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  10273:                                  scanf("%d",i);*/
1.187     brouard  10274:       } /* end of loop + on total covariates */
                   10275:     } /* end if strlen(modelsave == 0) age*age might exist */
                   10276:   } /* end if strlen(model == 0) */
1.136     brouard  10277:   
                   10278:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   10279:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  10280:   
1.136     brouard  10281:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  10282:      printf("cptcovprod=%d ", cptcovprod);
                   10283:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   10284:      scanf("%d ",i);*/
                   10285: 
                   10286: 
1.230     brouard  10287: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   10288:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  10289: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   10290:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   10291:    k =           1    2   3     4       5       6      7      8        9
                   10292:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
1.319     brouard  10293:    Typevar[k]=   0    0   0     2       1       0      2      1        0
1.227     brouard  10294:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   10295:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   10296:          Tmodelind[combination of covar]=k;
1.225     brouard  10297: */  
                   10298: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  10299:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  10300:   /* 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  10301:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.318     brouard  10302:   printf("Model=1+age+%s\n\
1.227     brouard  10303: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   10304: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   10305: 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  10306:   fprintf(ficlog,"Model=1+age+%s\n\
1.227     brouard  10307: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   10308: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   10309: 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  10310:   for(k=-1;k<=cptcovt; k++){ Fixed[k]=0; Dummy[k]=0;}
1.234     brouard  10311:   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 */
                   10312:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  10313:       Fixed[k]= 0;
                   10314:       Dummy[k]= 0;
1.225     brouard  10315:       ncoveff++;
1.232     brouard  10316:       ncovf++;
1.234     brouard  10317:       nsd++;
                   10318:       modell[k].maintype= FTYPE;
                   10319:       TvarsD[nsd]=Tvar[k];
                   10320:       TvarsDind[nsd]=k;
                   10321:       TvarF[ncovf]=Tvar[k];
                   10322:       TvarFind[ncovf]=k;
                   10323:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   10324:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   10325:     }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /* Product of fixed dummy (<=ncovcol) covariates */
                   10326:       Fixed[k]= 0;
                   10327:       Dummy[k]= 0;
                   10328:       ncoveff++;
                   10329:       ncovf++;
                   10330:       modell[k].maintype= FTYPE;
                   10331:       TvarF[ncovf]=Tvar[k];
                   10332:       TvarFind[ncovf]=k;
1.230     brouard  10333:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  10334:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.240     brouard  10335:     }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  10336:       Fixed[k]= 0;
                   10337:       Dummy[k]= 1;
1.230     brouard  10338:       nqfveff++;
1.234     brouard  10339:       modell[k].maintype= FTYPE;
                   10340:       modell[k].subtype= FQ;
                   10341:       nsq++;
                   10342:       TvarsQ[nsq]=Tvar[k];
                   10343:       TvarsQind[nsq]=k;
1.232     brouard  10344:       ncovf++;
1.234     brouard  10345:       TvarF[ncovf]=Tvar[k];
                   10346:       TvarFind[ncovf]=k;
1.231     brouard  10347:       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  10348:       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  10349:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.227     brouard  10350:       Fixed[k]= 1;
                   10351:       Dummy[k]= 0;
1.225     brouard  10352:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  10353:       modell[k].maintype= VTYPE;
                   10354:       modell[k].subtype= VD;
                   10355:       nsd++;
                   10356:       TvarsD[nsd]=Tvar[k];
                   10357:       TvarsDind[nsd]=k;
                   10358:       ncovv++; /* Only simple time varying variables */
                   10359:       TvarV[ncovv]=Tvar[k];
1.242     brouard  10360:       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  10361:       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 */
                   10362:       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  10363:       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);
                   10364:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  10365:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.234     brouard  10366:       Fixed[k]= 1;
                   10367:       Dummy[k]= 1;
                   10368:       nqtveff++;
                   10369:       modell[k].maintype= VTYPE;
                   10370:       modell[k].subtype= VQ;
                   10371:       ncovv++; /* Only simple time varying variables */
                   10372:       nsq++;
1.319     brouard  10373:       TvarsQ[nsq]=Tvar[k]; /* k=1 Tvar=5 nsq=1 TvarsQ[1]=5 */
1.234     brouard  10374:       TvarsQind[nsq]=k;
                   10375:       TvarV[ncovv]=Tvar[k];
1.242     brouard  10376:       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  10377:       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 */
                   10378:       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  10379:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   10380:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
                   10381:       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  10382:       printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv);
1.227     brouard  10383:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  10384:       ncova++;
                   10385:       TvarA[ncova]=Tvar[k];
                   10386:       TvarAind[ncova]=k;
1.231     brouard  10387:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  10388:        Fixed[k]= 2;
                   10389:        Dummy[k]= 2;
                   10390:        modell[k].maintype= ATYPE;
                   10391:        modell[k].subtype= APFD;
                   10392:        /* ncoveff++; */
1.227     brouard  10393:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  10394:        Fixed[k]= 2;
                   10395:        Dummy[k]= 3;
                   10396:        modell[k].maintype= ATYPE;
                   10397:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   10398:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  10399:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  10400:        Fixed[k]= 3;
                   10401:        Dummy[k]= 2;
                   10402:        modell[k].maintype= ATYPE;
                   10403:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   10404:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  10405:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  10406:        Fixed[k]= 3;
                   10407:        Dummy[k]= 3;
                   10408:        modell[k].maintype= ATYPE;
                   10409:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   10410:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  10411:       }
                   10412:     }else if (Typevar[k] == 2) {  /* product without age */
                   10413:       k1=Tposprod[k];
                   10414:       if(Tvard[k1][1] <=ncovcol){
1.240     brouard  10415:        if(Tvard[k1][2] <=ncovcol){
                   10416:          Fixed[k]= 1;
                   10417:          Dummy[k]= 0;
                   10418:          modell[k].maintype= FTYPE;
                   10419:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
                   10420:          ncovf++; /* Fixed variables without age */
                   10421:          TvarF[ncovf]=Tvar[k];
                   10422:          TvarFind[ncovf]=k;
                   10423:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10424:          Fixed[k]= 0;  /* or 2 ?*/
                   10425:          Dummy[k]= 1;
                   10426:          modell[k].maintype= FTYPE;
                   10427:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
                   10428:          ncovf++; /* Varying variables without age */
                   10429:          TvarF[ncovf]=Tvar[k];
                   10430:          TvarFind[ncovf]=k;
                   10431:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10432:          Fixed[k]= 1;
                   10433:          Dummy[k]= 0;
                   10434:          modell[k].maintype= VTYPE;
                   10435:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
                   10436:          ncovv++; /* Varying variables without age */
                   10437:          TvarV[ncovv]=Tvar[k];
                   10438:          TvarVind[ncovv]=k;
                   10439:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10440:          Fixed[k]= 1;
                   10441:          Dummy[k]= 1;
                   10442:          modell[k].maintype= VTYPE;
                   10443:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
                   10444:          ncovv++; /* Varying variables without age */
                   10445:          TvarV[ncovv]=Tvar[k];
                   10446:          TvarVind[ncovv]=k;
                   10447:        }
1.227     brouard  10448:       }else if(Tvard[k1][1] <=ncovcol+nqv){
1.240     brouard  10449:        if(Tvard[k1][2] <=ncovcol){
                   10450:          Fixed[k]= 0;  /* or 2 ?*/
                   10451:          Dummy[k]= 1;
                   10452:          modell[k].maintype= FTYPE;
                   10453:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
                   10454:          ncovf++; /* Fixed variables without age */
                   10455:          TvarF[ncovf]=Tvar[k];
                   10456:          TvarFind[ncovf]=k;
                   10457:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10458:          Fixed[k]= 1;
                   10459:          Dummy[k]= 1;
                   10460:          modell[k].maintype= VTYPE;
                   10461:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
                   10462:          ncovv++; /* Varying variables without age */
                   10463:          TvarV[ncovv]=Tvar[k];
                   10464:          TvarVind[ncovv]=k;
                   10465:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10466:          Fixed[k]= 1;
                   10467:          Dummy[k]= 1;
                   10468:          modell[k].maintype= VTYPE;
                   10469:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
                   10470:          ncovv++; /* Varying variables without age */
                   10471:          TvarV[ncovv]=Tvar[k];
                   10472:          TvarVind[ncovv]=k;
                   10473:          ncovv++; /* Varying variables without age */
                   10474:          TvarV[ncovv]=Tvar[k];
                   10475:          TvarVind[ncovv]=k;
                   10476:        }
1.227     brouard  10477:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){
1.240     brouard  10478:        if(Tvard[k1][2] <=ncovcol){
                   10479:          Fixed[k]= 1;
                   10480:          Dummy[k]= 1;
                   10481:          modell[k].maintype= VTYPE;
                   10482:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
                   10483:          ncovv++; /* Varying variables without age */
                   10484:          TvarV[ncovv]=Tvar[k];
                   10485:          TvarVind[ncovv]=k;
                   10486:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10487:          Fixed[k]= 1;
                   10488:          Dummy[k]= 1;
                   10489:          modell[k].maintype= VTYPE;
                   10490:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
                   10491:          ncovv++; /* Varying variables without age */
                   10492:          TvarV[ncovv]=Tvar[k];
                   10493:          TvarVind[ncovv]=k;
                   10494:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10495:          Fixed[k]= 1;
                   10496:          Dummy[k]= 0;
                   10497:          modell[k].maintype= VTYPE;
                   10498:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
                   10499:          ncovv++; /* Varying variables without age */
                   10500:          TvarV[ncovv]=Tvar[k];
                   10501:          TvarVind[ncovv]=k;
                   10502:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10503:          Fixed[k]= 1;
                   10504:          Dummy[k]= 1;
                   10505:          modell[k].maintype= VTYPE;
                   10506:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
                   10507:          ncovv++; /* Varying variables without age */
                   10508:          TvarV[ncovv]=Tvar[k];
                   10509:          TvarVind[ncovv]=k;
                   10510:        }
1.227     brouard  10511:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  10512:        if(Tvard[k1][2] <=ncovcol){
                   10513:          Fixed[k]= 1;
                   10514:          Dummy[k]= 1;
                   10515:          modell[k].maintype= VTYPE;
                   10516:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
                   10517:          ncovv++; /* Varying variables without age */
                   10518:          TvarV[ncovv]=Tvar[k];
                   10519:          TvarVind[ncovv]=k;
                   10520:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10521:          Fixed[k]= 1;
                   10522:          Dummy[k]= 1;
                   10523:          modell[k].maintype= VTYPE;
                   10524:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
                   10525:          ncovv++; /* Varying variables without age */
                   10526:          TvarV[ncovv]=Tvar[k];
                   10527:          TvarVind[ncovv]=k;
                   10528:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10529:          Fixed[k]= 1;
                   10530:          Dummy[k]= 1;
                   10531:          modell[k].maintype= VTYPE;
                   10532:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
                   10533:          ncovv++; /* Varying variables without age */
                   10534:          TvarV[ncovv]=Tvar[k];
                   10535:          TvarVind[ncovv]=k;
                   10536:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10537:          Fixed[k]= 1;
                   10538:          Dummy[k]= 1;
                   10539:          modell[k].maintype= VTYPE;
                   10540:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
                   10541:          ncovv++; /* Varying variables without age */
                   10542:          TvarV[ncovv]=Tvar[k];
                   10543:          TvarVind[ncovv]=k;
                   10544:        }
1.227     brouard  10545:       }else{
1.240     brouard  10546:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   10547:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   10548:       } /*end k1*/
1.225     brouard  10549:     }else{
1.226     brouard  10550:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   10551:       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  10552:     }
1.227     brouard  10553:     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  10554:     printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype);
1.227     brouard  10555:     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]);
                   10556:   }
                   10557:   /* Searching for doublons in the model */
                   10558:   for(k1=1; k1<= cptcovt;k1++){
                   10559:     for(k2=1; k2 <k1;k2++){
1.285     brouard  10560:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   10561:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  10562:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   10563:          if(Tvar[k1]==Tvar[k2]){
1.285     brouard  10564:            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]);
                   10565:            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  10566:            return(1);
                   10567:          }
                   10568:        }else if (Typevar[k1] ==2){
                   10569:          k3=Tposprod[k1];
                   10570:          k4=Tposprod[k2];
                   10571:          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])) ){
                   10572:            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]]);
                   10573:            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);
                   10574:            return(1);
                   10575:          }
                   10576:        }
1.227     brouard  10577:       }
                   10578:     }
1.225     brouard  10579:   }
                   10580:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   10581:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  10582:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   10583:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.137     brouard  10584:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  10585:   /*endread:*/
1.225     brouard  10586:   printf("Exiting decodemodel: ");
                   10587:   return (1);
1.136     brouard  10588: }
                   10589: 
1.169     brouard  10590: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  10591: {/* Check ages at death */
1.136     brouard  10592:   int i, m;
1.218     brouard  10593:   int firstone=0;
                   10594:   
1.136     brouard  10595:   for (i=1; i<=imx; i++) {
                   10596:     for(m=2; (m<= maxwav); m++) {
                   10597:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   10598:        anint[m][i]=9999;
1.216     brouard  10599:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   10600:          s[m][i]=-1;
1.136     brouard  10601:       }
                   10602:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  10603:        *nberr = *nberr + 1;
1.218     brouard  10604:        if(firstone == 0){
                   10605:          firstone=1;
1.260     brouard  10606:        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  10607:        }
1.262     brouard  10608:        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  10609:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  10610:       }
                   10611:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  10612:        (*nberr)++;
1.259     brouard  10613:        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  10614:        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  10615:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  10616:       }
                   10617:     }
                   10618:   }
                   10619: 
                   10620:   for (i=1; i<=imx; i++)  {
                   10621:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   10622:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  10623:       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  10624:        if (s[m][i] >= nlstate+1) {
1.169     brouard  10625:          if(agedc[i]>0){
                   10626:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  10627:              agev[m][i]=agedc[i];
1.214     brouard  10628:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  10629:            }else {
1.136     brouard  10630:              if ((int)andc[i]!=9999){
                   10631:                nbwarn++;
                   10632:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   10633:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   10634:                agev[m][i]=-1;
                   10635:              }
                   10636:            }
1.169     brouard  10637:          } /* agedc > 0 */
1.214     brouard  10638:        } /* end if */
1.136     brouard  10639:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   10640:                                 years but with the precision of a month */
                   10641:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   10642:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   10643:            agev[m][i]=1;
                   10644:          else if(agev[m][i] < *agemin){ 
                   10645:            *agemin=agev[m][i];
                   10646:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   10647:          }
                   10648:          else if(agev[m][i] >*agemax){
                   10649:            *agemax=agev[m][i];
1.156     brouard  10650:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  10651:          }
                   10652:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   10653:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  10654:        } /* en if 9*/
1.136     brouard  10655:        else { /* =9 */
1.214     brouard  10656:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  10657:          agev[m][i]=1;
                   10658:          s[m][i]=-1;
                   10659:        }
                   10660:       }
1.214     brouard  10661:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  10662:        agev[m][i]=1;
1.214     brouard  10663:       else{
                   10664:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   10665:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   10666:        agev[m][i]=0;
                   10667:       }
                   10668:     } /* End for lastpass */
                   10669:   }
1.136     brouard  10670:     
                   10671:   for (i=1; i<=imx; i++)  {
                   10672:     for(m=firstpass; (m<=lastpass); m++){
                   10673:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  10674:        (*nberr)++;
1.136     brouard  10675:        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);     
                   10676:        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);     
                   10677:        return 1;
                   10678:       }
                   10679:     }
                   10680:   }
                   10681: 
                   10682:   /*for (i=1; i<=imx; i++){
                   10683:   for (m=firstpass; (m<lastpass); m++){
                   10684:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   10685: }
                   10686: 
                   10687: }*/
                   10688: 
                   10689: 
1.139     brouard  10690:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   10691:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  10692: 
                   10693:   return (0);
1.164     brouard  10694:  /* endread:*/
1.136     brouard  10695:     printf("Exiting calandcheckages: ");
                   10696:     return (1);
                   10697: }
                   10698: 
1.172     brouard  10699: #if defined(_MSC_VER)
                   10700: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   10701: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   10702: //#include "stdafx.h"
                   10703: //#include <stdio.h>
                   10704: //#include <tchar.h>
                   10705: //#include <windows.h>
                   10706: //#include <iostream>
                   10707: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   10708: 
                   10709: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   10710: 
                   10711: BOOL IsWow64()
                   10712: {
                   10713:        BOOL bIsWow64 = FALSE;
                   10714: 
                   10715:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   10716:        //  (HANDLE, PBOOL);
                   10717: 
                   10718:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   10719: 
                   10720:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   10721:        const char funcName[] = "IsWow64Process";
                   10722:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   10723:                GetProcAddress(module, funcName);
                   10724: 
                   10725:        if (NULL != fnIsWow64Process)
                   10726:        {
                   10727:                if (!fnIsWow64Process(GetCurrentProcess(),
                   10728:                        &bIsWow64))
                   10729:                        //throw std::exception("Unknown error");
                   10730:                        printf("Unknown error\n");
                   10731:        }
                   10732:        return bIsWow64 != FALSE;
                   10733: }
                   10734: #endif
1.177     brouard  10735: 
1.191     brouard  10736: void syscompilerinfo(int logged)
1.292     brouard  10737: {
                   10738: #include <stdint.h>
                   10739: 
                   10740:   /* #include "syscompilerinfo.h"*/
1.185     brouard  10741:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   10742:    /* /GS /W3 /Gy
                   10743:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   10744:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   10745:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  10746:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   10747:    */ 
                   10748:    /* 64 bits */
1.185     brouard  10749:    /*
                   10750:      /GS /W3 /Gy
                   10751:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   10752:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   10753:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   10754:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   10755:    /* Optimization are useless and O3 is slower than O2 */
                   10756:    /*
                   10757:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   10758:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   10759:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   10760:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   10761:    */
1.186     brouard  10762:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  10763:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   10764:       /PDB:"visual studio
                   10765:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   10766:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   10767:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   10768:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   10769:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   10770:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   10771:       uiAccess='false'"
                   10772:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   10773:       /NOLOGO /TLBID:1
                   10774:    */
1.292     brouard  10775: 
                   10776: 
1.177     brouard  10777: #if defined __INTEL_COMPILER
1.178     brouard  10778: #if defined(__GNUC__)
                   10779:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   10780: #endif
1.177     brouard  10781: #elif defined(__GNUC__) 
1.179     brouard  10782: #ifndef  __APPLE__
1.174     brouard  10783: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  10784: #endif
1.177     brouard  10785:    struct utsname sysInfo;
1.178     brouard  10786:    int cross = CROSS;
                   10787:    if (cross){
                   10788:           printf("Cross-");
1.191     brouard  10789:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  10790:    }
1.174     brouard  10791: #endif
                   10792: 
1.191     brouard  10793:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  10794: #if defined(__clang__)
1.191     brouard  10795:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  10796: #endif
                   10797: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  10798:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  10799: #endif
                   10800: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  10801:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  10802: #endif
                   10803: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  10804:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  10805: #endif
                   10806: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  10807:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  10808: #endif
                   10809: #if defined(_MSC_VER)
1.191     brouard  10810:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  10811: #endif
                   10812: #if defined(__PGI)
1.191     brouard  10813:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  10814: #endif
                   10815: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  10816:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  10817: #endif
1.191     brouard  10818:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  10819:    
1.167     brouard  10820: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   10821: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   10822:     // Windows (x64 and x86)
1.191     brouard  10823:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  10824: #elif __unix__ // all unices, not all compilers
                   10825:     // Unix
1.191     brouard  10826:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  10827: #elif __linux__
                   10828:     // linux
1.191     brouard  10829:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  10830: #elif __APPLE__
1.174     brouard  10831:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  10832:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  10833: #endif
                   10834: 
                   10835: /*  __MINGW32__          */
                   10836: /*  __CYGWIN__  */
                   10837: /* __MINGW64__  */
                   10838: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   10839: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   10840: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   10841: /* _WIN64  // Defined for applications for Win64. */
                   10842: /* _M_X64 // Defined for compilations that target x64 processors. */
                   10843: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  10844: 
1.167     brouard  10845: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  10846:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  10847: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  10848:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  10849: #else
1.191     brouard  10850:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  10851: #endif
                   10852: 
1.169     brouard  10853: #if defined(__GNUC__)
                   10854: # if defined(__GNUC_PATCHLEVEL__)
                   10855: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   10856:                             + __GNUC_MINOR__ * 100 \
                   10857:                             + __GNUC_PATCHLEVEL__)
                   10858: # else
                   10859: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   10860:                             + __GNUC_MINOR__ * 100)
                   10861: # endif
1.174     brouard  10862:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  10863:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  10864: 
                   10865:    if (uname(&sysInfo) != -1) {
                   10866:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  10867:         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  10868:    }
                   10869:    else
                   10870:       perror("uname() error");
1.179     brouard  10871:    //#ifndef __INTEL_COMPILER 
                   10872: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  10873:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  10874:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  10875: #endif
1.169     brouard  10876: #endif
1.172     brouard  10877: 
1.286     brouard  10878:    //   void main ()
1.172     brouard  10879:    //   {
1.169     brouard  10880: #if defined(_MSC_VER)
1.174     brouard  10881:    if (IsWow64()){
1.191     brouard  10882:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   10883:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  10884:    }
                   10885:    else{
1.191     brouard  10886:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   10887:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  10888:    }
1.172     brouard  10889:    //     printf("\nPress Enter to continue...");
                   10890:    //     getchar();
                   10891:    //   }
                   10892: 
1.169     brouard  10893: #endif
                   10894:    
1.167     brouard  10895: 
1.219     brouard  10896: }
1.136     brouard  10897: 
1.219     brouard  10898: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  10899:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.235     brouard  10900:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  10901:   /* double ftolpl = 1.e-10; */
1.180     brouard  10902:   double age, agebase, agelim;
1.203     brouard  10903:   double tot;
1.180     brouard  10904: 
1.202     brouard  10905:   strcpy(filerespl,"PL_");
                   10906:   strcat(filerespl,fileresu);
                   10907:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  10908:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   10909:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  10910:   }
1.288     brouard  10911:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   10912:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  10913:   pstamp(ficrespl);
1.288     brouard  10914:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  10915:   fprintf(ficrespl,"#Age ");
                   10916:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   10917:   fprintf(ficrespl,"\n");
1.180     brouard  10918:   
1.219     brouard  10919:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  10920: 
1.219     brouard  10921:   agebase=ageminpar;
                   10922:   agelim=agemaxpar;
1.180     brouard  10923: 
1.227     brouard  10924:   /* i1=pow(2,ncoveff); */
1.234     brouard  10925:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  10926:   if (cptcovn < 1){i1=1;}
1.180     brouard  10927: 
1.238     brouard  10928:   for(k=1; k<=i1;k++){ /* For each combination k of dummy covariates in the model */
                   10929:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  10930:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  10931:        continue;
1.235     brouard  10932: 
1.238     brouard  10933:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   10934:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   10935:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   10936:       /* k=k+1; */
                   10937:       /* to clean */
                   10938:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   10939:       fprintf(ficrespl,"#******");
                   10940:       printf("#******");
                   10941:       fprintf(ficlog,"#******");
                   10942:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   10943:        fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); /* Here problem for varying dummy*/
                   10944:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10945:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10946:       }
                   10947:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   10948:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10949:        fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10950:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10951:       }
                   10952:       fprintf(ficrespl,"******\n");
                   10953:       printf("******\n");
                   10954:       fprintf(ficlog,"******\n");
                   10955:       if(invalidvarcomb[k]){
                   10956:        printf("\nCombination (%d) ignored because no case \n",k); 
                   10957:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   10958:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   10959:        continue;
                   10960:       }
1.219     brouard  10961: 
1.238     brouard  10962:       fprintf(ficrespl,"#Age ");
                   10963:       for(j=1;j<=cptcoveff;j++) {
                   10964:        fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10965:       }
                   10966:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   10967:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  10968:     
1.238     brouard  10969:       for (age=agebase; age<=agelim; age++){
                   10970:        /* for (age=agebase; age<=agebase; age++){ */
                   10971:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres);
                   10972:        fprintf(ficrespl,"%.0f ",age );
                   10973:        for(j=1;j<=cptcoveff;j++)
                   10974:          fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10975:        tot=0.;
                   10976:        for(i=1; i<=nlstate;i++){
                   10977:          tot +=  prlim[i][i];
                   10978:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   10979:        }
                   10980:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   10981:       } /* Age */
                   10982:       /* was end of cptcod */
                   10983:     } /* cptcov */
                   10984:   } /* nres */
1.219     brouard  10985:   return 0;
1.180     brouard  10986: }
                   10987: 
1.218     brouard  10988: 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  10989:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  10990:        
                   10991:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   10992:    * at any age between ageminpar and agemaxpar
                   10993:         */
1.235     brouard  10994:   int i, j, k, i1, nres=0 ;
1.217     brouard  10995:   /* double ftolpl = 1.e-10; */
                   10996:   double age, agebase, agelim;
                   10997:   double tot;
1.218     brouard  10998:   /* double ***mobaverage; */
                   10999:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  11000: 
                   11001:   strcpy(fileresplb,"PLB_");
                   11002:   strcat(fileresplb,fileresu);
                   11003:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  11004:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   11005:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  11006:   }
1.288     brouard  11007:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   11008:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  11009:   pstamp(ficresplb);
1.288     brouard  11010:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  11011:   fprintf(ficresplb,"#Age ");
                   11012:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   11013:   fprintf(ficresplb,"\n");
                   11014:   
1.218     brouard  11015:   
                   11016:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   11017:   
                   11018:   agebase=ageminpar;
                   11019:   agelim=agemaxpar;
                   11020:   
                   11021:   
1.227     brouard  11022:   i1=pow(2,cptcoveff);
1.218     brouard  11023:   if (cptcovn < 1){i1=1;}
1.227     brouard  11024:   
1.238     brouard  11025:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11026:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  11027:      if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  11028:        continue;
                   11029:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   11030:       fprintf(ficresplb,"#******");
                   11031:       printf("#******");
                   11032:       fprintf(ficlog,"#******");
                   11033:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   11034:        fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11035:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11036:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11037:       }
                   11038:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11039:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11040:        fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11041:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11042:       }
                   11043:       fprintf(ficresplb,"******\n");
                   11044:       printf("******\n");
                   11045:       fprintf(ficlog,"******\n");
                   11046:       if(invalidvarcomb[k]){
                   11047:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   11048:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   11049:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   11050:        continue;
                   11051:       }
1.218     brouard  11052:     
1.238     brouard  11053:       fprintf(ficresplb,"#Age ");
                   11054:       for(j=1;j<=cptcoveff;j++) {
                   11055:        fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11056:       }
                   11057:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   11058:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  11059:     
                   11060:     
1.238     brouard  11061:       for (age=agebase; age<=agelim; age++){
                   11062:        /* for (age=agebase; age<=agebase; age++){ */
                   11063:        if(mobilavproj > 0){
                   11064:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   11065:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  11066:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  11067:        }else if (mobilavproj == 0){
                   11068:          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);
                   11069:          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);
                   11070:          exit(1);
                   11071:        }else{
                   11072:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  11073:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  11074:          /* printf("TOTOT\n"); */
                   11075:           /* exit(1); */
1.238     brouard  11076:        }
                   11077:        fprintf(ficresplb,"%.0f ",age );
                   11078:        for(j=1;j<=cptcoveff;j++)
                   11079:          fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11080:        tot=0.;
                   11081:        for(i=1; i<=nlstate;i++){
                   11082:          tot +=  bprlim[i][i];
                   11083:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   11084:        }
                   11085:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   11086:       } /* Age */
                   11087:       /* was end of cptcod */
1.255     brouard  11088:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.238     brouard  11089:     } /* end of any combination */
                   11090:   } /* end of nres */  
1.218     brouard  11091:   /* hBijx(p, bage, fage); */
                   11092:   /* fclose(ficrespijb); */
                   11093:   
                   11094:   return 0;
1.217     brouard  11095: }
1.218     brouard  11096:  
1.180     brouard  11097: int hPijx(double *p, int bage, int fage){
                   11098:     /*------------- h Pij x at various ages ------------*/
                   11099: 
                   11100:   int stepsize;
                   11101:   int agelim;
                   11102:   int hstepm;
                   11103:   int nhstepm;
1.235     brouard  11104:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  11105: 
                   11106:   double agedeb;
                   11107:   double ***p3mat;
                   11108: 
1.201     brouard  11109:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  11110:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   11111:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   11112:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   11113:     }
                   11114:     printf("Computing pij: result on file '%s' \n", filerespij);
                   11115:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   11116:   
                   11117:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   11118:     /*if (stepm<=24) stepsize=2;*/
                   11119: 
                   11120:     agelim=AGESUP;
                   11121:     hstepm=stepsize*YEARM; /* Every year of age */
                   11122:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
1.218     brouard  11123:                
1.180     brouard  11124:     /* hstepm=1;   aff par mois*/
                   11125:     pstamp(ficrespij);
                   11126:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
1.227     brouard  11127:     i1= pow(2,cptcoveff);
1.218     brouard  11128:                /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11129:                /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   11130:                /*      k=k+1;  */
1.235     brouard  11131:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   11132:     for(k=1; k<=i1;k++){
1.253     brouard  11133:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  11134:        continue;
1.183     brouard  11135:       fprintf(ficrespij,"\n#****** ");
1.227     brouard  11136:       for(j=1;j<=cptcoveff;j++) 
1.198     brouard  11137:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  11138:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   11139:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   11140:        fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   11141:       }
1.183     brouard  11142:       fprintf(ficrespij,"******\n");
                   11143:       
                   11144:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   11145:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   11146:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   11147:        
                   11148:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  11149:        
1.183     brouard  11150:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11151:        oldm=oldms;savm=savms;
1.235     brouard  11152:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
1.183     brouard  11153:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   11154:        for(i=1; i<=nlstate;i++)
                   11155:          for(j=1; j<=nlstate+ndeath;j++)
                   11156:            fprintf(ficrespij," %1d-%1d",i,j);
                   11157:        fprintf(ficrespij,"\n");
                   11158:        for (h=0; h<=nhstepm; h++){
                   11159:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   11160:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  11161:          for(i=1; i<=nlstate;i++)
                   11162:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  11163:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  11164:          fprintf(ficrespij,"\n");
                   11165:        }
1.183     brouard  11166:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11167:        fprintf(ficrespij,"\n");
                   11168:       }
1.180     brouard  11169:       /*}*/
                   11170:     }
1.218     brouard  11171:     return 0;
1.180     brouard  11172: }
1.218     brouard  11173:  
                   11174:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  11175:     /*------------- h Bij x at various ages ------------*/
                   11176: 
                   11177:   int stepsize;
1.218     brouard  11178:   /* int agelim; */
                   11179:        int ageminl;
1.217     brouard  11180:   int hstepm;
                   11181:   int nhstepm;
1.238     brouard  11182:   int h, i, i1, j, k, nres;
1.218     brouard  11183:        
1.217     brouard  11184:   double agedeb;
                   11185:   double ***p3mat;
1.218     brouard  11186:        
                   11187:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   11188:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   11189:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   11190:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   11191:   }
                   11192:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   11193:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   11194:   
                   11195:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   11196:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  11197:   
1.218     brouard  11198:   /* agelim=AGESUP; */
1.289     brouard  11199:   ageminl=AGEINF; /* was 30 */
1.218     brouard  11200:   hstepm=stepsize*YEARM; /* Every year of age */
                   11201:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   11202:   
                   11203:   /* hstepm=1;   aff par mois*/
                   11204:   pstamp(ficrespijb);
1.255     brouard  11205:   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  11206:   i1= pow(2,cptcoveff);
1.218     brouard  11207:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11208:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   11209:   /*   k=k+1;  */
1.238     brouard  11210:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11211:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  11212:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  11213:        continue;
                   11214:       fprintf(ficrespijb,"\n#****** ");
                   11215:       for(j=1;j<=cptcoveff;j++)
                   11216:        fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11217:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11218:        fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11219:       }
                   11220:       fprintf(ficrespijb,"******\n");
1.264     brouard  11221:       if(invalidvarcomb[k]){  /* Is it necessary here? */
1.238     brouard  11222:        fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   11223:        continue;
                   11224:       }
                   11225:       
                   11226:       /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   11227:       for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   11228:        /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
1.297     brouard  11229:        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 */
                   11230:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
1.238     brouard  11231:        
                   11232:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
                   11233:        
1.266     brouard  11234:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   11235:        /* and memory limitations if stepm is small */
                   11236: 
1.238     brouard  11237:        /* oldm=oldms;savm=savms; */
                   11238:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.325     brouard  11239:        hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);/* Bug valgrind */
1.238     brouard  11240:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
1.255     brouard  11241:        fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
1.217     brouard  11242:        for(i=1; i<=nlstate;i++)
                   11243:          for(j=1; j<=nlstate+ndeath;j++)
1.238     brouard  11244:            fprintf(ficrespijb," %1d-%1d",i,j);
1.217     brouard  11245:        fprintf(ficrespijb,"\n");
1.238     brouard  11246:        for (h=0; h<=nhstepm; h++){
                   11247:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   11248:          fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   11249:          /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
                   11250:          for(i=1; i<=nlstate;i++)
                   11251:            for(j=1; j<=nlstate+ndeath;j++)
1.325     brouard  11252:              fprintf(ficrespijb," %.5f", p3mat[i][j][h]);/* Bug valgrind */
1.238     brouard  11253:          fprintf(ficrespijb,"\n");
                   11254:        }
                   11255:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11256:        fprintf(ficrespijb,"\n");
                   11257:       } /* end age deb */
                   11258:     } /* end combination */
                   11259:   } /* end nres */
1.218     brouard  11260:   return 0;
                   11261:  } /*  hBijx */
1.217     brouard  11262: 
1.180     brouard  11263: 
1.136     brouard  11264: /***********************************************/
                   11265: /**************** Main Program *****************/
                   11266: /***********************************************/
                   11267: 
                   11268: int main(int argc, char *argv[])
                   11269: {
                   11270: #ifdef GSL
                   11271:   const gsl_multimin_fminimizer_type *T;
                   11272:   size_t iteri = 0, it;
                   11273:   int rval = GSL_CONTINUE;
                   11274:   int status = GSL_SUCCESS;
                   11275:   double ssval;
                   11276: #endif
                   11277:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  11278:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   11279:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  11280:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  11281:   int jj, ll, li, lj, lk;
1.136     brouard  11282:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  11283:   int num_filled;
1.136     brouard  11284:   int itimes;
                   11285:   int NDIM=2;
                   11286:   int vpopbased=0;
1.235     brouard  11287:   int nres=0;
1.258     brouard  11288:   int endishere=0;
1.277     brouard  11289:   int noffset=0;
1.274     brouard  11290:   int ncurrv=0; /* Temporary variable */
                   11291:   
1.164     brouard  11292:   char ca[32], cb[32];
1.136     brouard  11293:   /*  FILE *fichtm; *//* Html File */
                   11294:   /* FILE *ficgp;*/ /*Gnuplot File */
                   11295:   struct stat info;
1.191     brouard  11296:   double agedeb=0.;
1.194     brouard  11297: 
                   11298:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  11299:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  11300: 
1.165     brouard  11301:   double fret;
1.191     brouard  11302:   double dum=0.; /* Dummy variable */
1.136     brouard  11303:   double ***p3mat;
1.218     brouard  11304:   /* double ***mobaverage; */
1.319     brouard  11305:   double wald;
1.164     brouard  11306: 
                   11307:   char line[MAXLINE];
1.197     brouard  11308:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   11309: 
1.234     brouard  11310:   char  modeltemp[MAXLINE];
1.230     brouard  11311:   char resultline[MAXLINE];
                   11312:   
1.136     brouard  11313:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  11314:   char *tok, *val; /* pathtot */
1.290     brouard  11315:   int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs declared globally ;*/
1.195     brouard  11316:   int c,  h , cpt, c2;
1.191     brouard  11317:   int jl=0;
                   11318:   int i1, j1, jk, stepsize=0;
1.194     brouard  11319:   int count=0;
                   11320: 
1.164     brouard  11321:   int *tab; 
1.136     brouard  11322:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  11323:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   11324:   /* double anprojf, mprojf, jprojf; */
                   11325:   /* double jintmean,mintmean,aintmean;   */
                   11326:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   11327:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   11328:   double yrfproj= 10.0; /* Number of years of forward projections */
                   11329:   double yrbproj= 10.0; /* Number of years of backward projections */
                   11330:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  11331:   int mobilav=0,popforecast=0;
1.191     brouard  11332:   int hstepm=0, nhstepm=0;
1.136     brouard  11333:   int agemortsup;
                   11334:   float  sumlpop=0.;
                   11335:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   11336:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   11337: 
1.191     brouard  11338:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  11339:   double ftolpl=FTOL;
                   11340:   double **prlim;
1.217     brouard  11341:   double **bprlim;
1.317     brouard  11342:   double ***param; /* Matrix of parameters, param[i][j][k] param=ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel) 
                   11343:                     state of origin, state of destination including death, for each covariate: constante, age, and V1 V2 etc. */
1.251     brouard  11344:   double ***paramstart; /* Matrix of starting parameter values */
                   11345:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  11346:   double **matcov; /* Matrix of covariance */
1.203     brouard  11347:   double **hess; /* Hessian matrix */
1.136     brouard  11348:   double ***delti3; /* Scale */
                   11349:   double *delti; /* Scale */
                   11350:   double ***eij, ***vareij;
                   11351:   double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  11352: 
1.136     brouard  11353:   double *epj, vepp;
1.164     brouard  11354: 
1.273     brouard  11355:   double dateprev1, dateprev2;
1.296     brouard  11356:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   11357:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   11358: 
1.217     brouard  11359: 
1.136     brouard  11360:   double **ximort;
1.145     brouard  11361:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  11362:   int *dcwave;
                   11363: 
1.164     brouard  11364:   char z[1]="c";
1.136     brouard  11365: 
                   11366:   /*char  *strt;*/
                   11367:   char strtend[80];
1.126     brouard  11368: 
1.164     brouard  11369: 
1.126     brouard  11370: /*   setlocale (LC_ALL, ""); */
                   11371: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   11372: /*   textdomain (PACKAGE); */
                   11373: /*   setlocale (LC_CTYPE, ""); */
                   11374: /*   setlocale (LC_MESSAGES, ""); */
                   11375: 
                   11376:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  11377:   rstart_time = time(NULL);  
                   11378:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   11379:   start_time = *localtime(&rstart_time);
1.126     brouard  11380:   curr_time=start_time;
1.157     brouard  11381:   /*tml = *localtime(&start_time.tm_sec);*/
                   11382:   /* strcpy(strstart,asctime(&tml)); */
                   11383:   strcpy(strstart,asctime(&start_time));
1.126     brouard  11384: 
                   11385: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  11386: /*  tp.tm_sec = tp.tm_sec +86400; */
                   11387: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  11388: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   11389: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   11390: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  11391: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  11392: /*   strt=asctime(&tmg); */
                   11393: /*   printf("Time(after) =%s",strstart);  */
                   11394: /*  (void) time (&time_value);
                   11395: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   11396: *  tm = *localtime(&time_value);
                   11397: *  strstart=asctime(&tm);
                   11398: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   11399: */
                   11400: 
                   11401:   nberr=0; /* Number of errors and warnings */
                   11402:   nbwarn=0;
1.184     brouard  11403: #ifdef WIN32
                   11404:   _getcwd(pathcd, size);
                   11405: #else
1.126     brouard  11406:   getcwd(pathcd, size);
1.184     brouard  11407: #endif
1.191     brouard  11408:   syscompilerinfo(0);
1.196     brouard  11409:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  11410:   if(argc <=1){
                   11411:     printf("\nEnter the parameter file name: ");
1.205     brouard  11412:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   11413:       printf("ERROR Empty parameter file name\n");
                   11414:       goto end;
                   11415:     }
1.126     brouard  11416:     i=strlen(pathr);
                   11417:     if(pathr[i-1]=='\n')
                   11418:       pathr[i-1]='\0';
1.156     brouard  11419:     i=strlen(pathr);
1.205     brouard  11420:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  11421:       pathr[i-1]='\0';
1.205     brouard  11422:     }
                   11423:     i=strlen(pathr);
                   11424:     if( i==0 ){
                   11425:       printf("ERROR Empty parameter file name\n");
                   11426:       goto end;
                   11427:     }
                   11428:     for (tok = pathr; tok != NULL; ){
1.126     brouard  11429:       printf("Pathr |%s|\n",pathr);
                   11430:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   11431:       printf("val= |%s| pathr=%s\n",val,pathr);
                   11432:       strcpy (pathtot, val);
                   11433:       if(pathr[0] == '\0') break; /* Dirty */
                   11434:     }
                   11435:   }
1.281     brouard  11436:   else if (argc<=2){
                   11437:     strcpy(pathtot,argv[1]);
                   11438:   }
1.126     brouard  11439:   else{
                   11440:     strcpy(pathtot,argv[1]);
1.281     brouard  11441:     strcpy(z,argv[2]);
                   11442:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  11443:   }
                   11444:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   11445:   /*cygwin_split_path(pathtot,path,optionfile);
                   11446:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   11447:   /* cutv(path,optionfile,pathtot,'\\');*/
                   11448: 
                   11449:   /* Split argv[0], imach program to get pathimach */
                   11450:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   11451:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   11452:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   11453:  /*   strcpy(pathimach,argv[0]); */
                   11454:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   11455:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   11456:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  11457: #ifdef WIN32
                   11458:   _chdir(path); /* Can be a relative path */
                   11459:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   11460: #else
1.126     brouard  11461:   chdir(path); /* Can be a relative path */
1.184     brouard  11462:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   11463: #endif
                   11464:   printf("Current directory %s!\n",pathcd);
1.126     brouard  11465:   strcpy(command,"mkdir ");
                   11466:   strcat(command,optionfilefiname);
                   11467:   if((outcmd=system(command)) != 0){
1.169     brouard  11468:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  11469:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   11470:     /* fclose(ficlog); */
                   11471: /*     exit(1); */
                   11472:   }
                   11473: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   11474: /*     perror("mkdir"); */
                   11475: /*   } */
                   11476: 
                   11477:   /*-------- arguments in the command line --------*/
                   11478: 
1.186     brouard  11479:   /* Main Log file */
1.126     brouard  11480:   strcat(filelog, optionfilefiname);
                   11481:   strcat(filelog,".log");    /* */
                   11482:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   11483:     printf("Problem with logfile %s\n",filelog);
                   11484:     goto end;
                   11485:   }
                   11486:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  11487:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  11488:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   11489:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   11490:  path=%s \n\
                   11491:  optionfile=%s\n\
                   11492:  optionfilext=%s\n\
1.156     brouard  11493:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  11494: 
1.197     brouard  11495:   syscompilerinfo(1);
1.167     brouard  11496: 
1.126     brouard  11497:   printf("Local time (at start):%s",strstart);
                   11498:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   11499:   fflush(ficlog);
                   11500: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  11501: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  11502: 
                   11503:   /* */
                   11504:   strcpy(fileres,"r");
                   11505:   strcat(fileres, optionfilefiname);
1.201     brouard  11506:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  11507:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  11508:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  11509: 
1.186     brouard  11510:   /* Main ---------arguments file --------*/
1.126     brouard  11511: 
                   11512:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  11513:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   11514:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  11515:     fflush(ficlog);
1.149     brouard  11516:     /* goto end; */
                   11517:     exit(70); 
1.126     brouard  11518:   }
                   11519: 
                   11520:   strcpy(filereso,"o");
1.201     brouard  11521:   strcat(filereso,fileresu);
1.126     brouard  11522:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   11523:     printf("Problem with Output resultfile: %s\n", filereso);
                   11524:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   11525:     fflush(ficlog);
                   11526:     goto end;
                   11527:   }
1.278     brouard  11528:       /*-------- Rewriting parameter file ----------*/
                   11529:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   11530:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   11531:   strcat(rfileres,".");    /* */
                   11532:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   11533:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   11534:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   11535:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   11536:     fflush(ficlog);
                   11537:     goto end;
                   11538:   }
                   11539:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  11540: 
1.278     brouard  11541:                                      
1.126     brouard  11542:   /* Reads comments: lines beginning with '#' */
                   11543:   numlinepar=0;
1.277     brouard  11544:   /* Is it a BOM UTF-8 Windows file? */
                   11545:   /* First parameter line */
1.197     brouard  11546:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  11547:     noffset=0;
                   11548:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   11549:     {
                   11550:       noffset=noffset+3;
                   11551:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   11552:     }
1.302     brouard  11553: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   11554:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
1.277     brouard  11555:     {
                   11556:       noffset=noffset+2;
                   11557:       printf("# File is an UTF16BE BOM file\n");
                   11558:     }
                   11559:     else if( line[0] == 0 && line[1] == 0)
                   11560:     {
                   11561:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   11562:        noffset=noffset+4;
                   11563:        printf("# File is an UTF16BE BOM file\n");
                   11564:       }
                   11565:     } else{
                   11566:       ;/*printf(" Not a BOM file\n");*/
                   11567:     }
                   11568:   
1.197     brouard  11569:     /* If line starts with a # it is a comment */
1.277     brouard  11570:     if (line[noffset] == '#') {
1.197     brouard  11571:       numlinepar++;
                   11572:       fputs(line,stdout);
                   11573:       fputs(line,ficparo);
1.278     brouard  11574:       fputs(line,ficres);
1.197     brouard  11575:       fputs(line,ficlog);
                   11576:       continue;
                   11577:     }else
                   11578:       break;
                   11579:   }
                   11580:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   11581:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   11582:     if (num_filled != 5) {
                   11583:       printf("Should be 5 parameters\n");
1.283     brouard  11584:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  11585:     }
1.126     brouard  11586:     numlinepar++;
1.197     brouard  11587:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  11588:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   11589:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   11590:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  11591:   }
                   11592:   /* Second parameter line */
                   11593:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  11594:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   11595:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  11596:     if (line[0] == '#') {
                   11597:       numlinepar++;
1.283     brouard  11598:       printf("%s",line);
                   11599:       fprintf(ficres,"%s",line);
                   11600:       fprintf(ficparo,"%s",line);
                   11601:       fprintf(ficlog,"%s",line);
1.197     brouard  11602:       continue;
                   11603:     }else
                   11604:       break;
                   11605:   }
1.223     brouard  11606:   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", \
                   11607:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   11608:     if (num_filled != 11) {
                   11609:       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  11610:       printf("but line=%s\n",line);
1.283     brouard  11611:       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");
                   11612:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  11613:     }
1.286     brouard  11614:     if( lastpass > maxwav){
                   11615:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   11616:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   11617:       fflush(ficlog);
                   11618:       goto end;
                   11619:     }
                   11620:       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  11621:     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  11622:     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  11623:     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  11624:   }
1.203     brouard  11625:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  11626:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  11627:   /* Third parameter line */
                   11628:   while(fgets(line, MAXLINE, ficpar)) {
                   11629:     /* If line starts with a # it is a comment */
                   11630:     if (line[0] == '#') {
                   11631:       numlinepar++;
1.283     brouard  11632:       printf("%s",line);
                   11633:       fprintf(ficres,"%s",line);
                   11634:       fprintf(ficparo,"%s",line);
                   11635:       fprintf(ficlog,"%s",line);
1.197     brouard  11636:       continue;
                   11637:     }else
                   11638:       break;
                   11639:   }
1.201     brouard  11640:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
1.279     brouard  11641:     if (num_filled != 1){
1.302     brouard  11642:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   11643:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
1.197     brouard  11644:       model[0]='\0';
                   11645:       goto end;
                   11646:     }
                   11647:     else{
                   11648:       if (model[0]=='+'){
                   11649:        for(i=1; i<=strlen(model);i++)
                   11650:          modeltemp[i-1]=model[i];
1.201     brouard  11651:        strcpy(model,modeltemp); 
1.197     brouard  11652:       }
                   11653:     }
1.199     brouard  11654:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  11655:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  11656:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   11657:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   11658:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  11659:   }
                   11660:   /* 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); */
                   11661:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   11662:   /* 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  11663:   /* 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); */
                   11664:   /* 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  11665:   fflush(ficlog);
1.190     brouard  11666:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   11667:   if(model[0]=='#'){
1.279     brouard  11668:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   11669:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   11670:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  11671:     if(mle != -1){
1.279     brouard  11672:       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  11673:       exit(1);
                   11674:     }
                   11675:   }
1.126     brouard  11676:   while((c=getc(ficpar))=='#' && c!= EOF){
                   11677:     ungetc(c,ficpar);
                   11678:     fgets(line, MAXLINE, ficpar);
                   11679:     numlinepar++;
1.195     brouard  11680:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   11681:       z[0]=line[1];
                   11682:     }
                   11683:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  11684:     fputs(line, stdout);
                   11685:     //puts(line);
1.126     brouard  11686:     fputs(line,ficparo);
                   11687:     fputs(line,ficlog);
                   11688:   }
                   11689:   ungetc(c,ficpar);
                   11690: 
                   11691:    
1.290     brouard  11692:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   11693:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   11694:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
                   11695:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /**< Time varying covariate (dummy and quantitative)*/
1.136     brouard  11696:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   11697:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   11698:      v1+v2*age+v2*v3 makes cptcovn = 3
                   11699:   */
                   11700:   if (strlen(model)>1) 
1.187     brouard  11701:     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  11702:   else
1.187     brouard  11703:     ncovmodel=2; /* Constant and age */
1.133     brouard  11704:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   11705:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  11706:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   11707:     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);
                   11708:     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);
                   11709:     fflush(stdout);
                   11710:     fclose (ficlog);
                   11711:     goto end;
                   11712:   }
1.126     brouard  11713:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   11714:   delti=delti3[1][1];
                   11715:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   11716:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  11717: /* We could also provide initial parameters values giving by simple logistic regression 
                   11718:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   11719:       /* for(i=1;i<nlstate;i++){ */
                   11720:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   11721:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   11722:       /* } */
1.126     brouard  11723:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  11724:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   11725:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  11726:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   11727:     fclose (ficparo);
                   11728:     fclose (ficlog);
                   11729:     goto end;
                   11730:     exit(0);
1.220     brouard  11731:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  11732:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  11733:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   11734:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  11735:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   11736:     matcov=matrix(1,npar,1,npar);
1.203     brouard  11737:     hess=matrix(1,npar,1,npar);
1.220     brouard  11738:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  11739:     /* Read guessed parameters */
1.126     brouard  11740:     /* Reads comments: lines beginning with '#' */
                   11741:     while((c=getc(ficpar))=='#' && c!= EOF){
                   11742:       ungetc(c,ficpar);
                   11743:       fgets(line, MAXLINE, ficpar);
                   11744:       numlinepar++;
1.141     brouard  11745:       fputs(line,stdout);
1.126     brouard  11746:       fputs(line,ficparo);
                   11747:       fputs(line,ficlog);
                   11748:     }
                   11749:     ungetc(c,ficpar);
                   11750:     
                   11751:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  11752:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  11753:     for(i=1; i <=nlstate; i++){
1.234     brouard  11754:       j=0;
1.126     brouard  11755:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  11756:        if(jj==i) continue;
                   11757:        j++;
1.292     brouard  11758:        while((c=getc(ficpar))=='#' && c!= EOF){
                   11759:          ungetc(c,ficpar);
                   11760:          fgets(line, MAXLINE, ficpar);
                   11761:          numlinepar++;
                   11762:          fputs(line,stdout);
                   11763:          fputs(line,ficparo);
                   11764:          fputs(line,ficlog);
                   11765:        }
                   11766:        ungetc(c,ficpar);
1.234     brouard  11767:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   11768:        if ((i1 != i) || (j1 != jj)){
                   11769:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  11770: It might be a problem of design; if ncovcol and the model are correct\n \
                   11771: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  11772:          exit(1);
                   11773:        }
                   11774:        fprintf(ficparo,"%1d%1d",i1,j1);
                   11775:        if(mle==1)
                   11776:          printf("%1d%1d",i,jj);
                   11777:        fprintf(ficlog,"%1d%1d",i,jj);
                   11778:        for(k=1; k<=ncovmodel;k++){
                   11779:          fscanf(ficpar," %lf",&param[i][j][k]);
                   11780:          if(mle==1){
                   11781:            printf(" %lf",param[i][j][k]);
                   11782:            fprintf(ficlog," %lf",param[i][j][k]);
                   11783:          }
                   11784:          else
                   11785:            fprintf(ficlog," %lf",param[i][j][k]);
                   11786:          fprintf(ficparo," %lf",param[i][j][k]);
                   11787:        }
                   11788:        fscanf(ficpar,"\n");
                   11789:        numlinepar++;
                   11790:        if(mle==1)
                   11791:          printf("\n");
                   11792:        fprintf(ficlog,"\n");
                   11793:        fprintf(ficparo,"\n");
1.126     brouard  11794:       }
                   11795:     }  
                   11796:     fflush(ficlog);
1.234     brouard  11797:     
1.251     brouard  11798:     /* Reads parameters values */
1.126     brouard  11799:     p=param[1][1];
1.251     brouard  11800:     pstart=paramstart[1][1];
1.126     brouard  11801:     
                   11802:     /* Reads comments: lines beginning with '#' */
                   11803:     while((c=getc(ficpar))=='#' && c!= EOF){
                   11804:       ungetc(c,ficpar);
                   11805:       fgets(line, MAXLINE, ficpar);
                   11806:       numlinepar++;
1.141     brouard  11807:       fputs(line,stdout);
1.126     brouard  11808:       fputs(line,ficparo);
                   11809:       fputs(line,ficlog);
                   11810:     }
                   11811:     ungetc(c,ficpar);
                   11812: 
                   11813:     for(i=1; i <=nlstate; i++){
                   11814:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  11815:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   11816:        if ( (i1-i) * (j1-j) != 0){
                   11817:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   11818:          exit(1);
                   11819:        }
                   11820:        printf("%1d%1d",i,j);
                   11821:        fprintf(ficparo,"%1d%1d",i1,j1);
                   11822:        fprintf(ficlog,"%1d%1d",i1,j1);
                   11823:        for(k=1; k<=ncovmodel;k++){
                   11824:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   11825:          printf(" %le",delti3[i][j][k]);
                   11826:          fprintf(ficparo," %le",delti3[i][j][k]);
                   11827:          fprintf(ficlog," %le",delti3[i][j][k]);
                   11828:        }
                   11829:        fscanf(ficpar,"\n");
                   11830:        numlinepar++;
                   11831:        printf("\n");
                   11832:        fprintf(ficparo,"\n");
                   11833:        fprintf(ficlog,"\n");
1.126     brouard  11834:       }
                   11835:     }
                   11836:     fflush(ficlog);
1.234     brouard  11837:     
1.145     brouard  11838:     /* Reads covariance matrix */
1.126     brouard  11839:     delti=delti3[1][1];
1.220     brouard  11840:                
                   11841:                
1.126     brouard  11842:     /* 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  11843:                
1.126     brouard  11844:     /* Reads comments: lines beginning with '#' */
                   11845:     while((c=getc(ficpar))=='#' && c!= EOF){
                   11846:       ungetc(c,ficpar);
                   11847:       fgets(line, MAXLINE, ficpar);
                   11848:       numlinepar++;
1.141     brouard  11849:       fputs(line,stdout);
1.126     brouard  11850:       fputs(line,ficparo);
                   11851:       fputs(line,ficlog);
                   11852:     }
                   11853:     ungetc(c,ficpar);
1.220     brouard  11854:                
1.126     brouard  11855:     matcov=matrix(1,npar,1,npar);
1.203     brouard  11856:     hess=matrix(1,npar,1,npar);
1.131     brouard  11857:     for(i=1; i <=npar; i++)
                   11858:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  11859:                
1.194     brouard  11860:     /* Scans npar lines */
1.126     brouard  11861:     for(i=1; i <=npar; i++){
1.226     brouard  11862:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  11863:       if(count != 3){
1.226     brouard  11864:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  11865: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   11866: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  11867:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  11868: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   11869: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  11870:        exit(1);
1.220     brouard  11871:       }else{
1.226     brouard  11872:        if(mle==1)
                   11873:          printf("%1d%1d%d",i1,j1,jk);
                   11874:       }
                   11875:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   11876:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  11877:       for(j=1; j <=i; j++){
1.226     brouard  11878:        fscanf(ficpar," %le",&matcov[i][j]);
                   11879:        if(mle==1){
                   11880:          printf(" %.5le",matcov[i][j]);
                   11881:        }
                   11882:        fprintf(ficlog," %.5le",matcov[i][j]);
                   11883:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  11884:       }
                   11885:       fscanf(ficpar,"\n");
                   11886:       numlinepar++;
                   11887:       if(mle==1)
1.220     brouard  11888:                                printf("\n");
1.126     brouard  11889:       fprintf(ficlog,"\n");
                   11890:       fprintf(ficparo,"\n");
                   11891:     }
1.194     brouard  11892:     /* End of read covariance matrix npar lines */
1.126     brouard  11893:     for(i=1; i <=npar; i++)
                   11894:       for(j=i+1;j<=npar;j++)
1.226     brouard  11895:        matcov[i][j]=matcov[j][i];
1.126     brouard  11896:     
                   11897:     if(mle==1)
                   11898:       printf("\n");
                   11899:     fprintf(ficlog,"\n");
                   11900:     
                   11901:     fflush(ficlog);
                   11902:     
                   11903:   }    /* End of mle != -3 */
1.218     brouard  11904:   
1.186     brouard  11905:   /*  Main data
                   11906:    */
1.290     brouard  11907:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   11908:   /* num=lvector(1,n); */
                   11909:   /* moisnais=vector(1,n); */
                   11910:   /* annais=vector(1,n); */
                   11911:   /* moisdc=vector(1,n); */
                   11912:   /* andc=vector(1,n); */
                   11913:   /* weight=vector(1,n); */
                   11914:   /* agedc=vector(1,n); */
                   11915:   /* cod=ivector(1,n); */
                   11916:   /* for(i=1;i<=n;i++){ */
                   11917:   num=lvector(firstobs,lastobs);
                   11918:   moisnais=vector(firstobs,lastobs);
                   11919:   annais=vector(firstobs,lastobs);
                   11920:   moisdc=vector(firstobs,lastobs);
                   11921:   andc=vector(firstobs,lastobs);
                   11922:   weight=vector(firstobs,lastobs);
                   11923:   agedc=vector(firstobs,lastobs);
                   11924:   cod=ivector(firstobs,lastobs);
                   11925:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  11926:     num[i]=0;
                   11927:     moisnais[i]=0;
                   11928:     annais[i]=0;
                   11929:     moisdc[i]=0;
                   11930:     andc[i]=0;
                   11931:     agedc[i]=0;
                   11932:     cod[i]=0;
                   11933:     weight[i]=1.0; /* Equal weights, 1 by default */
                   11934:   }
1.290     brouard  11935:   mint=matrix(1,maxwav,firstobs,lastobs);
                   11936:   anint=matrix(1,maxwav,firstobs,lastobs);
1.325     brouard  11937:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */
                   11938:   printf("BUG ncovmodel=%d NCOVMAX=%d 2**ncovmodel=%f BUG\n",ncovmodel,NCOVMAX,pow(2,ncovmodel));
1.126     brouard  11939:   tab=ivector(1,NCOVMAX);
1.144     brouard  11940:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  11941:   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  11942: 
1.136     brouard  11943:   /* Reads data from file datafile */
                   11944:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   11945:     goto end;
                   11946: 
                   11947:   /* Calculation of the number of parameters from char model */
1.234     brouard  11948:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  11949:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   11950:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   11951:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   11952:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  11953:   */
                   11954:   
                   11955:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   11956:   TvarsDind=ivector(1,NCOVMAX); /*  */
                   11957:   TvarsD=ivector(1,NCOVMAX); /*  */
                   11958:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   11959:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  11960:   TvarF=ivector(1,NCOVMAX); /*  */
                   11961:   TvarFind=ivector(1,NCOVMAX); /*  */
                   11962:   TvarV=ivector(1,NCOVMAX); /*  */
                   11963:   TvarVind=ivector(1,NCOVMAX); /*  */
                   11964:   TvarA=ivector(1,NCOVMAX); /*  */
                   11965:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  11966:   TvarFD=ivector(1,NCOVMAX); /*  */
                   11967:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   11968:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   11969:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   11970:   TvarVD=ivector(1,NCOVMAX); /*  */
                   11971:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   11972:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   11973:   TvarVQind=ivector(1,NCOVMAX); /*  */
                   11974: 
1.230     brouard  11975:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  11976:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  11977:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   11978:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   11979:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.137     brouard  11980:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   11981:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   11982:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   11983:   */
                   11984:   /* For model-covariate k tells which data-covariate to use but
                   11985:     because this model-covariate is a construction we invent a new column
                   11986:     ncovcol + k1
                   11987:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   11988:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  11989:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   11990:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  11991:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   11992:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  11993:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  11994:   */
1.145     brouard  11995:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   11996:   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  11997:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   11998:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  11999:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  12000:                         4 covariates (3 plus signs)
                   12001:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   12002:                      */  
1.230     brouard  12003:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  12004:                                * individual dummy, fixed or varying:
                   12005:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   12006:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  12007:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   12008:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   12009:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   12010:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   12011:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  12012:                                * individual quantitative, fixed or varying:
                   12013:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   12014:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   12015:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.186     brouard  12016: /* Main decodemodel */
                   12017: 
1.187     brouard  12018: 
1.223     brouard  12019:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  12020:     goto end;
                   12021: 
1.137     brouard  12022:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   12023:     nbwarn++;
                   12024:     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); 
                   12025:     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); 
                   12026:   }
1.136     brouard  12027:     /*  if(mle==1){*/
1.137     brouard  12028:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   12029:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  12030:   }
                   12031: 
                   12032:     /*-calculation of age at interview from date of interview and age at death -*/
                   12033:   agev=matrix(1,maxwav,1,imx);
                   12034: 
                   12035:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   12036:     goto end;
                   12037: 
1.126     brouard  12038: 
1.136     brouard  12039:   agegomp=(int)agemin;
1.290     brouard  12040:   free_vector(moisnais,firstobs,lastobs);
                   12041:   free_vector(annais,firstobs,lastobs);
1.126     brouard  12042:   /* free_matrix(mint,1,maxwav,1,n);
                   12043:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  12044:   /* free_vector(moisdc,1,n); */
                   12045:   /* free_vector(andc,1,n); */
1.145     brouard  12046:   /* */
                   12047:   
1.126     brouard  12048:   wav=ivector(1,imx);
1.214     brouard  12049:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   12050:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   12051:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   12052:   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.*/
                   12053:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   12054:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  12055:    
                   12056:   /* Concatenates waves */
1.214     brouard  12057:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   12058:      Death is a valid wave (if date is known).
                   12059:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   12060:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   12061:      and mw[mi+1][i]. dh depends on stepm.
                   12062:   */
                   12063: 
1.126     brouard  12064:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  12065:   /* Concatenates waves */
1.145     brouard  12066:  
1.290     brouard  12067:   free_vector(moisdc,firstobs,lastobs);
                   12068:   free_vector(andc,firstobs,lastobs);
1.215     brouard  12069: 
1.126     brouard  12070:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   12071:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   12072:   ncodemax[1]=1;
1.145     brouard  12073:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  12074:   cptcoveff=0;
1.220     brouard  12075:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
                   12076:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.227     brouard  12077:   }
                   12078:   
                   12079:   ncovcombmax=pow(2,cptcoveff);
                   12080:   invalidvarcomb=ivector(1, ncovcombmax); 
                   12081:   for(i=1;i<ncovcombmax;i++)
                   12082:     invalidvarcomb[i]=0;
                   12083:   
1.211     brouard  12084:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  12085:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  12086:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  12087:   
1.200     brouard  12088:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  12089:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  12090:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  12091:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   12092:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   12093:    * (currently 0 or 1) in the data.
                   12094:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   12095:    * corresponding modality (h,j).
                   12096:    */
                   12097: 
1.145     brouard  12098:   h=0;
                   12099:   /*if (cptcovn > 0) */
1.126     brouard  12100:   m=pow(2,cptcoveff);
                   12101:  
1.144     brouard  12102:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  12103:           * For k=4 covariates, h goes from 1 to m=2**k
                   12104:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   12105:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.186     brouard  12106:           *     h\k   1     2     3     4
1.143     brouard  12107:           *______________________________  
                   12108:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   12109:           *     2     2     1     1     1
                   12110:           *     3 i=2 1     2     1     1
                   12111:           *     4     2     2     1     1
                   12112:           *     5 i=3 1 i=2 1     2     1
                   12113:           *     6     2     1     2     1
                   12114:           *     7 i=4 1     2     2     1
                   12115:           *     8     2     2     2     1
1.197     brouard  12116:           *     9 i=5 1 i=3 1 i=2 1     2
                   12117:           *    10     2     1     1     2
                   12118:           *    11 i=6 1     2     1     2
                   12119:           *    12     2     2     1     2
                   12120:           *    13 i=7 1 i=4 1     2     2    
                   12121:           *    14     2     1     2     2
                   12122:           *    15 i=8 1     2     2     2
                   12123:           *    16     2     2     2     2
1.143     brouard  12124:           */
1.212     brouard  12125:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  12126:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   12127:      * and the value of each covariate?
                   12128:      * V1=1, V2=1, V3=2, V4=1 ?
                   12129:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   12130:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   12131:      * In order to get the real value in the data, we use nbcode
                   12132:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   12133:      * We are keeping this crazy system in order to be able (in the future?) 
                   12134:      * to have more than 2 values (0 or 1) for a covariate.
                   12135:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   12136:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   12137:      *              bbbbbbbb
                   12138:      *              76543210     
                   12139:      *   h-1        00000101 (6-1=5)
1.219     brouard  12140:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  12141:      *           &
                   12142:      *     1        00000001 (1)
1.219     brouard  12143:      *              00000000        = 1 & ((h-1) >> (k-1))
                   12144:      *          +1= 00000001 =1 
1.211     brouard  12145:      *
                   12146:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   12147:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   12148:      *    >>k'            11
                   12149:      *          &   00000001
                   12150:      *            = 00000001
                   12151:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   12152:      * Reverse h=6 and m=16?
                   12153:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   12154:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   12155:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   12156:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   12157:      * V3=decodtabm(14,3,2**4)=2
                   12158:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   12159:      *(h-1) >> (j-1)    0011 =13 >> 2
                   12160:      *          &1 000000001
                   12161:      *           = 000000001
                   12162:      *         +1= 000000010 =2
                   12163:      *                  2211
                   12164:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   12165:      *                  V3=2
1.220     brouard  12166:                 * codtabm and decodtabm are identical
1.211     brouard  12167:      */
                   12168: 
1.145     brouard  12169: 
                   12170:  free_ivector(Ndum,-1,NCOVMAX);
                   12171: 
                   12172: 
1.126     brouard  12173:     
1.186     brouard  12174:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  12175:   strcpy(optionfilegnuplot,optionfilefiname);
                   12176:   if(mle==-3)
1.201     brouard  12177:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  12178:   strcat(optionfilegnuplot,".gp");
                   12179: 
                   12180:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   12181:     printf("Problem with file %s",optionfilegnuplot);
                   12182:   }
                   12183:   else{
1.204     brouard  12184:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  12185:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  12186:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   12187:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  12188:   }
                   12189:   /*  fclose(ficgp);*/
1.186     brouard  12190: 
                   12191: 
                   12192:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  12193: 
                   12194:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   12195:   if(mle==-3)
1.201     brouard  12196:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  12197:   strcat(optionfilehtm,".htm");
                   12198:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  12199:     printf("Problem with %s \n",optionfilehtm);
                   12200:     exit(0);
1.126     brouard  12201:   }
                   12202: 
                   12203:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   12204:   strcat(optionfilehtmcov,"-cov.htm");
                   12205:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   12206:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   12207:   }
                   12208:   else{
                   12209:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   12210: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  12211: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  12212:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   12213:   }
                   12214: 
1.324     brouard  12215:   fprintf(fichtm,"<html><head>\n<head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n<title>IMaCh %s</title></head>\n <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n<font size=\"3\">Sponsored by Copyright (C)  2002-2015 <a href=http://www.ined.fr>INED</a>-EUROREVES-Institut de longévité-2013-2016-Japan Society for the Promotion of Sciences 日本学術振興会 (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - <a href=https://software.intel.com/en-us>Intel Software 2015-2018</a></font><br>  \
1.204     brouard  12216: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   12217: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  12218: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  12219: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  12220: \n\
                   12221: <hr  size=\"2\" color=\"#EC5E5E\">\
                   12222:  <ul><li><h4>Parameter files</h4>\n\
                   12223:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   12224:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   12225:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   12226:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   12227:  - Date and time at start: %s</ul>\n",\
                   12228:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   12229:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   12230:          fileres,fileres,\
                   12231:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   12232:   fflush(fichtm);
                   12233: 
                   12234:   strcpy(pathr,path);
                   12235:   strcat(pathr,optionfilefiname);
1.184     brouard  12236: #ifdef WIN32
                   12237:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   12238: #else
1.126     brouard  12239:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  12240: #endif
                   12241:          
1.126     brouard  12242:   
1.220     brouard  12243:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   12244:                 and for any valid combination of covariates
1.126     brouard  12245:      and prints on file fileres'p'. */
1.251     brouard  12246:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  12247:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  12248: 
                   12249:   fprintf(fichtm,"\n");
1.286     brouard  12250:   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  12251:          ftol, stepm);
                   12252:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   12253:   ncurrv=1;
                   12254:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   12255:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   12256:   ncurrv=i;
                   12257:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  12258:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  12259:   ncurrv=i;
                   12260:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  12261:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  12262:   ncurrv=i;
                   12263:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   12264:   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", \
                   12265:           nlstate, ndeath, maxwav, mle, weightopt);
                   12266: 
                   12267:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   12268: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   12269: 
                   12270:   
1.317     brouard  12271:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Number of (used) observations=%d <br>\n\
1.126     brouard  12272: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   12273: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  12274:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  12275:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  12276:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   12277:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   12278:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   12279:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  12280: 
1.126     brouard  12281:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   12282:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   12283:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   12284: 
                   12285:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  12286:   /* For mortality only */
1.126     brouard  12287:   if (mle==-3){
1.136     brouard  12288:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  12289:     for(i=1;i<=NDIM;i++)
                   12290:       for(j=1;j<=NDIM;j++)
                   12291:        ximort[i][j]=0.;
1.186     brouard  12292:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  12293:     cens=ivector(firstobs,lastobs);
                   12294:     ageexmed=vector(firstobs,lastobs);
                   12295:     agecens=vector(firstobs,lastobs);
                   12296:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  12297:                
1.126     brouard  12298:     for (i=1; i<=imx; i++){
                   12299:       dcwave[i]=-1;
                   12300:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  12301:        if (s[m][i]>nlstate) {
                   12302:          dcwave[i]=m;
                   12303:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   12304:          break;
                   12305:        }
1.126     brouard  12306:     }
1.226     brouard  12307:     
1.126     brouard  12308:     for (i=1; i<=imx; i++) {
                   12309:       if (wav[i]>0){
1.226     brouard  12310:        ageexmed[i]=agev[mw[1][i]][i];
                   12311:        j=wav[i];
                   12312:        agecens[i]=1.; 
                   12313:        
                   12314:        if (ageexmed[i]> 1 && wav[i] > 0){
                   12315:          agecens[i]=agev[mw[j][i]][i];
                   12316:          cens[i]= 1;
                   12317:        }else if (ageexmed[i]< 1) 
                   12318:          cens[i]= -1;
                   12319:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   12320:          cens[i]=0 ;
1.126     brouard  12321:       }
                   12322:       else cens[i]=-1;
                   12323:     }
                   12324:     
                   12325:     for (i=1;i<=NDIM;i++) {
                   12326:       for (j=1;j<=NDIM;j++)
1.226     brouard  12327:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  12328:     }
                   12329:     
1.302     brouard  12330:     p[1]=0.0268; p[NDIM]=0.083;
                   12331:     /* printf("%lf %lf", p[1], p[2]); */
1.126     brouard  12332:     
                   12333:     
1.136     brouard  12334: #ifdef GSL
                   12335:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  12336: #else
1.126     brouard  12337:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  12338: #endif
1.201     brouard  12339:     strcpy(filerespow,"POW-MORT_"); 
                   12340:     strcat(filerespow,fileresu);
1.126     brouard  12341:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   12342:       printf("Problem with resultfile: %s\n", filerespow);
                   12343:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   12344:     }
1.136     brouard  12345: #ifdef GSL
                   12346:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  12347: #else
1.126     brouard  12348:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  12349: #endif
1.126     brouard  12350:     /*  for (i=1;i<=nlstate;i++)
                   12351:        for(j=1;j<=nlstate+ndeath;j++)
                   12352:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   12353:     */
                   12354:     fprintf(ficrespow,"\n");
1.136     brouard  12355: #ifdef GSL
                   12356:     /* gsl starts here */ 
                   12357:     T = gsl_multimin_fminimizer_nmsimplex;
                   12358:     gsl_multimin_fminimizer *sfm = NULL;
                   12359:     gsl_vector *ss, *x;
                   12360:     gsl_multimin_function minex_func;
                   12361: 
                   12362:     /* Initial vertex size vector */
                   12363:     ss = gsl_vector_alloc (NDIM);
                   12364:     
                   12365:     if (ss == NULL){
                   12366:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   12367:     }
                   12368:     /* Set all step sizes to 1 */
                   12369:     gsl_vector_set_all (ss, 0.001);
                   12370: 
                   12371:     /* Starting point */
1.126     brouard  12372:     
1.136     brouard  12373:     x = gsl_vector_alloc (NDIM);
                   12374:     
                   12375:     if (x == NULL){
                   12376:       gsl_vector_free(ss);
                   12377:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   12378:     }
                   12379:   
                   12380:     /* Initialize method and iterate */
                   12381:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  12382:     /*     gsl_vector_set(x, 0, 0.0268); */
                   12383:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  12384:     gsl_vector_set(x, 0, p[1]);
                   12385:     gsl_vector_set(x, 1, p[2]);
                   12386: 
                   12387:     minex_func.f = &gompertz_f;
                   12388:     minex_func.n = NDIM;
                   12389:     minex_func.params = (void *)&p; /* ??? */
                   12390:     
                   12391:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   12392:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   12393:     
                   12394:     printf("Iterations beginning .....\n\n");
                   12395:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   12396: 
                   12397:     iteri=0;
                   12398:     while (rval == GSL_CONTINUE){
                   12399:       iteri++;
                   12400:       status = gsl_multimin_fminimizer_iterate(sfm);
                   12401:       
                   12402:       if (status) printf("error: %s\n", gsl_strerror (status));
                   12403:       fflush(0);
                   12404:       
                   12405:       if (status) 
                   12406:         break;
                   12407:       
                   12408:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   12409:       ssval = gsl_multimin_fminimizer_size (sfm);
                   12410:       
                   12411:       if (rval == GSL_SUCCESS)
                   12412:         printf ("converged to a local maximum at\n");
                   12413:       
                   12414:       printf("%5d ", iteri);
                   12415:       for (it = 0; it < NDIM; it++){
                   12416:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   12417:       }
                   12418:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   12419:     }
                   12420:     
                   12421:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   12422:     
                   12423:     gsl_vector_free(x); /* initial values */
                   12424:     gsl_vector_free(ss); /* inital step size */
                   12425:     for (it=0; it<NDIM; it++){
                   12426:       p[it+1]=gsl_vector_get(sfm->x,it);
                   12427:       fprintf(ficrespow," %.12lf", p[it]);
                   12428:     }
                   12429:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   12430: #endif
                   12431: #ifdef POWELL
                   12432:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   12433: #endif  
1.126     brouard  12434:     fclose(ficrespow);
                   12435:     
1.203     brouard  12436:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  12437: 
                   12438:     for(i=1; i <=NDIM; i++)
                   12439:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  12440:                                matcov[i][j]=matcov[j][i];
1.126     brouard  12441:     
                   12442:     printf("\nCovariance matrix\n ");
1.203     brouard  12443:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  12444:     for(i=1; i <=NDIM; i++) {
                   12445:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  12446:                                printf("%f ",matcov[i][j]);
                   12447:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  12448:       }
1.203     brouard  12449:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  12450:     }
                   12451:     
                   12452:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  12453:     for (i=1;i<=NDIM;i++) {
1.126     brouard  12454:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  12455:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   12456:     }
1.302     brouard  12457:     lsurv=vector(agegomp,AGESUP);
                   12458:     lpop=vector(agegomp,AGESUP);
                   12459:     tpop=vector(agegomp,AGESUP);
1.126     brouard  12460:     lsurv[agegomp]=100000;
                   12461:     
                   12462:     for (k=agegomp;k<=AGESUP;k++) {
                   12463:       agemortsup=k;
                   12464:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   12465:     }
                   12466:     
                   12467:     for (k=agegomp;k<agemortsup;k++)
                   12468:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   12469:     
                   12470:     for (k=agegomp;k<agemortsup;k++){
                   12471:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   12472:       sumlpop=sumlpop+lpop[k];
                   12473:     }
                   12474:     
                   12475:     tpop[agegomp]=sumlpop;
                   12476:     for (k=agegomp;k<(agemortsup-3);k++){
                   12477:       /*  tpop[k+1]=2;*/
                   12478:       tpop[k+1]=tpop[k]-lpop[k];
                   12479:     }
                   12480:     
                   12481:     
                   12482:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   12483:     for (k=agegomp;k<(agemortsup-2);k++) 
                   12484:       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]);
                   12485:     
                   12486:     
                   12487:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  12488:                ageminpar=50;
                   12489:                agemaxpar=100;
1.194     brouard  12490:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   12491:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   12492: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12493: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   12494:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   12495: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12496: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  12497:     }else{
                   12498:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   12499:                        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  12500:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  12501:                }
1.201     brouard  12502:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  12503:                     stepm, weightopt,\
                   12504:                     model,imx,p,matcov,agemortsup);
                   12505:     
1.302     brouard  12506:     free_vector(lsurv,agegomp,AGESUP);
                   12507:     free_vector(lpop,agegomp,AGESUP);
                   12508:     free_vector(tpop,agegomp,AGESUP);
1.220     brouard  12509:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  12510:     free_ivector(dcwave,firstobs,lastobs);
                   12511:     free_vector(agecens,firstobs,lastobs);
                   12512:     free_vector(ageexmed,firstobs,lastobs);
                   12513:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  12514: #ifdef GSL
1.136     brouard  12515: #endif
1.186     brouard  12516:   } /* Endof if mle==-3 mortality only */
1.205     brouard  12517:   /* Standard  */
                   12518:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   12519:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   12520:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  12521:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  12522:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   12523:     for (k=1; k<=npar;k++)
                   12524:       printf(" %d %8.5f",k,p[k]);
                   12525:     printf("\n");
1.205     brouard  12526:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   12527:       /* mlikeli uses func not funcone */
1.247     brouard  12528:       /* for(i=1;i<nlstate;i++){ */
                   12529:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   12530:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   12531:       /* } */
1.205     brouard  12532:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   12533:     }
                   12534:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   12535:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   12536:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   12537:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   12538:     }
                   12539:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  12540:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   12541:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   12542:     for (k=1; k<=npar;k++)
                   12543:       printf(" %d %8.5f",k,p[k]);
                   12544:     printf("\n");
                   12545:     
                   12546:     /*--------- results files --------------*/
1.283     brouard  12547:     /* 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  12548:     
                   12549:     
                   12550:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  12551:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); /* Printing model equation */
1.126     brouard  12552:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  12553: 
                   12554:     printf("#model=  1      +     age ");
                   12555:     fprintf(ficres,"#model=  1      +     age ");
                   12556:     fprintf(ficlog,"#model=  1      +     age ");
                   12557:     fprintf(fichtm,"\n<ul><li> model=1+age+%s\n \
                   12558: </ul>", model);
                   12559: 
                   12560:     fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">\n");
                   12561:     fprintf(fichtm, "<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   12562:     if(nagesqr==1){
                   12563:       printf("  + age*age  ");
                   12564:       fprintf(ficres,"  + age*age  ");
                   12565:       fprintf(ficlog,"  + age*age  ");
                   12566:       fprintf(fichtm, "<th>+ age*age</th>");
                   12567:     }
                   12568:     for(j=1;j <=ncovmodel-2;j++){
                   12569:       if(Typevar[j]==0) {
                   12570:        printf("  +      V%d  ",Tvar[j]);
                   12571:        fprintf(ficres,"  +      V%d  ",Tvar[j]);
                   12572:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   12573:        fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   12574:       }else if(Typevar[j]==1) {
                   12575:        printf("  +    V%d*age ",Tvar[j]);
                   12576:        fprintf(ficres,"  +    V%d*age ",Tvar[j]);
                   12577:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   12578:        fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   12579:       }else if(Typevar[j]==2) {
                   12580:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   12581:        fprintf(ficres,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   12582:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   12583:        fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   12584:       }
                   12585:     }
                   12586:     printf("\n");
                   12587:     fprintf(ficres,"\n");
                   12588:     fprintf(ficlog,"\n");
                   12589:     fprintf(fichtm, "</tr>");
                   12590:     fprintf(fichtm, "\n");
                   12591:     
                   12592:     
1.126     brouard  12593:     for(i=1,jk=1; i <=nlstate; i++){
                   12594:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  12595:        if (k != i) {
1.319     brouard  12596:          fprintf(fichtm, "<tr>");
1.225     brouard  12597:          printf("%d%d ",i,k);
                   12598:          fprintf(ficlog,"%d%d ",i,k);
                   12599:          fprintf(ficres,"%1d%1d ",i,k);
1.319     brouard  12600:          fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  12601:          for(j=1; j <=ncovmodel; j++){
                   12602:            printf("%12.7f ",p[jk]);
                   12603:            fprintf(ficlog,"%12.7f ",p[jk]);
                   12604:            fprintf(ficres,"%12.7f ",p[jk]);
1.319     brouard  12605:            fprintf(fichtm, "<td>%12.7f</td>",p[jk]);
1.225     brouard  12606:            jk++; 
                   12607:          }
                   12608:          printf("\n");
                   12609:          fprintf(ficlog,"\n");
                   12610:          fprintf(ficres,"\n");
1.319     brouard  12611:          fprintf(fichtm, "</tr>\n");
1.225     brouard  12612:        }
1.126     brouard  12613:       }
                   12614:     }
1.319     brouard  12615:     /* fprintf(fichtm,"</tr>\n"); */
                   12616:     fprintf(fichtm,"</table>\n");
                   12617:     fprintf(fichtm, "\n");
                   12618: 
1.203     brouard  12619:     if(mle != 0){
                   12620:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  12621:       ftolhess=ftol; /* Usually correct */
1.203     brouard  12622:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   12623:       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");
                   12624:       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  12625:       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  12626:       fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">");
                   12627:       fprintf(fichtm, "\n<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   12628:       if(nagesqr==1){
                   12629:        printf("  + age*age  ");
                   12630:        fprintf(ficres,"  + age*age  ");
                   12631:        fprintf(ficlog,"  + age*age  ");
                   12632:        fprintf(fichtm, "<th>+ age*age</th>");
                   12633:       }
                   12634:       for(j=1;j <=ncovmodel-2;j++){
                   12635:        if(Typevar[j]==0) {
                   12636:          printf("  +      V%d  ",Tvar[j]);
                   12637:          fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   12638:        }else if(Typevar[j]==1) {
                   12639:          printf("  +    V%d*age ",Tvar[j]);
                   12640:          fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   12641:        }else if(Typevar[j]==2) {
                   12642:          fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   12643:        }
                   12644:       }
                   12645:       fprintf(fichtm, "</tr>\n");
                   12646:  
1.203     brouard  12647:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  12648:        for(k=1; k <=(nlstate+ndeath); k++){
                   12649:          if (k != i) {
1.319     brouard  12650:            fprintf(fichtm, "<tr valign=top>");
1.225     brouard  12651:            printf("%d%d ",i,k);
                   12652:            fprintf(ficlog,"%d%d ",i,k);
1.319     brouard  12653:            fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  12654:            for(j=1; j <=ncovmodel; j++){
1.319     brouard  12655:              wald=p[jk]/sqrt(matcov[jk][jk]);
1.324     brouard  12656:              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]));
                   12657:              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  12658:              if(fabs(wald) > 1.96){
1.321     brouard  12659:                fprintf(fichtm, "<td><b>%12.7f</b></br> (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
1.319     brouard  12660:              }else{
                   12661:                fprintf(fichtm, "<td>%12.7f (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
                   12662:              }
1.324     brouard  12663:              fprintf(fichtm,"W=%8.3f</br>",wald);
1.319     brouard  12664:              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  12665:              jk++; 
                   12666:            }
                   12667:            printf("\n");
                   12668:            fprintf(ficlog,"\n");
1.319     brouard  12669:            fprintf(fichtm, "</tr>\n");
1.225     brouard  12670:          }
                   12671:        }
1.193     brouard  12672:       }
1.203     brouard  12673:     } /* end of hesscov and Wald tests */
1.319     brouard  12674:     fprintf(fichtm,"</table>\n");
1.225     brouard  12675:     
1.203     brouard  12676:     /*  */
1.126     brouard  12677:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   12678:     printf("# Scales (for hessian or gradient estimation)\n");
                   12679:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   12680:     for(i=1,jk=1; i <=nlstate; i++){
                   12681:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  12682:        if (j!=i) {
                   12683:          fprintf(ficres,"%1d%1d",i,j);
                   12684:          printf("%1d%1d",i,j);
                   12685:          fprintf(ficlog,"%1d%1d",i,j);
                   12686:          for(k=1; k<=ncovmodel;k++){
                   12687:            printf(" %.5e",delti[jk]);
                   12688:            fprintf(ficlog," %.5e",delti[jk]);
                   12689:            fprintf(ficres," %.5e",delti[jk]);
                   12690:            jk++;
                   12691:          }
                   12692:          printf("\n");
                   12693:          fprintf(ficlog,"\n");
                   12694:          fprintf(ficres,"\n");
                   12695:        }
1.126     brouard  12696:       }
                   12697:     }
                   12698:     
                   12699:     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  12700:     if(mle >= 1) /* To big for the screen */
1.126     brouard  12701:       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");
                   12702:     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");
                   12703:     /* # 121 Var(a12)\n\ */
                   12704:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   12705:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   12706:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   12707:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   12708:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   12709:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   12710:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   12711:     
                   12712:     
                   12713:     /* Just to have a covariance matrix which will be more understandable
                   12714:        even is we still don't want to manage dictionary of variables
                   12715:     */
                   12716:     for(itimes=1;itimes<=2;itimes++){
                   12717:       jj=0;
                   12718:       for(i=1; i <=nlstate; i++){
1.225     brouard  12719:        for(j=1; j <=nlstate+ndeath; j++){
                   12720:          if(j==i) continue;
                   12721:          for(k=1; k<=ncovmodel;k++){
                   12722:            jj++;
                   12723:            ca[0]= k+'a'-1;ca[1]='\0';
                   12724:            if(itimes==1){
                   12725:              if(mle>=1)
                   12726:                printf("#%1d%1d%d",i,j,k);
                   12727:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   12728:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   12729:            }else{
                   12730:              if(mle>=1)
                   12731:                printf("%1d%1d%d",i,j,k);
                   12732:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   12733:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   12734:            }
                   12735:            ll=0;
                   12736:            for(li=1;li <=nlstate; li++){
                   12737:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   12738:                if(lj==li) continue;
                   12739:                for(lk=1;lk<=ncovmodel;lk++){
                   12740:                  ll++;
                   12741:                  if(ll<=jj){
                   12742:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   12743:                    if(ll<jj){
                   12744:                      if(itimes==1){
                   12745:                        if(mle>=1)
                   12746:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12747:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12748:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12749:                      }else{
                   12750:                        if(mle>=1)
                   12751:                          printf(" %.5e",matcov[jj][ll]); 
                   12752:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   12753:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   12754:                      }
                   12755:                    }else{
                   12756:                      if(itimes==1){
                   12757:                        if(mle>=1)
                   12758:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   12759:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   12760:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   12761:                      }else{
                   12762:                        if(mle>=1)
                   12763:                          printf(" %.7e",matcov[jj][ll]); 
                   12764:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   12765:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   12766:                      }
                   12767:                    }
                   12768:                  }
                   12769:                } /* end lk */
                   12770:              } /* end lj */
                   12771:            } /* end li */
                   12772:            if(mle>=1)
                   12773:              printf("\n");
                   12774:            fprintf(ficlog,"\n");
                   12775:            fprintf(ficres,"\n");
                   12776:            numlinepar++;
                   12777:          } /* end k*/
                   12778:        } /*end j */
1.126     brouard  12779:       } /* end i */
                   12780:     } /* end itimes */
                   12781:     
                   12782:     fflush(ficlog);
                   12783:     fflush(ficres);
1.225     brouard  12784:     while(fgets(line, MAXLINE, ficpar)) {
                   12785:       /* If line starts with a # it is a comment */
                   12786:       if (line[0] == '#') {
                   12787:        numlinepar++;
                   12788:        fputs(line,stdout);
                   12789:        fputs(line,ficparo);
                   12790:        fputs(line,ficlog);
1.299     brouard  12791:        fputs(line,ficres);
1.225     brouard  12792:        continue;
                   12793:       }else
                   12794:        break;
                   12795:     }
                   12796:     
1.209     brouard  12797:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   12798:     /*   ungetc(c,ficpar); */
                   12799:     /*   fgets(line, MAXLINE, ficpar); */
                   12800:     /*   fputs(line,stdout); */
                   12801:     /*   fputs(line,ficparo); */
                   12802:     /* } */
                   12803:     /* ungetc(c,ficpar); */
1.126     brouard  12804:     
                   12805:     estepm=0;
1.209     brouard  12806:     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  12807:       
                   12808:       if (num_filled != 6) {
                   12809:        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);
                   12810:        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);
                   12811:        goto end;
                   12812:       }
                   12813:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   12814:     }
                   12815:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   12816:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   12817:     
1.209     brouard  12818:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  12819:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   12820:     if (fage <= 2) {
                   12821:       bage = ageminpar;
                   12822:       fage = agemaxpar;
                   12823:     }
                   12824:     
                   12825:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  12826:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   12827:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  12828:                
1.186     brouard  12829:     /* Other stuffs, more or less useful */    
1.254     brouard  12830:     while(fgets(line, MAXLINE, ficpar)) {
                   12831:       /* If line starts with a # it is a comment */
                   12832:       if (line[0] == '#') {
                   12833:        numlinepar++;
                   12834:        fputs(line,stdout);
                   12835:        fputs(line,ficparo);
                   12836:        fputs(line,ficlog);
1.299     brouard  12837:        fputs(line,ficres);
1.254     brouard  12838:        continue;
                   12839:       }else
                   12840:        break;
                   12841:     }
                   12842: 
                   12843:     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){
                   12844:       
                   12845:       if (num_filled != 7) {
                   12846:        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);
                   12847:        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);
                   12848:        goto end;
                   12849:       }
                   12850:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   12851:       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);
                   12852:       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);
                   12853:       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  12854:     }
1.254     brouard  12855: 
                   12856:     while(fgets(line, MAXLINE, ficpar)) {
                   12857:       /* If line starts with a # it is a comment */
                   12858:       if (line[0] == '#') {
                   12859:        numlinepar++;
                   12860:        fputs(line,stdout);
                   12861:        fputs(line,ficparo);
                   12862:        fputs(line,ficlog);
1.299     brouard  12863:        fputs(line,ficres);
1.254     brouard  12864:        continue;
                   12865:       }else
                   12866:        break;
1.126     brouard  12867:     }
                   12868:     
                   12869:     
                   12870:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   12871:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   12872:     
1.254     brouard  12873:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   12874:       if (num_filled != 1) {
                   12875:        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);
                   12876:        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);
                   12877:        goto end;
                   12878:       }
                   12879:       printf("pop_based=%d\n",popbased);
                   12880:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   12881:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   12882:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   12883:     }
                   12884:      
1.258     brouard  12885:     /* Results */
1.307     brouard  12886:     endishere=0;
1.258     brouard  12887:     nresult=0;
1.308     brouard  12888:     parameterline=0;
1.258     brouard  12889:     do{
                   12890:       if(!fgets(line, MAXLINE, ficpar)){
                   12891:        endishere=1;
1.308     brouard  12892:        parameterline=15;
1.258     brouard  12893:       }else if (line[0] == '#') {
                   12894:        /* If line starts with a # it is a comment */
1.254     brouard  12895:        numlinepar++;
                   12896:        fputs(line,stdout);
                   12897:        fputs(line,ficparo);
                   12898:        fputs(line,ficlog);
1.299     brouard  12899:        fputs(line,ficres);
1.254     brouard  12900:        continue;
1.258     brouard  12901:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   12902:        parameterline=11;
1.296     brouard  12903:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  12904:        parameterline=12;
1.307     brouard  12905:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
1.258     brouard  12906:        parameterline=13;
1.307     brouard  12907:       }
1.258     brouard  12908:       else{
                   12909:        parameterline=14;
1.254     brouard  12910:       }
1.308     brouard  12911:       switch (parameterline){ /* =0 only if only comments */
1.258     brouard  12912:       case 11:
1.296     brouard  12913:        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)){
                   12914:                  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  12915:          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);
                   12916:          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);
                   12917:          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);
                   12918:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  12919:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   12920:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  12921:           prvforecast = 1;
                   12922:        } 
                   12923:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.313     brouard  12924:          printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   12925:          fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   12926:          fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  12927:           prvforecast = 2;
                   12928:        }
                   12929:        else {
                   12930:          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);
                   12931:          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);
                   12932:          goto end;
1.258     brouard  12933:        }
1.254     brouard  12934:        break;
1.258     brouard  12935:       case 12:
1.296     brouard  12936:        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)){
                   12937:           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);
                   12938:          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);
                   12939:          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);
                   12940:          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);
                   12941:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  12942:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   12943:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  12944:           prvbackcast = 1;
                   12945:        } 
                   12946:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.313     brouard  12947:          printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   12948:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   12949:          fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  12950:           prvbackcast = 2;
                   12951:        }
                   12952:        else {
                   12953:          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);
                   12954:          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);
                   12955:          goto end;
1.258     brouard  12956:        }
1.230     brouard  12957:        break;
1.258     brouard  12958:       case 13:
1.307     brouard  12959:        num_filled=sscanf(line,"result:%[^\n]\n",resultline);
                   12960:        nresult++; /* Sum of resultlines */
                   12961:        printf("Result %d: result:%s\n",nresult, resultline);
1.318     brouard  12962:        if(nresult > MAXRESULTLINESPONE-1){
                   12963:          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);
                   12964:          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  12965:          goto end;
                   12966:        }
1.310     brouard  12967:        if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.314     brouard  12968:          fprintf(ficparo,"result: %s\n",resultline);
                   12969:          fprintf(ficres,"result: %s\n",resultline);
                   12970:          fprintf(ficlog,"result: %s\n",resultline);
1.310     brouard  12971:        } else
                   12972:          goto end;
1.307     brouard  12973:        break;
                   12974:       case 14:
                   12975:        printf("Error: Unknown command '%s'\n",line);
                   12976:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
1.314     brouard  12977:        if(line[0] == ' ' || line[0] == '\n'){
                   12978:          printf("It should not be an empty line '%s'\n",line);
                   12979:          fprintf(ficlog,"It should not be an empty line '%s'\n",line);
                   12980:        }         
1.307     brouard  12981:        if(ncovmodel >=2 && nresult==0 ){
                   12982:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   12983:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  12984:        }
1.307     brouard  12985:        /* goto end; */
                   12986:        break;
1.308     brouard  12987:       case 15:
                   12988:        printf("End of resultlines.\n");
                   12989:        fprintf(ficlog,"End of resultlines.\n");
                   12990:        break;
                   12991:       default: /* parameterline =0 */
1.307     brouard  12992:        nresult=1;
                   12993:        decoderesult(".",nresult ); /* No covariate */
1.258     brouard  12994:       } /* End switch parameterline */
                   12995:     }while(endishere==0); /* End do */
1.126     brouard  12996:     
1.230     brouard  12997:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  12998:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  12999:     
                   13000:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  13001:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  13002:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  13003: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13004: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  13005:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  13006: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13007: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  13008:     }else{
1.270     brouard  13009:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  13010:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   13011:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   13012:       if(prvforecast==1){
                   13013:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   13014:         jprojd=jproj1;
                   13015:         mprojd=mproj1;
                   13016:         anprojd=anproj1;
                   13017:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   13018:         jprojf=jproj2;
                   13019:         mprojf=mproj2;
                   13020:         anprojf=anproj2;
                   13021:       } else if(prvforecast == 2){
                   13022:         dateprojd=dateintmean;
                   13023:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   13024:         dateprojf=dateintmean+yrfproj;
                   13025:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   13026:       }
                   13027:       if(prvbackcast==1){
                   13028:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   13029:         jbackd=jback1;
                   13030:         mbackd=mback1;
                   13031:         anbackd=anback1;
                   13032:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   13033:         jbackf=jback2;
                   13034:         mbackf=mback2;
                   13035:         anbackf=anback2;
                   13036:       } else if(prvbackcast == 2){
                   13037:         datebackd=dateintmean;
                   13038:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   13039:         datebackf=dateintmean-yrbproj;
                   13040:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   13041:       }
                   13042:       
                   13043:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);
1.220     brouard  13044:     }
                   13045:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  13046:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   13047:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  13048:                
1.225     brouard  13049:     /*------------ free_vector  -------------*/
                   13050:     /*  chdir(path); */
1.220     brouard  13051:                
1.215     brouard  13052:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   13053:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   13054:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   13055:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  13056:     free_lvector(num,firstobs,lastobs);
                   13057:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  13058:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   13059:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   13060:     fclose(ficparo);
                   13061:     fclose(ficres);
1.220     brouard  13062:                
                   13063:                
1.186     brouard  13064:     /* Other results (useful)*/
1.220     brouard  13065:                
                   13066:                
1.126     brouard  13067:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  13068:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   13069:     prlim=matrix(1,nlstate,1,nlstate);
1.209     brouard  13070:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  13071:     fclose(ficrespl);
                   13072: 
                   13073:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  13074:     /*#include "hpijx.h"*/
                   13075:     hPijx(p, bage, fage);
1.145     brouard  13076:     fclose(ficrespij);
1.227     brouard  13077:     
1.220     brouard  13078:     /* ncovcombmax=  pow(2,cptcoveff); */
1.219     brouard  13079:     /*-------------- Variance of one-step probabilities---*/
1.145     brouard  13080:     k=1;
1.126     brouard  13081:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  13082:     
1.269     brouard  13083:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   13084:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   13085:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  13086:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  13087:        for(k=1;k<=ncovcombmax;k++)
                   13088:          probs[i][j][k]=0.;
1.269     brouard  13089:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   13090:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  13091:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  13092:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   13093:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  13094:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  13095:          for(k=1;k<=ncovcombmax;k++)
                   13096:            mobaverages[i][j][k]=0.;
1.219     brouard  13097:       mobaverage=mobaverages;
                   13098:       if (mobilav!=0) {
1.235     brouard  13099:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  13100:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  13101:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   13102:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   13103:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   13104:        }
1.269     brouard  13105:       } else if (mobilavproj !=0) {
1.235     brouard  13106:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  13107:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  13108:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   13109:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   13110:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   13111:        }
1.269     brouard  13112:       }else{
                   13113:        printf("Internal error moving average\n");
                   13114:        fflush(stdout);
                   13115:        exit(1);
1.219     brouard  13116:       }
                   13117:     }/* end if moving average */
1.227     brouard  13118:     
1.126     brouard  13119:     /*---------- Forecasting ------------------*/
1.296     brouard  13120:     if(prevfcast==1){ 
                   13121:       /*   /\*    if(stepm ==1){*\/ */
                   13122:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   13123:       /*This done previously after freqsummary.*/
                   13124:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   13125:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   13126:       
                   13127:       /* } else if (prvforecast==2){ */
                   13128:       /*   /\*    if(stepm ==1){*\/ */
                   13129:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   13130:       /* } */
                   13131:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   13132:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  13133:     }
1.269     brouard  13134: 
1.296     brouard  13135:     /* Prevbcasting */
                   13136:     if(prevbcast==1){
1.219     brouard  13137:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   13138:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   13139:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   13140: 
                   13141:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   13142: 
                   13143:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  13144: 
1.219     brouard  13145:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   13146:       fclose(ficresplb);
                   13147: 
1.222     brouard  13148:       hBijx(p, bage, fage, mobaverage);
                   13149:       fclose(ficrespijb);
1.219     brouard  13150: 
1.296     brouard  13151:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   13152:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   13153:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   13154:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   13155:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   13156:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   13157: 
                   13158:       
1.269     brouard  13159:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  13160: 
                   13161:       
1.269     brouard  13162:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  13163:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   13164:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   13165:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  13166:     }    /* end  Prevbcasting */
1.268     brouard  13167:  
1.186     brouard  13168:  
                   13169:     /* ------ Other prevalence ratios------------ */
1.126     brouard  13170: 
1.215     brouard  13171:     free_ivector(wav,1,imx);
                   13172:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   13173:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   13174:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  13175:                
                   13176:                
1.127     brouard  13177:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  13178:                
1.201     brouard  13179:     strcpy(filerese,"E_");
                   13180:     strcat(filerese,fileresu);
1.126     brouard  13181:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   13182:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   13183:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   13184:     }
1.208     brouard  13185:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   13186:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  13187: 
                   13188:     pstamp(ficreseij);
1.219     brouard  13189:                
1.235     brouard  13190:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   13191:     if (cptcovn < 1){i1=1;}
                   13192:     
                   13193:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   13194:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  13195:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  13196:        continue;
1.219     brouard  13197:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  13198:       printf("\n#****** ");
1.225     brouard  13199:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  13200:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  13201:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   13202:       }
                   13203:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   13204:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   13205:        fprintf(ficreseij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
1.219     brouard  13206:       }
                   13207:       fprintf(ficreseij,"******\n");
1.235     brouard  13208:       printf("******\n");
1.219     brouard  13209:       
                   13210:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   13211:       oldm=oldms;savm=savms;
1.235     brouard  13212:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  13213:       
1.219     brouard  13214:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  13215:     }
                   13216:     fclose(ficreseij);
1.208     brouard  13217:     printf("done evsij\n");fflush(stdout);
                   13218:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  13219: 
1.218     brouard  13220:                
1.227     brouard  13221:     /*---------- State-specific expectancies and variances ------------*/
1.218     brouard  13222:                
1.201     brouard  13223:     strcpy(filerest,"T_");
                   13224:     strcat(filerest,fileresu);
1.127     brouard  13225:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   13226:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   13227:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   13228:     }
1.208     brouard  13229:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   13230:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  13231:     strcpy(fileresstde,"STDE_");
                   13232:     strcat(fileresstde,fileresu);
1.126     brouard  13233:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  13234:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   13235:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  13236:     }
1.227     brouard  13237:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   13238:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  13239: 
1.201     brouard  13240:     strcpy(filerescve,"CVE_");
                   13241:     strcat(filerescve,fileresu);
1.126     brouard  13242:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  13243:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   13244:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  13245:     }
1.227     brouard  13246:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   13247:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  13248: 
1.201     brouard  13249:     strcpy(fileresv,"V_");
                   13250:     strcat(fileresv,fileresu);
1.126     brouard  13251:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   13252:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   13253:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   13254:     }
1.227     brouard  13255:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   13256:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  13257: 
1.235     brouard  13258:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   13259:     if (cptcovn < 1){i1=1;}
                   13260:     
                   13261:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   13262:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  13263:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  13264:        continue;
1.321     brouard  13265:       printf("\n# model %s \n#****** Result for:", model);
                   13266:       fprintf(ficrest,"\n# model %s \n#****** Result for:", model);
                   13267:       fprintf(ficlog,"\n# model %s \n#****** Result for:", model);
1.227     brouard  13268:       for(j=1;j<=cptcoveff;j++){ 
                   13269:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   13270:        fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   13271:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   13272:       }
1.235     brouard  13273:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   13274:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   13275:        fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   13276:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   13277:       }        
1.208     brouard  13278:       fprintf(ficrest,"******\n");
1.227     brouard  13279:       fprintf(ficlog,"******\n");
                   13280:       printf("******\n");
1.208     brouard  13281:       
                   13282:       fprintf(ficresstdeij,"\n#****** ");
                   13283:       fprintf(ficrescveij,"\n#****** ");
1.225     brouard  13284:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  13285:        fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   13286:        fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.208     brouard  13287:       }
1.235     brouard  13288:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   13289:        fprintf(ficresstdeij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   13290:        fprintf(ficrescveij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   13291:       }        
1.208     brouard  13292:       fprintf(ficresstdeij,"******\n");
                   13293:       fprintf(ficrescveij,"******\n");
                   13294:       
                   13295:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  13296:       /* pstamp(ficresvij); */
1.225     brouard  13297:       for(j=1;j<=cptcoveff;j++) 
1.227     brouard  13298:        fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  13299:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   13300:        fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   13301:       }        
1.208     brouard  13302:       fprintf(ficresvij,"******\n");
                   13303:       
                   13304:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   13305:       oldm=oldms;savm=savms;
1.235     brouard  13306:       printf(" cvevsij ");
                   13307:       fprintf(ficlog, " cvevsij ");
                   13308:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  13309:       printf(" end cvevsij \n ");
                   13310:       fprintf(ficlog, " end cvevsij \n ");
                   13311:       
                   13312:       /*
                   13313:        */
                   13314:       /* goto endfree; */
                   13315:       
                   13316:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   13317:       pstamp(ficrest);
                   13318:       
1.269     brouard  13319:       epj=vector(1,nlstate+1);
1.208     brouard  13320:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  13321:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   13322:        cptcod= 0; /* To be deleted */
                   13323:        printf("varevsij vpopbased=%d \n",vpopbased);
                   13324:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  13325:        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  13326:        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 ");
                   13327:        if(vpopbased==1)
                   13328:          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);
                   13329:        else
1.288     brouard  13330:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  13331:        fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
                   13332:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   13333:        fprintf(ficrest,"\n");
                   13334:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  13335:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   13336:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  13337:        for(age=bage; age <=fage ;age++){
1.235     brouard  13338:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  13339:          if (vpopbased==1) {
                   13340:            if(mobilav ==0){
                   13341:              for(i=1; i<=nlstate;i++)
                   13342:                prlim[i][i]=probs[(int)age][i][k];
                   13343:            }else{ /* mobilav */ 
                   13344:              for(i=1; i<=nlstate;i++)
                   13345:                prlim[i][i]=mobaverage[(int)age][i][k];
                   13346:            }
                   13347:          }
1.219     brouard  13348:          
1.227     brouard  13349:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   13350:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   13351:          /* printf(" age %4.0f ",age); */
                   13352:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   13353:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   13354:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   13355:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   13356:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   13357:            }
                   13358:            epj[nlstate+1] +=epj[j];
                   13359:          }
                   13360:          /* printf(" age %4.0f \n",age); */
1.219     brouard  13361:          
1.227     brouard  13362:          for(i=1, vepp=0.;i <=nlstate;i++)
                   13363:            for(j=1;j <=nlstate;j++)
                   13364:              vepp += vareij[i][j][(int)age];
                   13365:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   13366:          for(j=1;j <=nlstate;j++){
                   13367:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   13368:          }
                   13369:          fprintf(ficrest,"\n");
                   13370:        }
1.208     brouard  13371:       } /* End vpopbased */
1.269     brouard  13372:       free_vector(epj,1,nlstate+1);
1.208     brouard  13373:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   13374:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  13375:       printf("done selection\n");fflush(stdout);
                   13376:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  13377:       
1.235     brouard  13378:     } /* End k selection */
1.227     brouard  13379: 
                   13380:     printf("done State-specific expectancies\n");fflush(stdout);
                   13381:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   13382: 
1.288     brouard  13383:     /* variance-covariance of forward period prevalence*/
1.269     brouard  13384:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  13385: 
1.227     brouard  13386:     
1.290     brouard  13387:     free_vector(weight,firstobs,lastobs);
1.227     brouard  13388:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  13389:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   13390:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   13391:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   13392:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  13393:     free_ivector(tab,1,NCOVMAX);
                   13394:     fclose(ficresstdeij);
                   13395:     fclose(ficrescveij);
                   13396:     fclose(ficresvij);
                   13397:     fclose(ficrest);
                   13398:     fclose(ficpar);
                   13399:     
                   13400:     
1.126     brouard  13401:     /*---------- End : free ----------------*/
1.219     brouard  13402:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  13403:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   13404:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  13405:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   13406:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  13407:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  13408:   /* endfree:*/
                   13409:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   13410:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   13411:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.290     brouard  13412:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs);
                   13413:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   13414:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   13415:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  13416:   free_matrix(matcov,1,npar,1,npar);
                   13417:   free_matrix(hess,1,npar,1,npar);
                   13418:   /*free_vector(delti,1,npar);*/
                   13419:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   13420:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  13421:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  13422:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   13423:   
                   13424:   free_ivector(ncodemax,1,NCOVMAX);
                   13425:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   13426:   free_ivector(Dummy,-1,NCOVMAX);
                   13427:   free_ivector(Fixed,-1,NCOVMAX);
1.238     brouard  13428:   free_ivector(DummyV,1,NCOVMAX);
                   13429:   free_ivector(FixedV,1,NCOVMAX);
1.227     brouard  13430:   free_ivector(Typevar,-1,NCOVMAX);
                   13431:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  13432:   free_ivector(TvarsQ,1,NCOVMAX);
                   13433:   free_ivector(TvarsQind,1,NCOVMAX);
                   13434:   free_ivector(TvarsD,1,NCOVMAX);
                   13435:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  13436:   free_ivector(TvarFD,1,NCOVMAX);
                   13437:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  13438:   free_ivector(TvarF,1,NCOVMAX);
                   13439:   free_ivector(TvarFind,1,NCOVMAX);
                   13440:   free_ivector(TvarV,1,NCOVMAX);
                   13441:   free_ivector(TvarVind,1,NCOVMAX);
                   13442:   free_ivector(TvarA,1,NCOVMAX);
                   13443:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  13444:   free_ivector(TvarFQ,1,NCOVMAX);
                   13445:   free_ivector(TvarFQind,1,NCOVMAX);
                   13446:   free_ivector(TvarVD,1,NCOVMAX);
                   13447:   free_ivector(TvarVDind,1,NCOVMAX);
                   13448:   free_ivector(TvarVQ,1,NCOVMAX);
                   13449:   free_ivector(TvarVQind,1,NCOVMAX);
1.230     brouard  13450:   free_ivector(Tvarsel,1,NCOVMAX);
                   13451:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  13452:   free_ivector(Tposprod,1,NCOVMAX);
                   13453:   free_ivector(Tprod,1,NCOVMAX);
                   13454:   free_ivector(Tvaraff,1,NCOVMAX);
                   13455:   free_ivector(invalidvarcomb,1,ncovcombmax);
                   13456:   free_ivector(Tage,1,NCOVMAX);
                   13457:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  13458:   free_ivector(TmodelInvind,1,NCOVMAX);
                   13459:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.227     brouard  13460:   
                   13461:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   13462:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  13463:   fflush(fichtm);
                   13464:   fflush(ficgp);
                   13465:   
1.227     brouard  13466:   
1.126     brouard  13467:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  13468:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   13469:     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  13470:   }else{
                   13471:     printf("End of Imach\n");
                   13472:     fprintf(ficlog,"End of Imach\n");
                   13473:   }
                   13474:   printf("See log file on %s\n",filelog);
                   13475:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  13476:   /*(void) gettimeofday(&end_time,&tzp);*/
                   13477:   rend_time = time(NULL);  
                   13478:   end_time = *localtime(&rend_time);
                   13479:   /* tml = *localtime(&end_time.tm_sec); */
                   13480:   strcpy(strtend,asctime(&end_time));
1.126     brouard  13481:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   13482:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  13483:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  13484:   
1.157     brouard  13485:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   13486:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   13487:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  13488:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   13489: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   13490:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   13491:   fclose(fichtm);
                   13492:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   13493:   fclose(fichtmcov);
                   13494:   fclose(ficgp);
                   13495:   fclose(ficlog);
                   13496:   /*------ End -----------*/
1.227     brouard  13497:   
1.281     brouard  13498: 
                   13499: /* Executes gnuplot */
1.227     brouard  13500:   
                   13501:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  13502: #ifdef WIN32
1.227     brouard  13503:   if (_chdir(pathcd) != 0)
                   13504:     printf("Can't move to directory %s!\n",path);
                   13505:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  13506: #else
1.227     brouard  13507:     if(chdir(pathcd) != 0)
                   13508:       printf("Can't move to directory %s!\n", path);
                   13509:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  13510: #endif 
1.126     brouard  13511:     printf("Current directory %s!\n",pathcd);
                   13512:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   13513:   sprintf(plotcmd,"gnuplot");
1.157     brouard  13514: #ifdef _WIN32
1.126     brouard  13515:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   13516: #endif
                   13517:   if(!stat(plotcmd,&info)){
1.158     brouard  13518:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  13519:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  13520:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  13521:     }else
                   13522:       strcpy(pplotcmd,plotcmd);
1.157     brouard  13523: #ifdef __unix
1.126     brouard  13524:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   13525:     if(!stat(plotcmd,&info)){
1.158     brouard  13526:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  13527:     }else
                   13528:       strcpy(pplotcmd,plotcmd);
                   13529: #endif
                   13530:   }else
                   13531:     strcpy(pplotcmd,plotcmd);
                   13532:   
                   13533:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  13534:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  13535:   strcpy(pplotcmd,plotcmd);
1.227     brouard  13536:   
1.126     brouard  13537:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  13538:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  13539:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  13540:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  13541:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  13542:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  13543:       strcpy(plotcmd,pplotcmd);
                   13544:     }
1.126     brouard  13545:   }
1.158     brouard  13546:   printf(" Successful, please wait...");
1.126     brouard  13547:   while (z[0] != 'q') {
                   13548:     /* chdir(path); */
1.154     brouard  13549:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  13550:     scanf("%s",z);
                   13551: /*     if (z[0] == 'c') system("./imach"); */
                   13552:     if (z[0] == 'e') {
1.158     brouard  13553: #ifdef __APPLE__
1.152     brouard  13554:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  13555: #elif __linux
                   13556:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  13557: #else
1.152     brouard  13558:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  13559: #endif
                   13560:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   13561:       system(pplotcmd);
1.126     brouard  13562:     }
                   13563:     else if (z[0] == 'g') system(plotcmd);
                   13564:     else if (z[0] == 'q') exit(0);
                   13565:   }
1.227     brouard  13566: end:
1.126     brouard  13567:   while (z[0] != 'q') {
1.195     brouard  13568:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  13569:     scanf("%s",z);
                   13570:   }
1.283     brouard  13571:   printf("End\n");
1.282     brouard  13572:   exit(0);
1.126     brouard  13573: }

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